I'm trying to use Django signals in my application but the post_save
signal is sending two times, and the post_delete
is sending once like it's supposed to.
My signals.py:
@receiver([post_save,post_delete], sender=Award)
def print_request(sender, **kwargs):
print('Request finished!')
The result in my terminal when I save an object:
Request finished!
Request finished!
My 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)
My form.py
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',
})
}
答案 0 :(得分:2)
当您致电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)