Django updateView saving another instance instead of updating

*爱你&永不变心* 提交于 2019-12-13 02:48:14

问题


im trying to update my model but it just creates another instance and i cant figure out why. i was under the impression that all i needed was:

class QuestionUpdate(generic.UpdateView):
    model = models.Question
    form_class = QuestionForm

and it would take care of it for me but that doesnt seem to be the case. im in django 1.11 and running python 3.6. Any and all help is appreciated.

models.py

class Question(models.Model):
    class Meta:
        ordering = ['-date_updated']
    # user = models.ForeignKey(User, related_name="question", default='')
    question = models.TextField(unique=False, blank=False, null=False)
    question_html = models.TextField(blank=False, null=False)
    answer = models.TextField(blank=False, null=False)
    answer_html = models.TextField(blank=False,null=False)
    date_created = models.DateTimeField(auto_now=True, null=True)
    date_updated = models.DateTimeField(auto_now=True, null=True)

    def __str__(self):
        return self.question
        # ^ to display an object in the Django admin site and
        # as the value inserted into a template when it displays an object.

    def save(self, *args, **kwargs):
        self.question_html = misaka.html(self.question)
        self.answer_html = misaka.html(self.answer)
        super().save(*args, **kwargs)

views.py

class QuestionUpdate(generic.UpdateView):
    model = models.Question
    form_class = QuestionForm
    # fields = ('question', 'answer')

    def edit_question(self, request, id):
        question = get_object_or_404(Question, id=id)
        form = QuestionForm(request.POST, instance=question)
        if form.is_valid():
            form.save()

forms.py

class QuestionForm(forms.ModelForm):
# your_name = forms.CharField(label='Your name', max_length=100)

    class Meta:
        fields = ("question", 'answer')
        model = models.Question

urls.py

url(r'questionupdate/(?P<pk>\d+)/$', views.QuestionUpdate.as_view(), name='update'),

来源:https://stackoverflow.com/questions/49341267/django-updateview-saving-another-instance-instead-of-updating

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!