且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Django 模型选择字段 - 取决于其他字段的选择

更新时间:2023-02-12 08:20:04

您可能不能,因为这取决于用户与您的表单的交互:您的服务器无法提前知道您的用户在发送表单之前将选择哪个元素到浏览器.您可能可以使用 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 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

如果您不想要 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 of vehicle_type selected in the first form.

我从未这样做过,但是 Django 文档表单向导似乎是一个不错的起点.

I've never done this, but Django documentation on Form wizard seems a good place to start.