如何将表单模型中的数据获取到 Django 中的数据库中

卡尔劳森

我正在尝试从模型表单中获取数据,然后将其放入数据库中。我已经弄清楚如何制作表单,但是当单击提交按钮时,它似乎没有放在我的数据库中的任何位置。我做错了什么还是我没有在数据库中找正确的地方。

表格

from django import forms
from sxsw.models import Account

class AccountForm(forms.ModelForm):
    class Meta:
        model = Account
        fields = ['firstName', 'lastName', 'email']

views.py

from django.shortcuts import render
from django.shortcuts import redirect
from .forms import AccountForm
from .models import Account 

def sxsw(request):
    if request.method == 'POST':
        form = AccountForm(request.POST)
        if form.is_valid():
            form.save()
        else:
            print form.errors
    else:
        form = AccountForm()

    return render(request, 'sxsw/sxsw.html', {'form': form})

def formSubmitted(request):
    return render(request, 'sxsw/formSubmitted.html',{})

models.py

from __future__ import unicode_literals

from django.db import models

# Create your models here.

class Account(models.Model):
    firstName = models.CharField(max_length = 50)
    lastName = models.CharField(max_length = 50)
    email = models.EmailField()

    def __unicode__(self):
        return self.firstName

class Module(models.Model):
    author = models.ForeignKey(Account, on_delete = models.CASCADE)
    nameOfModule = models.CharField(max_length = 150) #arbitrary number
    moduleFile = models.FileField(upload_to = 'uploads/')#Not exactly sure about the upload_to thing
    public = models.BooleanField()

    def __unicode__(self):
        return self.nameOfModule

sxsw.html

{% extends "base.html" %}

{% block content %}
    <div class="container-fluid">
        <div class="jumbotron text-center">
          <h3>SXSW Form</h3> 
        </div>

    </div>

    <div align="center">
        <h1>New Form</h1>
        <form role='form' action="/sxsw/formSubmitted/" method="post">
            {% csrf_token %}
            {{ form.as_p }}
            <button type="submit">Submit</button>
        </form>
    </div>


  </div>
{% endblock %}

表单提交.html

{% extends "base.html" %}

{% block content %}
    <div class="container-fluid">
        <div class="jumbotron text-center">
          <h3>Form Successfully submitted</h3> 
        </div>

    </div>

    <div align="center">
        <a href="{% url 'sxsw' %}" class="btn">Submit Another Response</a>
    </div>


  </div>
{% endblock %}
赛斯

您的表单发布到我认为是错误的网址

 <form role='form' action="/sxsw/formSubmitted/" method="post">

应该使用 sxsw 视图的 url

 <form role='form' action="/sxsw/" method="post">

提交后,您可能希望重定向到提交的视图

 return redirect('/sxsw/formSubmitted/')  # Preferably use the url pattern name here

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章