我想在保存ModelForm时将BooleanField inuse
设置为True(我在管理区域之外使用表单),我不确定该怎么做。
型号:
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)
形式:
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()
查看:
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,
})
已更新至最新版(请参阅Manoj Govindan's answer)。提交/保存时仍未将inuse
更新为True。
答案 0 :(得分:3)
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()
答案 1 :(得分:2)
这是我的抨击:
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
location.save()
<强>更新强>
我用过的所有代码:
# models.py
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.py
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
location.save()
In [1]: from test_app.forms import BookingForm
In [2]: from test_app.models import Location
# I had already saved some `Location` instances.
In [3]: data = dict(name = 'MyCity', place = [p.id for p in Location.objects.all()])
In [4]: f = BookingForm(data)
In [5]: f.save()
In [6]: for each in Location.objects.all():
...: print each.place, each.inuse
...:
PlaceA True
PlaceB True
PlaceC True