I have this:
class OrderForm(ModelForm):
class Meta:
model = Order
ex开发者_开发技巧clude = ('number',)
def __init__(self, *args, **kwargs):
super(OrderForm, self).__init__(*args, **kwargs)
if self.initial.get('account', None):
self.fields['customer'].queryset = Customer.objects.filter(account=self.initial.get('account'))
def save(self, force_insert=False, force_update=False, commit=True):
m = super(OrderForm, self).save(commit=False)
# my custom code was here
if commit:
m.save()
return m
That works, except I need to set the "number" attribute of "Order" (which is required) to a certain number. I don't know how to do it. I tried adding:
self.fields['number'] = 50
inside the "save()" method, but I still get an IntegrityError when click save (obviously that's not the correct syntax but it hints at what I'm trying to do). Another problem I encountered to make matters worse is that I cannot even access the fields['number'] now because it's in the exclude Meta attribute (I don't want people to be able to edit it, or for it to be an ).
Should I be doing this in my model's "save()" method instead, or perhaps in the "init()"?
This seems like it would be cleaner in the model. This would be the syntax in model's save method:
def save(self, force_insert=False, force_update=False):
self.number = 50
super(Order, self).save(force_insert, force_update)
If you're really going to set it every time like that, then you can declare it right in the Order model as:
class Order(models.Model):
number = models.IntegerField(default=50)
I would think that this is the sort of thing you should do in the "clean" method. The django form-validation docs are here. Essentially it will give you a dictionary of cleaned fields and then allows you to do more complicated validation that requires the info from numerous fields. The you can return the dictionary of the corrected data ... including anything that you need to add or override.
If you include the model's code then we could help a little more.
you could have just put
m.number = 50
Where you have
# my custom code was here
self.fields
is a list of fields, not their values. If you want to access the values, use self.cleaned_data
. This doesn't help you in self.save()
though, use m.number
because m
is the instance that was created.
精彩评论