Reputation: 1516
I am trying to build questionnaire-like app. I have already build the models.py
which look like this:
# models.py
class QuestionSet(models.Model):
name = models.CharField(max_length=100)
description = models.TextField(blank=True)
def __str__(self):
return "{} Question Form".format(self.name)
class Question(models.Model):
q_set = models.ForeignKey(QuestionSet,
on_delete=models.CASCADE,
related_name='questions')
text = models.CharField(max_length=100)
def __str__(self):
return self.text
class Answer(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
related_name='answers')
question = models.ForeignKey(Question)
text = models.CharField(max_length=100)
def __str__(self):
return "Answer to {}".format(self.question)
However I am struggling to come up with the form which would correctly display this on the front-end and then validate the input data.
I've tried displaying question's text from my Question
Model and adding input fields beneath, all of this without using Django Forms. While this might look like it works, it raises raises the problem of data validation and associating data with particular question(hidden field with question id value).
Is there any way where I can create form, with multiple Question
s (all belonging to the same QuestionSet
), which would display read-only field(Question
Model's text field) and associated input field beneath(Answer
Model text field)?
Upvotes: 1
Views: 274
Reputation: 33
You should make a ModelForm for your Answer model. Check out the Django docs on modelforms, it is very simple and the validation will be taken care of automatically based on what you specified in the model.
Upvotes: 1