Django模型选择领域 - 取决于其他领域的选择 [英] Django model choice field - depend on other field's choice

查看:137
本文介绍了Django模型选择领域 - 取决于其他领域的选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要具有2个字段的django modelform,其中第二个字段选择列表取决于第一个选择列表。我的模型:

  class Offer(BaseModel):

VEHICLE_TYPES =(
个人车),
('卡车','卡车'),

车辆类型= models.CharField(max_length = 32,选择= VEHICLE_TYPES,默认='个人',verbose_name ='车辆类型')

PERSONAL_MAKES =(
('',''),

TRUCK_MAKES =(
',''),

make = models.CharField(max_length = 32)#what更多?

如何将 make 字段的选项设置为 PERSONAL_MAKES 如果vehicle_type设置为个人?我该怎么做?

解决方案

您可能不能因为用户与您的表单的交互:您的服务器可以提前知道您的用户在将表单发送到浏览器之前将选择哪一个元素。你可能可以使用ajax来实现这一点。我认为一个工作过程可能是:




  • 创建一个包含所有字段的表单,并使 make 字段隐藏

  • 创建一个视图(我会称之为 AjaxMakeFieldView ),它将捕获一个ajax请求,采用 vehicle_type 参数,并返回 make字段,填充相关数据。在您的URLConf中为此视图添加一个URL。

  • 在模板中添加一个Javascript绑定:当用户选择一个 vehicle_type 时,浏览器将向 AjaxMakeFieldView 发送aan ajax请求,并使用返回的HTML替换隐藏的 make 字段



如果你不想要javascript,另一种方式将是两步形式:




  • 具有 vehicle_type 字段的第一个表单

  • 提交第一个表单后,您的用户将获得第二个表单 make 字段,根据 vehicle_type 以第一种形式选择,填充初始数据。



我从来没有这样做,但是表单向导中的Django文档似乎是一个很好的起点。


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?

解决方案

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 :

  • 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 a vehicle_type argument and return the HTML for make 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 to AjaxMakeFieldView and replace hidden make field with returned HTML

If you don't want javascript, another way would be a two step form :

  • 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 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.

这篇关于Django模型选择领域 - 取决于其他领域的选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆