Django Not Saving Form Data
I fill the Django form in contact.html file. But form data is not saved in database or another place. There is no error or warning while saving the form data.
Form screenshot:
views.py:
from .forms import CnForm
def contact(request):
template = loader.get_template('contact.html')
form = CnForm(request.POST or None)
if form.is_valid():
form.save()
context = {'form': form }
return HttpResponse(template.render(context, request))
models.py:
from django.db import models
class FModel(models.Model):
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
def __str__(self):
return self.first_name
forms.py:
from django import forms
from .models import FModel
class CnForm(forms.ModelForm):
class Meta:
model = FModel
fields = "__all__"
contact.html:
<div class="contact-container">
<form action = "" method = "post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit">
</form>
</div>
urls.py:
urlpatterns = [
.
.
.
path('contact', views.contact, name='contact'),
]
Your view renders the template before redirecting or clearing the form, but the main issue is that you are not handling POST requests properly.
Django only saves the form if request.method == 'POST' and the form passes validation.
Try this version of your view:
from django.shortcuts import render, redirect
from .forms import CnForm
def contact(request):
if request.method == 'POST':
form = CnForm(request.POST)
if form.is_valid():
form.save()
return redirect('contact') # optional redirect to avoid resubmission
else:
form = CnForm()
return render(request, 'contact.html', {'form': form})
Always check
request.methodbefore creating the form.When you don’t do that, the form gets initialized with
request.POSTeven for GET requests, soform.is_valid()will fail silently.Using
redirect()after save prevents duplicate submissions when refreshing the page.
Add this in your HTML to make sure you see errors if any field fails validation:
<form method="post">
{% csrf_token %}
{{ form.as_p }}
{{ form.errors }}
<input type="submit" value="Submit">
</form>
Now if validation fails, you’ll see error messages directly on the page.