Alan Tingey Alan Tingey - 1 year ago 105
Python Question

Django Form Failure

I have the following form:

# coding=utf-8

class SelectTwoTeams(BootstrapForm):

def __init__(self, *args, **kwargs):
user = kwargs.pop('user', None)
self.currentSelectedTeam1 = kwargs.pop('currentSelectedTeam1', None)
self.currentSelectedTeam2 = kwargs.pop('currentSelectedTeam2', None)
self.currentfixturematchday = kwargs.pop('currentfixturematchday', None)
self.currentCampaignNo = kwargs.pop('currentCampaignNo', None)
super(SelectTwoTeams, self).__init__(*args, **kwargs)

cantSelectTeams = UserSelection.objects.select_related().filter(~Q(fixtureid__fixturematchday=self.currentfixturematchday),campaignno=self.currentCampaignNo)

if not cantSelectTeams:
queryset = StraightredTeam.objects.filter(currentteam = 1)
queryset = StraightredTeam.objects.filter(currentteam = 1).exclude(teamid__in=cantSelectTeams.values_list('teamselectionid', flat=True))

self.fields['team1'].queryset = queryset
self.fields['team2'].queryset = queryset
self.fields['team1'].initial = self.currentSelectedTeam1
self.fields['team2'].initial = self.currentSelectedTeam2

team1 = forms.ModelChoiceField(queryset=StraightredTeam.objects.none(), empty_label=None,
widget=forms.Select(attrs={"class":"select-format",'onchange': 'this.form.submit();'}))
team2 = forms.ModelChoiceField(queryset=StraightredTeam.objects.none(), empty_label=None,
widget=forms.Select(attrs={"class":"select-format",'onchange': 'this.form.submit();'}))

def clean(self):
cleaned_data = self.cleaned_data # individual field's clean methods have already been called
team1 = cleaned_data.get("team1")
team2 = cleaned_data.get("team2")
if team1 == team2:
raise forms.ValidationError("You picked the same team!")

return cleaned_data

If I use the following in my HTML file and choose the same two teams it correctly says "You Picked the same team!":

<form action="" method="post">
{% csrf_token %}
{{ form }}

However, if I use the following:

<form action="" method="post">
{% csrf_token %}
{{ form.team1 }}{{ form.team2 }}

I get no feedback. Nothing occurs when I choose the same two teams. Any idea as to why separating the fields stops it from working?

Many thanks, Alan.

Answer Source

The difference between those is not "separating the fields". It is that you have switched from the full form representation - including form labels, layout, and most importantly errors - to only displaying the two input fields themselves.

That's fine to do of course, as for most purposes you will want the extra layout control that it gives you, but you do need to remember to put in all the other things that the basic {{ form }} version does.

{{ form.non_field_errors }}
{{ form.team1.label_tag }}{{ form.team1 }}{{ form.team1.errors }}
{{ form.team2.label_tag }}{{ form.team2 }}{{ form.team2.errors }}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download