Django更新视图已保存但未更新

时间:2020-04-21 16:46:41

标签: django django-models django-forms django-views

我已经制作了一份工作表格来发布餐厅评论。
用户登录后,可以看到帖子下方显示了“编辑”按钮。
但是,当我使用Updateview时,它不会进行编辑,而是创建一个新行,其中会出现新评论(并且该新行不会再出现在我的网页上)。
这是模型:

class UserReview(models.Model):
    # Defining the possible grades
    Grade_1 = 1
    Grade_2 = 2
    Grade_3 = 3
    Grade_4 = 4
    Grade_5 = 5
    # All those grades will sit under Review_Grade to appear in choices
    Review_Grade = (
        (1, '1 - Not satisfied'),
        (2, '2 - Almost satisfied'),
        (3, '3 - Satisfied'),
        (4, '4 - Very satisfied'),
        (5, '5 - Exceptionally satisfied')
    )
    restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE)
    user_review_grade = models.IntegerField(default=None, choices=Review_Grade) # default=None pour eviter d'avoir un bouton vide sur ma template
    user_review_comment = models.CharField(max_length=1500)
    posted_by = models.ForeignKey(User, on_delete=models.DO_NOTHING)
    def get_absolute_url(self):
        return reverse('restaurants:reviews', args=[self.id])

    def get_edit_url(self):
        return reverse('restaurants:edit-review', args=(self.id,))

这是更新表格(类似于评论表格):

class EditReviewForm(forms.ModelForm):
    class Meta:
        model = UserReview
        fields = [
            'restaurant',
            'user_review_grade',
            'user_review_comment'
        ]
        widgets = {
            'restaurant': forms.HiddenInput,
            'user_review_grade': forms.RadioSelect,
            'user_review_comment': forms.Textarea
        }
        labels = {
            'user_review_grade': 'Chose a satisfaction level:',
            'user_review_comment': 'And write your comments:'
        }

这是UpdateView:

class EditReview (LoginRequiredMixin, UpdateView):
    template_name = 'restaurants/review_edit.html'
    form_class = EditReviewForm
    model = UserReview
    slug = 'review'
    # Post the data into the DB
    def post(self, request, pk, *args, **kwargs):
        form = UserReviewForm(request.POST)
        restaurant = get_object_or_404(Restaurant, pk=pk)
        if form.is_valid():
            edit_review = form.save(commit=False)
            form.instance.posted_by = self.request.user
            print(edit_review)  # Print so I can see in cmd prompt that something posts as it should
            edit_review.save()
            return HttpResponseRedirect(reverse_lazy('restaurants:details', args=[restaurant.id]))
        return render(request, 'restaurants/details.html', {'form': form})

您对可能出什么问题有任何想法吗? 谢谢:)

1 个答案:

答案 0 :(得分:1)

在更新视图中,您忘记了将对象实例添加到表单中。

html, body { 
    margin: 0;
    height: 100% !important; 
}

.body { 
    margin: 0;
    font-family: Roboto, "Helvetica Neue", sans-serif;
    background-color:#fafafa;
}

.body{
    overflow-x: hidden;
}