Form issues
Hi folks,
I've run into trouble with a ModelForm with multiple entries.
I have a Question model that is linked to an election so we can assign
different questions to different races. A separate Answer model is
connected to the Question model and the Candidate model (which is also
tied to a race).
I'm trying to build a form that allows a candidate to answer all
questions associated with his or her race, e.g. Candidate X who is
running for mayor would see a form with three questions for Mayoral
candidates and Candidate Y who is running for the school board would
see three different questions that were assigned to the schools race.
What would be the best way to create this? I've tried playing with
ModelForms, but haven't had any success. Similarly, I've tried
building a FormSet, but can't seem to tie each answer to its
appropriate question.
Here's the related code. Thanks in advance for any help or direction.
- Pat
# MODELS.PY
class Candidate(models.Model):
user = models.OneToOneField(User)
party = models.ForeignKey('Party')
race = models.ForeignKey('Race')
mugshot = models.ImageField(upload_to=uploadMug, null=True,
blank=True)
class Answer(models.Model):
answer = models.CharField(max_length=255, default="No answer
provided.")
candidate = models.ForeignKey('Candidate')
question = models.ForeignKey('Question')
class Question(models.Model):
question = models.CharField(max_length=255)
race = models.ManyToManyField('Race')
class Race(models.Model):
race = models.CharField(max_length=255)
election_date = models.DateField('Election Date', null=True)
active = models.BooleanField()
# VIEWS.PY
@login_required
def update_answers(request):
user = Candidate.objects.get(user__exact=request.user)
question_list = Question.objects.filter(Race__exact=user.race)
for question in question_list:
pass
# I tried writing a function that would serve forms with
appropriate
# candidate/question information, but kept getting NameErrors
if request.method == 'POST':
aForm = UpdateQandA(request.POST, instance=user)
if aForm.is_valid():
aForm.save()
return HttpResponseRedirect('/matchmaker/%d/%s/' %
(user.race.id, user.id))
else:
aForm = UpdateQandA(instance=user)
variables = RequestContext(request, {
'aForm':aForm,
})
return render_to_response('registration/UpdateAnswers.html',
variables)
# FORMS.PY
class UpdateQandA(forms.ModelForm):
answer = forms.CharField(widget = forms.Textarea)
class Meta:
model = Answer
fields = ('question', 'answer',)
--
You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
0 Comments:
Post a Comment
Subscribe to Post Comments [Atom]
<< Home