I have a model in django that is as below:
class Student(Model):
nationality = CharField(max_length=200)
I have a form as below:
class StudentForm(ModelForm):
class Meta:
model = Student
fields = ('nationality', )
my template is as below:
<form method="GET" novalidate id="my_form">
{{ student_form.as_p }}
</form>
<button type="submit" form="my_form" name="my_form">Submit</button>
I have a view as below:
def home(request):
if request.POST:
return HttpResponse('This should never happen')
else:
if request.GET.get('nationality'):
student_form = StudentForm(request.GET)
if student_form.is_valid():
return HttpResponse('get from form submission')
else:
student_form = StudentForm()
print('get from client request')
return render(request, my_template, {'student_form': student_form})
The problem with this method is that if sb submits the form without filling the nationality field, the result would be 'get from client request' that is wrong because the validation error should happen because the request is from submitting a form not direct client get request. What I can do is that I add a hidden field to my form as below:
<form method="GET" novalidate id="my_form">
{{ student_form.as_p }}
<input type="hidden" id="hidden" name="hidden" value="hidden">
</form>
<button type="submit" form="my_form" name="my_form">Submit</button>
and change my view as below:
def home(request):
if request.POST:
return HttpResponse('This should never happen')
else:
if request.GET.get('hidden'):
student_form = StudentForm(request.GET)
if student_form.is_valid():
return HttpResponse('get from form submission')
else:
student_form = StudentForm()
print('get from client request')
return render(request, my_template, {'student_form': student_form})
However, there should be another method to do this. There should be something in HTTP to tell us the request is fresh get request from client or it is from form submission. I am looking for this.