我创建了一个Form
,用户在其中设置了一个Alarm
对象。Alarm
对象按预期保存到数据库中。但是,问题是:另一个对象,它只包含Form
中完成的信息,也保存到数据库中。
据我了解,form_valid()
CreateView
保存表单。我已经尝试了另一个查询中建议的两种解决方案,但没有成功。我怀疑该问题是由return super().form_valid(form)
或create_alarm_object()
中的Alarm.objects.create()
引起的。
Views.py
class AlarmCreateView(LoginRequiredMixin, CreateView):
""" CreateView for User to create the Alarm object """
model = Alarm
form_class = SetAlarmForm
template_name = 'weather_alarm/set_alarm.html'
login_url = "/login/"
def form_valid(self, form):
self.create_alarm_object(request, form)
return super().form_valid(form)
def get_success_url(self, **kwargs):
return reverse("weather_alarm:active-alarm", kwargs={'pk':self.object.pk})
def create_alarm_object(self, request, form):
""" Function to get User's location from IP and create Alarm object """
...
alarm_object = Alarm.objects.create(
alarm_id=uuid.uuid4(),
user=self.request.user,
timezone=user_timezone,
city=location.raw['address']['city'],
country=location.raw['address']['country'],
time=form.cleaned_data['time'].astimezone(pytz.timezone(user_timezone)),
temp_conditional=form.cleaned_data['temp_conditional'],
surf_conditional=form.cleaned_data['surf_conditional'],
temp_max=form.cleaned_data['temp_max'],
temp_min=form.cleaned_data['temp_min'],
surf_max=form.cleaned_data['surf_max'],
surf_min=form.cleaned_data['surf_min'],
)
alarm_object.save()
你已经调试正确了。super
调用form_valid
和方法create_alarm_object
正在创建两个对象。
正如您在form_valid方法实现中看到的那样,它保存表单并使用success_url
返回一个HttpResponseRedirect
对象。
不要重写form_valid
方法,或者使用以下代码。
解决方案:
def form_valid(self, form):
self.create_alarm_object(self.request, form)
return HttpResponseRedirect(self.get_success_url())
编辑:
更新create_alarm_object
方法以设置self.object
并删除多余的save
调用。
def create_alarm_object(self, request, form):
self.object = Alarm.objects.create(...)
# no `save` call needed, `create` already creates and returns the saved object.