简体   繁体   中英

Confused with /app_name/page or app_name/page

I am confused that whether should I start a path starting with / or not? For example, here is one method from my views.py in django:

@login_required
def add_page(request,category_name_slug=None):
    # check for post method
    print category_name_slug
    try:
        cat = Category.objects.get(slug = category_name_slug)
    except Exception, e:
        cat = None


    if request.method == 'POST':
        print "sjhdfkjsdhkfhjs"
        # means you submitted the form.
        form = PageForm(request.POST)
        a = form.is_valid()
        if a:
            if cat:
                page = form.save(commit = False)
                page.category = cat
                page.views = 0
                page.save()
                print "sdjhfjshk"
                return HttpResponseRedirect('/rango/category/' + category_name_slug + '/')
        else:
            print form.errors

    else:
        form = PageForm()

    context_dict = {'form' : form,'category' : cat, 'slug': category_name_slug}

    return render(request,'rango/add_page.html', context_dict)

In the render line

return render(request,'rango/add_page.html', context_dict)

the line is not started with / . But, in case of following line:

return HttpResponseRedirect('/rango/category/' + category_name_slug + '/')

I have to start with / . Please explain me when should I use '/' and when not.

When using the render function in django, the second argument is the template name.

The string you specify there is used relative to the TEMPLATES settings you've defined in your settings.py. It tells django where the template file is located. This is why you don't start the template name with '/' in render()

Whereas, HttpResponseRedirect directly asks for the URL to redirect. It is upto you whether you should add '/' to it before the string.

When the supplied URL starts with '/', no matter where you redirect from, the user is taken to the exact path relative the the website root.

For example, if the user is at http://127.0.0.1:8000/some/other/page/ and you use the following to redirect user:

return HttpResponseRedirect('/dashboard/')

The user will be redirected to http://127.0.0.1:8000/dashboard/

If the URL does not start with '/', the url is just appended to the url from which user is visiting. In this case:

return HttpResponseRedirect('dashboard/')

User will be taken to http://127.0.0.1:8000/some/other/page/dashboard/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM