I am trying to fill a field in a forms.ModelForm
using a query based on a forms.Form
. Unfortunately I am getting an AttributeError
that suggests the field doesn't exist, and I'm not sure why this is.
The error is AttributeError: 'ElectionSuggestionForm' object has no attribute 'PostElection'
Here is the views.py:
def new_post(request):
if request.method == 'POST':
form = NewPostForm(request.POST)
election_form = ElectionSuggestionForm(request.user, request.POST)
if form.is_valid():
post = form.save(commit=False)
post.author = Candidate.objects.get(UserID=request.user, ElectionID=election_form.PostElection)
post.save()
return redirect('/feed/')
else:
form = NewPostForm()
election_form = ElectionSuggestionForm(request.user)
return render(request, 'campaign/new_post.html', {
"form": form,
"election_form": election_form,
})
Here is the forms.py:
class ElectionSuggestionForm(forms.Form):
PostElection = forms.ModelChoiceField(queryset=None)
def __init__(self, user, *args, **kwargs):
super(ElectionSuggestionForm, self).__init__(*args, **kwargs)
print(Election.objects.all().filter(candidate__UserID=user))
self.fields['PostElection'].queryset = Election.objects.all().filter(candidate__UserID=user)
Thanks