I'm making a forum kind of site where a patient can ask a question to doctors. And I'm confused about some idea. Here is my Question model:
class Question(models.Model):
user = models.ForeignKey(User)
title = models.CharField(max_length=120)
description = models.TextField()
category = models.ForeignKey('Category')
answers = models.ManyToManyField('Answer',related_name='answer_name', blank=True)
post_date = models.DateTimeField(auto_now=True)
published = models.BooleanField(default=False)
vote = models.IntegerField() # Field that denotes the no of vote for particular question
def __unicode__(self):
return self.title
I have created a form for asking question and that works well. What I want is that in the detail view of the question there would be the answer.
Here is my model and view for answer:
class Answer(models.Model):
user = models.ForeignKey(User)
question = models.ForeignKey(Question)
ans_body = models.TextField()
comments = models.ManyToManyField('Comment',related_name='answer_name', blank=True)
count = models.IntegerField()
post_date = models.DateTimeField(auto_now=True)
def __unicode__(self):
return self.ans_body
And view is:
class QuestionDetailView(DetailView):
context = {}
model = Question
form_class = AnswerCreationForm
template_name = "question-detail.html"
def get(self, request, pk, **kwargs):
self.pk = pk
print self.pk
return super(QuestionDetailView, self).get(request, pk, **kwargs)
def get_context_data(self, **kwargs):
context = super(QuestionDetailView,self).get_context_data(**kwargs)
context['question'] = Question.objects.get(pk=self.pk)
context['form'] = AnswerCreationForm
return context
Here I have passed context as form. I have created the form too and the fields are user
, question
and ans_body
.
Now I want to save the ans_body
, set user
to the current user and question
to the same question in detail view.
I'm stucked. I don't know what I'm doing is right. Is there any better solution?? Thanks in advance
You can override the save method of form, it similar to the models save method eg.
def save(self, commit=True, **kwargs):
user = kwargs.pop('user')
self.user = user
super(Classname, self).save(commit=True)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.