我试图更新我的模型,但它只是创建另一个实例,我无法找出原因。我的印象是我所需要的只是:
class QuestionUpdate(generic.UpdateView):
model = models.Question
form_class = QuestionForm
它会照顾我,但似乎并非如此。 我在django 1.11和运行python 3.6。任何和所有的帮助表示赞赏。
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'),