Django 模型选择字段 - 取决于其他字段的选择 [英] Django model choice field - depend on other field's choice
问题描述
我需要带有 2 个字段的 django modelform,其中第二个字段选择列表取决于第一个字段中选择的内容.我的模型:
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??
如果 Vehicle_type 设置为 personal,我如何将 make 字段的选项设置为 PERSONAL_MAKES?我怎样才能做到这一点?在模型级别上可以吗?
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?
推荐答案
您可能不能,因为这取决于用户与您的表单的交互:您的服务器无法提前知道您的用户在发送表单之前将选择哪个元素到浏览器.您可能可以使用 ajax 来实现这一点.我认为一个工作流程可能是:
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
字段 隐藏 - 创建一个视图(我将其称为
AjaxMakeFieldView
),该视图将捕获采用vehicle_type
参数的 ajax 请求并返回make 字段的 HTML代码>,填充相关数据.在您的 URLConf 中为此视图添加一个 URL.
- 在您的模板中,添加一个 Javascript 绑定:当用户选择一个
vehicle_type
时,浏览器将向AjaxMakeFieldView
发送一个 ajax 请求并替换隐藏的make
返回 HTML 的字段
- Create a form with all the fields, and make
make
field hidden - Create a view (I'll call it
AjaxMakeFieldView
) that will catch an ajax request taking avehicle_type
argument and return the HTML formake field
, populated with relevant data. Add a URL in your URLConf for this view. - In your template, add a Javascript binding : when user select a
vehicle_type
, the browser will send aan ajax request toAjaxMakeFieldView
and replace hiddenmake
field with returned HTML
如果您不想要 javascript,另一种方法是两步式:
If you don't want javascript, another way would be a two step form :
- 带有
vehicle_type
字段的第一个表单 - 提交第一个表单后,您的用户将获得带有
make
字段的第二个表单,根据在第一个表单中选择的vehicle_type
填充初始数据.
- A first form with a
vehicle_type
field - Once the first form is submitted, your user get a second form with a
make
field, which initial data is populated depending ofvehicle_type
selected in the first form.
我从未这样做过,但是 Django 文档表单向导似乎是一个不错的起点.
I've never done this, but Django documentation on Form wizard seems a good place to start.
这篇关于Django 模型选择字段 - 取决于其他字段的选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!