我的Django表单数据不会保存到我的数据库中

时间:2016-08-18 12:17:45

标签: python django django-forms mariadb

我试图将一个简单的表单保存到我的MariaDB数据库中,但是当我使用该表单时,我无法保存它。如果我使用Django Admin界面,我可以对数据库进行更改。

addstudent.html

<!DOCTYPE html>
<html>
    <head>
        <title>Add Student</title>
</head>

<body>
    <h1>Add a student</h1>

    <form id="studentform" method="post" action="/add-student/index/">

        {% csrf_token %}
        {% for hidden in form.hidden_fields %}
            {{ hidden }}
        {% endfor %}

        {% for field in form.visible_fields %}
            {{ field.errors }}
            {{ field.help_text }}
            {{ field }}
        {% endfor %}

        <input type="submit" name="submit" value="Create Student" />
    </form>
</body>

views.py *

def addstudent(request):    
    if request.method == 'POST':
        form = studentform(request.POST)
        if form.is_valid():
            form.save(commit=True)
            return index(request)
        else:
            print (form.errors)
    else:
        form = studentform()
    return render(request, 'addstudent/addstudent.html', {'form':form}) 

models.py

class student(models.Model):
    last_name = models.CharField(max_length=70)
    other_names = models.CharField(max_length=70)
    date_of_birth = models.DateField()

forms.py

DOY = ('1980', '1981', '1982', '1983', '1984', '1985', '1986', '1987',
       '1988', '1989', '1990', '1991', '1992', '1993', '1994', '1995',
       '1996', '1997', '1998', '1999', '2000', '2001', '2002', '2003',
       '2004', '2005', '2006', '2007', '2008', '2009', '2010', '2011',
       '2012', '2013', '2014', '2015')

class studentform(forms.ModelForm):
    last_name = forms.CharField(max_length=70, help_text="Last name")
    other_names = forms.CharField(max_length=70, help_text="Other names")
    date_of_birth = forms.DateField(widget = extras.SelectDateWidget(years = DOY ), help_text="Date Of Birth")

    class Meta:
        model = student
        fields = ('last_name', 'other_names', 'date_of_birth',)

关于它为什么不保存到数据库的任何想法?

1 个答案:

答案 0 :(得分:2)

您的表单操作设置为我假设的索引页面,这意味着它可能不会调用该视图

<form id="studentform" method="post" action="/add-student/index/">

此处的操作应指向链接到该特定视图的网址(最好使用url模板标记)