代码之家  ›  专栏  ›  技术社区  ›  Diogo Silva

Django信号发送两次

  •  0
  • Diogo Silva  · 技术社区  · 6 年前

    我试图在我的应用程序中使用django信号,但是 post_save 信号发送了两次, post_delete 就像它应该发送的一样。

    我的信号.py:

    @receiver([post_save,post_delete], sender=Award)
    def print_request(sender, **kwargs):
        print('Request finished!')
    

    在我的终端中保存对象时的结果:

    Request finished!
    Request finished!
    

    我的CreateView:

    class ResearcherPrizeCreateView(LoginRequiredMixin, CreateView):
        model = Award
        form_class = ResearcherPrizeCreateForm
        success_url = reverse_lazy('prize_list')
        template_name = 'researcher/award/award_create_form.html'
    
        def form_valid(self, form):
            researcher = Researcher.objects.get(user_id=self.request.user.id)
            self.object = form.save(commit=False)
            self.object.researcher = researcher
            self.object.save()
            return super(ResearcherPrizeCreateView, self).form_valid(form)
    

    我的表格

    class ResearcherPrizeCreateForm(forms.ModelForm):
        class Meta:
            model = Award
            fields = ('title', 'category')
    
            widgets = {
                'title':forms.TextInput(attrs={
                    'class':'form-control',
                    'placeholder':'Titulo da Premiação'
            }),
                'category':forms.Select(attrs={
                    'class':'form-control',                
            })
        }
    
    1 回复  |  直到 6 年前
        1
  •  2
  •   Alasdair    6 年前

    调用时对象将被保存一次 self.object.save() ,当你打电话时 super().form_valid(form) .

    一种方法是在 form_valid 方法。

    def form_valid(self, form):
        researcher = Researcher.objects.get(user_id=self.request.user.id)
        self.object = form.save(commit=False)
        self.object.researcher = researcher
        self.object.save()
        return redirect(self.success_url)
    

    另一种选择是将研究者分配给表单实例,然后调用 super(...).form_valid() 保存表单并重定向。

    def form_valid(self, form):
        researcher = Researcher.objects.get(user_id=self.request.user.id)
        form.instance.researcher = researcher
        return super(ResearcherPrizeCreateView, self).form_valid(form)