I have created a Form
, where the User sets an Alarm
object. The Alarm
object saves as expected to the database. However, the issue is that: another object, which contains only the information completed in the Form
, also saves to the database.
As I understand, form_valid()
for CreateView
saves the form. I have tried the two solutions suggested in another query with no success. I suspect that the issue is caused by either return super().form_valid(form)
or by Alarm.objects.create()
in create_alarm_object()
.
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()