I have the following models:
class Answer(models.Model):
review = models.ForeignKey(Review,related_name='answer_review_assoc',blank=False,on_delete=models.PROTECT)
question=models.OneToOneField(Question,related_name='answer_question_assoc',blank=False,on_delete=models.PROTECT)
answer=models.CharField(max_length=250,blank=True,null=True)
creation_date=models.DateTimeField(blank=False)
last_update_date=models.DateTimeField(auto_now=True)
created_by=models.ForeignKey(settings.AUTH_USER_MODEL, related_name='answers_created_by',on_delete=models.PROTECT)
last_update_by=models.ForeignKey(settings.AUTH_USER_MODEL, related_name='answers_last_update_by',on_delete=models.PROTECT)
class Meta:
verbose_name_plural = "Answers"
class Question(models.Model):
question_text=models.CharField(max_length=200,blank=False)
question_choice_type=models.CharField(max_length=3, blank=False,choices=QUESTION_CHOICE_TYPE)
mandatory=models.BooleanField(blank=True)
creation_date=models.DateTimeField(blank=False)
last_update_date=models.DateTimeField(auto_now=True)
series_type=models.CharField(max_length=3,blank=True,null=True,choices = Series.get_choices_models()['series_type'])
created_by=models.ForeignKey(settings.AUTH_USER_MODEL, related_name='questions_created_by',on_delete=models.PROTECT)
last_update_by=models.ForeignKey(settings.AUTH_USER_MODEL, related_name='question_last_update_by',on_delete=models.PROTECT)
choices=models.ManyToManyField(Choice,blank=True,related_name='question_choices_assoc')
question_type=models.CharField(max_length=10, blank=False,choices=QUESTION_TYPE)
Form:
class AnswerForm(ModelForm):
answer = forms.CharField(label='Answer Text',required=True,widget=forms.TextInput(attrs={'placeholder': 'Answer Text','class':'form-control'}))
class Meta:
model=Answer
fields=['answer']
def __init__(self, *args, **kwargs):
super(AnswerForm, self).__init__(*args, **kwargs)
# question_text=self.instance.question.question_text
# print(question_text)
I want to create formset of Answer and initialize with some questions This is what I do:
q=Question.objects.filter(question_type='PL').first()
ansfs=formset_factory(AnswerForm)
fs=ansfs(initial=[].append({'question':q}))
Now what i want is to set the label of the answer
field in AnswerForm
to question_text
coming from initial values.
But i am unable to access self.instance.question.question_text
in __init__
method of AnswerForm
.
models.Answer.Answer.question.RelatedObjectDoesNotExist: Answer has no question.
Please advise