用于在 Django 中进行编辑的表单向导
我正在制作一个网络应用程序,这个网络应用程序需要有一个表单向导。该向导由 3 个 ModelForm 组成,并且运行完美。但我需要第二种形式是“编辑形式”。也就是说,我需要它成为传递实例的表单。
如何使用表单向导来做到这一点?如何传递模型实例?我看到 FormWizard 类有一个 get_form 方法,但是没有记录的方法来使用 formwizard 编辑/查看数据吗?
I am in the process of making a webapp, and this webapp needs to have a form wizard. The wizard consists of 3 ModelForms, and it works flawlessly. But I need the second form to be a "edit form". That is, i need it to be a form that is passed an instance.
How can you do this with a form wizard? How do you pass in an instance of a model? I see that the FormWizard class has a get_form method, but isnt there a documented way to use the formwizard for editing/reviewing of data?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在 Django 1.4 中你可以这样做:
In Django 1.4 you can do something like:
您可以在视图中使用 formwizard 类并在其中传递初始值,例如:
其中初始值应该是一个字典,其键等于步骤,值是数据的字典,就像通常的表单一样。
you can use formwizard class in a view and pass initial there, something like:
where initial should be a dict with keys equal to steps and values are dicts of data just like for usual form.
我认为有几种方法,具体取决于您必须传递的数据的复杂程度。
您可以按照此处的说明进行操作: https://docs.djangoproject.com/en/dev/ref/contrib/formtools/form-wizard/#providing-initial-data-for-the-forms
并创建一个初始字典,将其传递给 urls.py 中的视图,如下所示:
您的另一个选择,这更复杂,但允许您有更多的逻辑,是覆盖 get_initkwargs 并将逻辑放在那里(请参阅 Django 代码: https://github.com /django/django/blob/master/django/contrib/formtools/wizard/views.py)。
最后,如果您需要根据先前表单的输入提供对象,那么它将变得相当复杂,因为 get_initkwargs 是一个类方法,并且在启动向导时需要传递初始字典。但是,您可以通过重写 get_form_kwargs 来实现:
然后您可以使用表单的 init 方法根据您在 kwargs 中传递的对象设置初始值。我经常使用最后一段代码,但没有真正使用过前面的代码。
I think there's a few approaches, depending how complicated the data you have to pass is.
You can follow the instructions here: https://docs.djangoproject.com/en/dev/ref/contrib/formtools/form-wizard/#providing-initial-data-for-the-forms
and create an initial dictionary that you pass to the view in urls.py like so:
Your other option, and this is more complex, but will allow you to have a little more logic, is to override get_initkwargs and put the logic in there (see Django code: https://github.com/django/django/blob/master/django/contrib/formtools/wizard/views.py).
Finally, if you need to provide the object based on the previous form's input, then it's going to get quite complicated, because get_initkwargs is a class method and initial dictionaries need to be passed when the wizard is initiated. But, you can probably do it by overriding get_form_kwargs:
Then you could use the form's init method to set initial values based on the object you passed in kwargs. I use that last piece of code a lot, but haven't really used the earlier ones.