动态形式的Django FormWizard [英] Django FormWizard with dynamic forms
问题描述
我想实现一个简单的2部分FormWizard。
Form 1将通过动态生成这样的东西:
I want to implement a simple 2 part FormWizard. Form 1 will by dynamically generated something like this:
class BuyAppleForm(forms.Form):
creditcard = forms.ChoiceField(widget = forms.RadioSelect)
type = forms.ChoiceField(widget = forms.RadioSelect)
def __init__(self,*args, **kwargs):
user = kwargs['user']
del kwargs['user']
super(BuyAppleForm, self).__init__(*args, **kwargs)
credit_cards = get_credit_cards(user)
self.fields['creditcard'].choices = [(card.id,str(card)) for card in credit_cards]
apple_types= get_types_packages()
self.fields['type'].choices = [(type.id,str(type)) for type in apple_types]
这将动态创建一个包含可用选项列表的表单。
This will dynamically create a form with lists of available choices.
我的第二个表单,我实际上不需要输入。我只想显示包含信用卡信息,苹果信息和金额(总计,税金,运费)的确认屏幕。一旦用户点击OK,我想要苹果购买开始。
My second form, I actually want no input. I just want to display a confirmation screen containing the credit card info, apple info, and money amounts (total, tax, shipping). Once user clicks OK, I want the apple purchase to commence.
我能够通过传入kwargs中的request.user对象来实现单一的表单方式。但是,使用FormWizard,我无法弄清楚这一点。
I was able to implement the single form way by passing in the request.user object in the kwargs. However, with the FormWizard, I cannot figure this out.
我遇到问题是错误的,FormWizard不是正确的方法吗?如果是,Form __ init __
方法如何从HTTP请求中访问用户对象?
Am I approaching the problem wrong and is the FormWizard not the proper way to do this? If it is, how can the Form __init__
method access the user object from the HTTP request?
推荐答案
我不知道如果回答自己的问题是StackOverflow上可以接受的行为,这里是我自己的问题的解决方案。
I don't know if answering one's own question is an acceptable behaviour on StackOverflow, here is my solution to my own problem.
首先,转换FormWizard。
First, ditch FormWizard.
我有一个表单。
两个视图: buy_apples
和 buy_apples_confirm
第一个视图只处理GET。它打印出未绑定的表单,并带有操作转到第二个视图的URL。
First view only handles GET. It prints out the unbound form, with an action to go to the URL of the second view.
第二个视图检查是否存在名为confirm的POST参数。如果它不存在(因为它不是第一次加载视图时):
The second view checks for the presence of a POST parameter named "confirm". If it is not present (as it is not when the view is loaded the first time) it:
- 调整所有字段上的小部件被隐藏输入
- 写出提供订单摘要的模板。此模板还会将一个名为confirm的隐藏字段设置为1(即使此窗体中不存在该字段)
当用户点击购买苹果,表单被提交回来,并且再次调用 buy_apples_confirm
视图。这一次,一个POST参数叫做确认,所以我们实际上处理了采购交易,用户得到了他的苹果。
When the user clicks to buy the apples, the form is submitted back and the buy_apples_confirm
view is invoked one more time. This time, a POST parameter called "confirm" is present, so we actually process the purchase transaction and the user gets his apples.
我欢迎任何关于这个方法的批评,更好的处理情况的方法。我是Django的新手,发现有很多不同的方法来解决问题。我想从最好的学习。
I welcome any critiques on this method or better ways of handling the situation. I am new to Django and find that there are many different ways of approaching a problem. I want to learn from the best though.
这篇关于动态形式的Django FormWizard的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!