我对Python很陌生,所以这可能是一个愚蠢的问题,但无论如何我都会问。是否存在Django为这种常见的视图情况形成“设计模式”?当我运行视图时,我希望它根据填写表单的用户类型,对两种不同类型的表单中的一种进行操作。在if request.method块中有两个if / then块来确定我正在使用哪种类型的表单似乎很难看。我想要的是能够引用一个“CreateProfileForm”,它将引用CreateManProfileForm或CreateWomanProfileForm,具体取决于会话变量中的内容。
谢谢!
def create_profile(request, template):
if request.session['user_type_cd'] == 'man':
is_man = True
else:
is_man = False
if request.method == "POST":
if is_man:
form = CreateManProfileForm(request.POST)
else:
form = CreateWomanProfileForm(request.POST)
if form.is_valid():
# Do stuff
return HttpResponseRedirect(reverse('do-next-thing'))
else:
if is_man:
form = CreateManProfileForm()
else:
form = CreateWomanProfileForm()
return render_to_response(template, locals(), context_instance=RequestContext(request))
答案 0 :(得分:1)
您可以这样做:
创建表单字典
FORMS = {
0: CreateWomanProfileForm,
1: CreateManProfileForm
}
在观点中:
def create_profile(request, template):
is_man = 1 if request.session.get('user_type_cd') == 'man' else 0
if request.method == "POST":
form = FORMS.get(is_man)(request.POST)
if form.is_valid():
# Do stuff
return HttpResponseRedirect(reverse('do-next-thing'))
else:
form = FORMS.get(is_man)()
return render_to_response(template, locals(), context_instance=RequestContext(request))
甚至这应该可行
def create_profile(request, template):
is_man = 1 if request.session['user_type_cd'] == 'man' else 0
form = FORMS.get(is_man)(request.POST or None)
if request.method == "POST":
if form.is_valid():
# Do stuff
return HttpResponseRedirect(reverse('do-next-thing'))
return render_to_response(template, locals(), context_instance=RequestContext(request))