I need django modelform with 2 fields, where second field choice list depends on what was chosen in first one. My model:
class Offer(BaseModel):
VEHICLE_TYPES = (
('personal','Personal car'),
('truck','Truck'),
)
vehicle_type = models.CharField(max_length=32, choices=VEHICLE_TYPES, default='personal', verbose_name='Vehicle type')
PERSONAL_MAKES = (
('',''),
)
TRUCK_MAKES = (
('',''),
)
make = models.CharField(max_length=32)#what more??
How can I set choices of make field to PERSONAL_MAKES if vehicle_type is set to personal? How can I do this? Is it possible on model level?
MultipleChoiceField in Django Forms is a Choice field, for input of multiple pairs of values from a field. The default widget for this input is SelectMultiple. It normalizes to a Python list of strings which you one can use for multiple purposes.
Choices limits the input from the user to the particular values specified in models.py . If choices are given, they're enforced by model validation and the default form widget will be a select box with these choices instead of the standard text field.
You would have to add blank=True as well in field definition. If the model field has blank=True, then required is set to False on the form field. Otherwise, required=True. Don't forget to reset and sync DB again after changing this.
To answer your question, with the new migration introduced in Django 1.7, in order to add a new field to a model you can simply add that field to your model and initialize migrations with ./manage.py makemigrations and then run ./manage.py migrate and the new field will be added to your DB.
You probably can't because it depends of user interaction with your form: your server can't know in advance which element your user will select before sending the form to the browser. You could probably achieve this using ajax. I think a working process could be :
make
field hidden
AjaxMakeFieldView
) that will catch an ajax request taking a vehicle_type
argument and return the HTML for make field
, populated with relevant data. Add a URL in your URLConf for this view.vehicle_type
, the browser will send aan ajax request to AjaxMakeFieldView
and replace hidden make
field with returned HTMLIf you don't want javascript, another way would be a two step form :
vehicle_type
fieldmake
field, which initial data is populated depending of vehicle_type
selected in the first form.I've never done this, but Django documentation on Form wizard seems a good place to start.
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