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.
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.
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.
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 .
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With