假设您有一个使用 post 和 get 方法的网页,并且您编写了以下 View 来生成它:
def homepage(request):
if 'login' in request.POST:
# ......... code goes here, and you return an appropriate response
if 'register' in request.POST:
# ......... code goes here, and you return an appropriate response
# When no Post request, just render the page
return render_to_response('homepage.html')
问题:
将上述 View 分成三个 View 是否被认为是良好的编程实践:一个用于登录,一个用于注册,一个用于呈现页面?或者保持原样是否可以。
编辑
在上面列出的情况下,我不会检查服务器是否收到“GET”。但想法还是一样的:)
最佳答案
我认为更好的主意是让这两个表单分别提交到不同的 URL。然后,您可以定义 View ,例如 /login
、/register
和 /
(默认主页处理程序)。您对 /login
和 /register
的 View 可以使用 if request.method == 'POST'
,然后重定向到主页(如果它们是)使用 GET 请求调用。
关于Django View : good programming practice question,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5306675/