Raise 404 and continue the URL chain

前端 未结 1 517
离开以前
离开以前 2021-02-11 15:56

I\'ve got a URLs pattern like this:

urlpatterns = (
    url(r\'^$\', list_titles, name=\'list\'),
    url(r\'^(?P[a-z\\-0-9]+?)/$\', list_titles, name         


        
相关标签:
1条回答
  • 2021-02-11 16:28

    This is certainly view logic; all urls.py is for is for matching URL patterns, not performing validation. You can use the Http404 exception to handle this.

    from django.http import Http404
    
    def detail(request, poll_id):
        try:
            p = Poll.objects.get(pk=poll_id)
        except Poll.DoesNotExist:
            raise Http404
        return render_to_response('polls/detail.html', {'poll': p})
    

    Alternatively, you may find the get_object_or_404 or get_list_or_404 methods, which shorten it up a bit.


    Promised edit follows. Not exactly what you're looking for, but...

    urlpatterns = (
        url(r'^$', list_titles, name='list'),
    )
    
    if 1=1: # Your logic here
        urlpatterns += ( url(r'^$', list_titles, name='list'), )
    
    urlpatterns += (
        url(r'^(?P<title>\S+?)/$', show_title, name='title'),
        url(r'^spam/$', spam_bar),
        url(r'^foo/$', foo_bar),
    }
    
    0 讨论(0)
提交回复
热议问题