user1285716
user1285716

Reputation: 41

default value for ChoiceField in modelform

I have problem with django:
models.py:

SUSPEND_TIME = (
    ('0', '0'),
    ('10', '10'),
    ('15', '15'),
    ('20', '20'),


class Order(models.Model):  
    user = models.ForeignKey(User)  
    city = models.CharField(max_length=20)  
    ...
    processed = models.BooleanField(default=False)
    suspend_time = models.CharField(max_length=2, choices=SUSPEND_TIME, default='0')  
    ..

form.py:

class OrderForm(forms.ModelForm):
    class Meta:
        model = Order
        fields = ('suspend_time', 'processed')

view.py:

        try:
            order = Order.objects.get(id=order_id)
        except Order.DoesNotExist:
            order = None
        else:
            form = OrderForm(request.POST, instance=order)
            if form.is_valid():
            form.save()
            ....  

then I send ajax request to update instance with only "processed" param..
form.is_valid is always False if I don't send "suspend_time" !
if request contain {'suspend_time': 'some_value' ...} form.is_valid is True
I don't understand why ? suspend_time has default value.. and order.suspend_time always has some value: default or other from choices.
why after form = OrderForm(request.POST, instance=order) form['suspend_time'].value() is None, other fields (city, processed) has normal value .

Upvotes: 1

Views: 1884

Answers (1)

Rohan
Rohan

Reputation: 53326

The behavior is as expected. The form should validate with given data. i.e. Whatever required fields are defined in the form, should be present in the data dictionary to instantiate it. It will not use data from instance to populate fields that are not provided in form data.

Text from django model forms

If you’re building a database-driven app, chances are you’ll have forms that map closely to Django models. For instance, you might have a BlogComment model, and you want to create a form that lets people submit comments. In this case, it would be redundant to define the field types in your form, because you’ve already defined the fields in your model.

For this reason, Django provides a helper class that let you create a Form class from a Django model.

Upvotes: 1

Related Questions