I have the following form:
<form action="" method="post">
{% csrf_token %}
<select name="selectTeamOne">
{% for x in currentTeams %}
{% if x.teamid != 66 %}
<option value={{x.teamid}}>{{x.teamname}}</option>
{% endif %}
{% endfor %}
</select>
<select name="selectTeamTwo">
{% for x in currentTeams %}
<option value={{x.teamid}}>{{x.teamname}}</option>
{% endfor %}
</select>
<input type="submit" value="Submit" />
</form>
This is driven by the following view:
def selectteams(request, soccerseason, fixturematchday):
if request.method == 'POST':
if form.is_valid():
return HttpResponse("Two different teams were selected.")
else:
return HttpResponse("Two different teams were not selected.")
fixtures = StraightredFixture.objects.filter(soccerseason=soccerseason,fixturematchday=fixturematchday).order_by('fixturedate')
currentTeams = StraightredTeam.objects.filter(currentteam=1).order_by('teamname')
cantSelectTeams = UserSelection.objects.filter(campaignno=389100069).order_by('campaignno')
return render(request, 'straightred/test.html',
{'fixtures' : fixtures,
'currentTeams' : currentTeams,
'cantSelectTeams' : cantSelectTeams,
'soccerseason' : soccerseason,
'fixturematchday' : fixturematchday})
I just wondered the best way to check if the the user has selected the same team twice from the drop down lists and return the relevant HttpResponse as you can see above.
Any advice to point me in the right direction is appreciated. Many thanks, Alan.
You can enforce server level validation on django forms: https://docs.djangoproject.com/en/dev/ref/forms/validation/#cleaning-and-validating-fields-that-depend-on-each-other
From the docs for django 1.8:
from django import forms
class ContactForm(forms.Form):
# Everything as before.
...
def clean(self):
cleaned_data = super(ContactForm, self).clean()
cc_myself = cleaned_data.get("cc_myself")
subject = cleaned_data.get("subject")
if cc_myself and subject:
# Only do something if both fields are valid so far.
if "help" not in subject:
raise forms.ValidationError(
"Did not send for 'help' in the subject despite "
"CC'ing yourself."
)