Django kind of overloaded views
How is this possible to make overloaded views in Django ? The problem is I have a view which may accept exactly one argument or none. If there is a argument, it will pass it to view.
Let show what I am tryin' to do
views.py
def member_list(request,message):
memberList = Member.objects.all()
return render_response(request, 'user/member_list.html', {'memberList': memberList, 'message':message })
def member_list(request,message):
memberList = Member.objects.all()
return render_response(request, 'user/member_list.html', {'memberList': memberList, 'message':message })
u开发者_StackOverflow社区rls.py
(r'^member/list/$', 'views.member_list'),
(r'^member/list/(?P<message>[-\w]+)/$', 'views.member_list'),
What is the right way to do this ?
Thanks
def member_list(request,message=None):
if message:
pass
else:
pass
You can use optional arguments in your view signature to your advantage here.
Simply define your view like this:
def member_list(request, message=None):
And then if there's a match in the URL, it'll get filled in. If not, it will still be None
.
if message is None:
# I got here via the '^member/list/$' URL regex
else:
# I got here via the '^member/list/(?P<message>[-\w]+)/$' URL regex
(Adapted from this blog post)
精彩评论