form_valid后对象未更新

时间:2017-07-23 01:11:16

标签: python django django-models django-forms

我有QuestionReply

创建Reply后,我想将相关Question的属性设置为new_replies = True。在使用通用CreateView / a表单创建Reply对象后,应该进行此切换。

我可以在提交表单后立即更新对象,但刷新页面会使更新消失。我认为这是因为更新没有保存到数据库

Models.py

class Reply(models.Model):
    parent_question = models.ForeignKey(Question, null=True) 

class Question(models.Model):
    new_replies = models.BooleanField(default=False)

Views.py

class ReplyCreate(CreateView):
"""
creates a comment object
"""
model = Reply #specify which model can be created here
fields = ['content', ] # which fields can be openly editted

...

def form_valid(self, form):
    """
    add associate blog and author to form.
    """
    #this is setting the author of the form
    form.instance.author = self.request.user.useredus

    #associate comment with Question based on passed
    parent_question = get_object_or_404(Question, pk= self.kwargs['pk'])
    form.instance.parent_question = parent_question

    response = super(ReplyCreate, self).form_valid(form)

    # PROBLEM: not being saved to dB?
    parent_question.new_replies = True  # inform the question there are new replies
    parent_question.save()

    return response

def get_success_url(self):
    return reverse('edus:question_detail', kwargs={'pk': self.kwargs['pk'], })

0 个答案:

没有答案