Django and urls.py: How do I HttpResponseRedirect via a named url?

前端 未结 4 2120
萌比男神i
萌比男神i 2020-12-29 22:23

I\'m writing a member-based web application, and I need to be able to redirect the page after login. I want to use the named url from my urls.py script in my views.py file f

相关标签:
4条回答
  • 2020-12-29 22:29

    You need to use the reverse() utils function.

    from django.urls import reverse
    # or Django < 2.0 : from django.core.urlresolvers import reverse
    
    def myview(request):
        return HttpResponseRedirect(reverse('arch-summary', args=[1945]))
    

    Where args satisfies all the arguments in your url's regular expression. You can also supply named args by passing a dictionary.

    0 讨论(0)
  • 2020-12-29 22:34

    A more concise way to write that if statement would be if request.session.get('user'). has_key is deprecated nowadays, and .get() returns None (by default, changeable by passing a second parameter). So combining this with Soviut's reply:

    from django.core.urlresolvers import reverse
    
    def login(request): 
        if request.session.get('user'):
             return HttpResponseRedirect(reverse('my-named-url'))
    
    0 讨论(0)
  • 2020-12-29 22:45
    from django.core.urlresolvers import reverse
    from django.shortcuts import redirect
    
    def login(request):
        if request.session.get('user'):
            return redirect(reverse('name-of-url'))
    

    Also see https://docs.djangoproject.com/en/dev/topics/http/urls/#reverse-resolution-of-urls

    0 讨论(0)
  • 2020-12-29 22:53

    The right answer from Django 1.3 onwards, where the redirect method implicitly does a reverse call, is:

    from django.shortcuts import redirect
    
    def login(request):
        if request.session.get('user'):
            return redirect('named_url')
    
    0 讨论(0)
提交回复
热议问题