Home > Blockchain >  Saving new model overrides existing model
Saving new model overrides existing model

Time:01-17

I have a form that I am using to create new models, but every time I submit the form, it overrides the only existing model in the database.

My form view:

class createItinerary(CreateView):
    template = "create.html"
    form_class = CreateItineraryForm

    def get(self, request, *args, **kwargs):
        form = self.form_class()
        return render(request, self.template, {"form": form})

    def post(self, request, *args, **kwargs):
        super().__init__(*args, **kwargs)
        form = self.form_class(request.POST)

        if form.is_valid():
            destination = form.cleaned_data.get("destination")
            trip_length = form.cleaned_data.get("trip_length")
            start = form.cleaned_data.get("start")
            end = form.cleaned_data.get("end")
            sights = form.cleaned_data.get("sights")

            new = Itinerary(destination=destination,
                trip_length=trip_length, start=start, end=end)

            new.sights.set(sights)
            new.save()

            return redirect("/")
        else:
            form = CreateItineraryForm

        return render(request, self.template, {"form" : form})

My forms.py:

from django import forms
from django.forms.widgets import *
from itineraries.models import Itinerary
from sights.models import Sight

sight_choices = ()

for sight in Sight.objects.all():
    new_sight = (("%s" % sight.name, "%s" % sight.name))
    sight_choices  = new_sight

class CreateItineraryForm(forms.ModelForm):
    class Meta:
        model = Itinerary
        exclude = []

    destination = forms.CharField(label="Destination", max_length=100)
    start = forms.DateField(widget=NumberInput(attrs={"type" : "date"}))
    end = forms.DateField(widget=NumberInput(attrs={"type" : "date"}))

    sights = forms.ModelMultipleChoiceField(
        queryset=Sight.objects.all())

My models.py:

from django.db import models
from sights.models import Sight
import datetime

class Itinerary(models.Model):
    id = models.AutoField(primary_key=True, default=0)
    destination = models.CharField(max_length=100, null=False)
    trip_length = models.IntegerField(null=False)
    start = models.DateField()
    end = models.DateField()
    sights = models.ManyToManyField(Sight)

    def __str__(self):
        trip_name = "%s in %s days" % (self.destination, self.trip_length)
        return trip_name

This is the only existing model in the database: enter image description here

When I use the form to save a new one:

enter image description here

It replaces the old model with the newly created one every time.

CodePudding user response:

Remove default=0 from id in your model.

  • Related