Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple Django form / model save question

I want to set the BooleanField inuse to True when I save the ModelForm (I'm using a form outside of the admin area) and I'm unsure how to do it.

Models:

class Location(models.Model):
    place = models.CharField(max_length=100)
    inuse = models.BooleanField()

class Booking(models.Model):
    name = models.CharField(max_length=100, verbose_name="Your name*:")
    place = models.ManyToManyField(Location, blank=True, null=True)

Forms:

class BookingForm(ModelForm):

    class Meta:
        model = Booking

        def save(self, commit=True):
            booking = super(BookingForm, self).save(commit=False)
            if commit:
                booking.save()
                self.save_m2m()
                for location in booking.place.all():
                    location.inuse = True
                    print location #nothing prints
                    location.save()

View:

def booking(request):
    form = BookingForm()
    if request.method == 'POST':
        form = BookingForm(request.POST)
        if form.is_valid():
            form.save()
        else:
            form = form

        return render_to_response('bookingform.html', {
                'form': form,
            })

Updated to latest (see Manoj Govindan's answer). It is still not updating inuse to True on submit / save.

like image 977
Rob B Avatar asked Sep 06 '10 15:09

Rob B


People also ask

What does save () do in Django?

The save method is an inherited method from models. Model which is executed to save an instance into a particular Model. Whenever one tries to create an instance of a model either from admin interface or django shell, save() function is run.

What is form Save ()?

The save() method Every ModelForm also has a save() method. This method creates and saves a database object from the data bound to the form. A subclass of ModelForm can accept an existing model instance as the keyword argument instance ; if this is supplied, save() will update that instance.

What is form save in Django?

If you want to get rid of re-defining fields in django form then Django model form provides best way to map form with your model and form field will define automatically . Django Provides a helper class which help us to create form class using django model .


1 Answers

class BookingForm(ModelForm):

    class Meta:
        model = Booking

    def save(self, commit=True):
        booking = super(BookingForm, self).save(commit=False)
        booking.inuse = True
        if commit:
            booking.save()
like image 156
Daniel Roseman Avatar answered Sep 30 '22 12:09

Daniel Roseman