【问题标题】:Django receiving duplicate signals when updating content from HTML pageDjango 在从 HTML 页面更新内容时收到重复信号
【发布时间】:2021-09-17 21:33:09
【问题描述】:

从 html 页面更新内容时,我得到了每个内容的重复。看图片:

从 Django 管理面板更新时,我没有得到任何重复。从 HTML 模板更新时如何避免重复?

这是我的代码

我认为我的观点有任何错误。这是我的 views.py

class ApproveCommentPage(UpdateView):
      model = BlogComment
      template_name = "blog/approve_comment.html"
      form_class =AdminComment
     
      def form_valid(self, form):
        self.object = form.save()
        status = self.object.is_published
        name = self.object.name[0:20]
        messages.success(self.request, f"{name} comment status {status}")
        return super().form_valid(form)

#更新问题

这是我的通知.html,其中呈现所有消息:

notifications.html

{% for notification in  notifications  %} 
{%if user.id ==   notification.blog.author.id %}
{% if notification.notification_type == "Comment Approved" %}

 {{ notification.text_preview }}
            
{%endif%}
{%endif%}
{%endfor%}

notification.views.py

def ShowNOtifications(request):
    notifications = Notifications.objects.all().order_by('-date')
    
    template_name ='blog/notifications.html'
     
   

    context = {
        'notifications': notifications,
    }
    print("##############",context)      
    return render(request,template_name,context)

我正在更新评论状态的 html 页面。默认情况下,所有评论状态为“待定”,表示未发布。在这里,我正在查看每条评论并将其状态更改为“已发布”。只有在从这里更改状态时才会重复。 approve_commnet.html

<form  method="POST">
            {% csrf_token %}
            {{form.as_p}}
             
            
            <button class="btn btn-info">Publish</button>
        </form>

从管理面板更新评论状态时,我没有得到任何重复。仅在尝试从approve_commnet.html 更新评论状态时重复。

【问题讨论】:

  • 您能分享一下您呈现消息的模板部分吗?
  • @WillemVanOnsem 我更新了我的问题并描述了细节。请看
  • 但是你在哪里呈现 messages(不是表单),而是你页面上的消息?
  • @WillemVanOnsem 我在 notify.html 中呈现消息。请看上面我标记为粗体的notifications.html。
  • 但是你这里使用的是 Django 的消息框架,但是你用 Notification 渲染它?

标签: django


【解决方案1】:

在您的def form_valid(self, form): 方法中,您将对象保存为self.object = form.save(),当您的逻辑完成后,您返回super().form_valid(form),它实际上再次保存了实例,因此您得到了一个副本。在我看来,最好的解决方案是不要在您的方法中保存对象,让super().form_valid() 为您保存它。第二个,而不是return super().form_valid(form)return super(FormMixin).form_valid(form)

编辑: 我认为最好的解决方案是;

class ApproveCommentPage(UpdateView):
    model = BlogComment
    template_name = "blog/approve_comment.html"
    form_class = AdminComment # Assumed this is a ModelForm
     
    def form_valid(self, form):
        self.object = form.save(commit=False) # this kwarg makes save method not to save it to database.
        status = self.object.is_published
        name = self.object.name[0:20]
        messages.success(self.request, f"{name} comment status {status}")
        return super().form_valid(form)

【讨论】:

  • berkeeb 感谢您的回答。您能否稍微编辑一下您的答案并告诉我需要在我的views.py中编辑的位置。py
猜你喜欢
  • 2017-01-18
  • 2011-04-08
  • 2012-05-09
  • 1970-01-01
  • 2022-11-29
  • 2016-07-16
  • 1970-01-01
  • 2018-04-25
  • 1970-01-01
相关资源
最近更新 更多