I have a web page with 3 forms each with their own submit button. On the second form I’m trying to implement a botcatcher by creating a hidden field and checking it’s length. I can’t seem to get this to work. To test the code I use chrome developer tools and add a value attribute to the hidden field and then submit the page. Here are the relevant files:
form_page.html
<!DOCTYPE html>
{% load static %}
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="{% static 'basicapp/style.css' %}">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" >
<title>Forms</title>
</head>
<body>
<h2>welcome to our first form</h2>
<div class="container">
<div class="jumbotron">
<form name='form001' method="post">
{% csrf_token %}
{{ form.as_p }}
<input type='submit' class="btn btn-primary" name='whichForm' value="Submit">
</form>
</div>
<div class='jumbotron'>
<form method="post">
{% csrf_token %}
{{ form1.as_p }}
<input type='submit' class="btn btn-primary" name='whichForm' value="Submit1">
</form>
</div>
<div class='jumbotron'>
<form method="post">
{% csrf_token %}
{{ form2.as_p }}
<input type='submit' class="btn btn-primary" name='whichForm' value="Submit2">
</form>
</div>
</div>
</body>
</html>
views.py
from django.shortcuts import render
from . import forms
# Create your views here.
def index(request):
return render(request,'basicapp/index.html')
def myform_view(request):
form = forms.MyForm()
form1 = forms.MyForm1()
form2 = forms.MyForm2()
if request.method == 'POST':
if request.POST['whichForm'] == 'Submit':
temp = forms.MyForm(request.POST)
elif request.POST['whichForm'] == 'Submit1':
temp = forms.MyForm1(request.POST)
elif request.POST['whichForm'] == 'Submit2':
temp = forms.MyForm2(request.POST)
if form.is_valid():
print("VALIDATION SUCCESS!")
print("NAME: " + temp.cleaned_data['name'])
print("EMAIL: " + temp.cleaned_data['email'])
print("TEXT: " + temp.cleaned_data['text'])
return render(request,'basicapp/form_page.html',{'form':form,
'form1':form1,
'form2':form2})
forms.py
from django import forms
class MyForm(forms.Form):
name = forms.CharField()
email = forms.EmailField()
text = forms.CharField(widget=forms.Textarea)
class MyForm1(forms.Form):
name = forms.CharField()
email = forms.EmailField()
text = forms.CharField(widget=forms.Textarea)
botcatcher =forms.CharField(required=False,widget=forms.HiddenInput)
def clean_botcatcher(self):
botcatcher = self.cleaned_data['botcatcher']
if len(botcatcher) > 0:
raise forms.ValidationError("GOTCHA BOT!")
return botcatcher
class MyForm2(forms.Form):
name = forms.CharField()
email = forms.EmailField()
text = forms.CharField(widget=forms.Textarea)