如何避免在下面的视图中复制GET
块中的逻辑代码?
逻辑是特定于视图的,我觉得将辅助函数放在单独的utils.py中是有意义的。
'''
show_stuff view shows different stuff depending on how many other
POST requests have been submitted to view and saved to the DB.
All the users access the same URL randomly, so I don't believe it's possible to
split things up like "view_for_template1", "view_for_template2" in urls.py
'''
def show_stuff(request, url_dispatch_var1, url_dispatch_var2=None):
if request.method == "GET":
#30 lines of logic determining which Template and Context to return
if request.method =="POST":
#10 lines of logic determining which Form type to save
#then, the same 30 lines of logic as the GET block to determine
#which Template and Context to return
答案 0 :(得分:3)
您通常可以执行以下操作:
def show_stuff(request, url_dispatch_var1, url_dispatch_var2=None):
if request.method =="POST":
#10 lines of logic determining which Form type to save
# redirect if form is valid
else:
# this is a GET request
form = MyForm() # unbound form for get request
# 30 lines of logic to determine which Template and Context to return
return render(request, template, context)
请注意,在成功发布请求后,通常的方法是重定向以防止重复提交。
此可能是基于类的视图有用的情况。您可以继承FormView
,然后覆盖get_context_data
,get_template_names
,依此类推。
答案 1 :(得分:0)
也许您可以将用户重定向到您的GET视图,而不是为POST请求返回正文?