user6626063 user6626063 - 3 months ago 15
Python Question

My Django form data won't save to my database

I'm trying to get a simple form to save to my MariaDB database but I can't get it to save when I use the form. If I use the Django Admin interface, I can make changes to the database however.

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',)


Any ideas as to why it's not saving to the database?

Answer

Your form action is set to what I assume is the index page also which means its probably not calling that view whatsoever

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

The action here should point to the url that links to that particular view (preferably using the url template tag)

Comments