wernerfeuer
wernerfeuer

Reputation: 575

Django render to view not html

I have templates in my django project. My index.html is a custom login page.

In views.py:

def index(request):
    return render(request, 'index.html')

As soos as submit button is clicked the page forwards to:

def checklogin(request):
    username = request.POST('username')    # input element name in template.
    username = request.POST('password')    # input element name in template.
    if user is None:
        return render(request, 'register.html') # Page to register as user.
    else:
        return render(request, 'home.html')

def home(request):
    return render(request, 'home.html')

My urls.py:

from myapp import views

urlpatterns = patterns('',
                       url(r'^login/$', views.index, name=index),
                       url(r'^login/register/$', views.checklogin, name='register'),
                       url(r'^$', views.home, name='home'),
                      )

This works fine. The index page directs you to the login. If you fail it will take you to register - url changing from 127.0.0.1:8000/mysite/login to 127.0.0.1:8000/mysite/login/register/.

However, if login succeeds the user is taken to home.html, but not to 127.0.0.1:8000/mysite/ but rather to 127.0.0.1:8000/mysite/login/register/ as well. This creates a problem, because if i pass a query in def home(request) to the home.html template it is only available at 127.0.0.1:8000/mysite/ and not at 127.0.0.1:8000/mysite/login/register/.

Can someone help me to direct to def home(request) and not just the html with a successful login?

Upvotes: 1

Views: 4891

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599846

You shouldn't do it like that. You should always redirect after a POST anyway; so here you just redirect back to 'home'.

from django.shortcuts import redirect
...
return redirect('home')

The register branch should be a redirect as well, of course.

Upvotes: 2

Related Questions