django使用表单作为上下文并使用当前用户保存

时间:2014-09-18 11:34:20

标签: python django forms

我正在建立一个论坛类型的网站,患者可以向医生提问。我对某些想法感到困惑。这是我的问题模型:

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

我创建了一个提问的表单,效果很好。我想要的是,在问题的详细视图中会有答案。

这是我的模型和答案视图:

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

观点是:

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

这里我已将上下文作为表单传递。我也创建了表单,字段为userquestionans_body

现在我要保存ans_body,将user设置为当前用户,将question设置为详细视图中的同一问题。

我被困了。我不知道我在做什么是对的。还有更好的解决方案吗?提前致谢

1 个答案:

答案 0 :(得分:0)

您可以覆盖表单的保存方法,它类似于模型保存方法,例如。

def save(self, commit=True, **kwargs):
    user = kwargs.pop('user')
    self.user = user
    super(Classname, self).save(commit=True)