Django urls.py not rendering correct template - python

This is my urls.py
"""s7h URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^articles/', include('article.urls')),
url(r'^',include('django.contrib.auth.urls')),
url(r'^projects/', include('project.urls')),
#Serve Media Files
url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT,
}),
#subscribe
url(r'^subscribe/$', 'article.views.subscribe'),
url(r'^verify/$', 'article.views.activateSubscriber'),
# user auth urls
url(r'^home/$', 's7h.views.home'),
url(r'^', 's7h.views.home'),
url(r'^accounts/login/$', 's7h.views.login'),
url(r'^accounts/auth/$', 's7h.views.auth_view'),
url(r'^accounts/logout/$', 's7h.views.logout'),
url(r'^accounts/loggedin/$', 's7h.views.loggedin'),
url(r'^accounts/invalid/$', 's7h.views.invalid_login'),
# user registration urls
url(r'^accounts/register/$', 's7h.views.register'),
url(r'^accounts/register_success/$', 's7h.views.register_success'),
url(r'^accounts/register_auth/$', 's7h.views.register_auth'),
url(r'^contact/$', 's7h.views.contact'),
]+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
handler400 = 's7h.views.custom_400'
handler403 = 's7h.views.custom_403'
handler404 = 's7h.views.custom_404'
handler500 = 's7h.views.custom_500'
if not settings.DEBUG:
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns += staticfiles_urlpatterns()
This is my views.py
from django.shortcuts import render, render_to_response, RequestContext
from django.http import HttpResponseRedirect
from django.contrib import auth,messages
from django.core.context_processors import csrf
from django.template import RequestContext
from django.template.loader import get_template
from forms import MyRegistrationForm
from article.models import Article, ArticleCategory
from project.models import Project, ProjectCategory
def home(request):
args={}
article = Article.objects.earliest("-pub_date")
project = Project.objects.earliest("-pub_date")
article_category = ArticleCategory.objects.all()
project_category = ProjectCategory.objects.all()
args.update(csrf(request))
args['article'] = article
args['project'] = project
args['project_categories'] = project_category
args['article_categories'] = article_category
args['loggedin'] = request.session.get('email', None)
return render_to_response('home.html', args)
def login(request):
c = {}
c.update(csrf(request))
return render_to_response('login.html', c)
def auth_view(request):
username = request.POST.get('username', '')
password = request.POST.get('password', '')
user = auth.authenticate(username=username, password=password)
if user is not None:
auth.login(request, user)
request.session['email'] = user.email
return render(request, "loggedin.html", locals(),context_instance=RequestContext(request))
else:
return HttpResponseRedirect('/accounts/invalid/')
def loggedin(request):
return render_to_response('loggedin.html', {})
def invalid_login(request):
return render_to_response('invalid_login.html')
def logout(request):
auth.logout(request)
return HttpResponseRedirect('/accounts/login/')
This is my template for login
{% extends "user_forms.html" %}
{% block title %}
S7H - Login
{% endblock %}
{% block main %}
<span class="fa fa-user bigicon"></span>
<h2>Enter Details</h2>
<form action = "/accounts/auth/" method = "POST">{% csrf_token %}
<p><input type="text" name="username" required placeholder="Username" autofocus></p>
<p><input type="password" name="password" required placeholder="Password"></p>
<button class="btn btn-default" type="submit" name="submit" />Sign In</button>
Sign Up
</form>
<small>Forgot your password?</small><br />
{% if messages %}
{% for message in messages %}
<small {% if message.tags %} class="{{message.tags}}" {% endif %}>{{message}}</small>
{% endfor %}
{% endif %}
{% endblock %}
Now when I do http://127.0.0.1:8000/accounts/login/ , Django should render login.html because url accounts/login/ leads me to def login(request): and there in render_to_response() I have mentioned login.html to get rendered but instead of it, Django renders my home.html file. URL of the browser changes to http://127.0.0.1:8000/accounts/login/ when I press the login button on my home page but it keeps on rendering the same home.html template.
This thing is happening with other urls also. Every url is rendering home.html template.
I double checked all my urls, views and templates, I have not been able to figure out my mistake. Django is also not giving any Exceptions and Error messages.
Also in the terminal the HTTP response is 200 OK :/
[08/Jun/2015 01:38:40]"GET /accounts/login/ HTTP/1.1" 200 10201
Help me!

Your s7h.views.home pattern has no terminating $ so it matches every URL.

Related

AttributeError: module 'users.views' has no attribute 'register'

I am new to Python and Django. Getting this error when running the server. The problem seems to be in 'urls.py' of the project.
File "C:\Users\Desktop\myproject\django_project\django_project\urls.py", line 22, in <module>
path('register/', user_views.register , name = 'register'),
AttributeError: module 'users.views' has no attribute 'register'
This is my urls.py
from django.contrib import admin
from django.urls import path, include
from users import views as user_views
urlpatterns = [
path('admin/', admin.site.urls),
path('register/', user_views.register , name = 'register'),
path('', include('blog.urls')),
]
This is register.html under users/templates/users/register.html (users is the name of the app)
{% extends "blog/base.html" %}
{% load crispy_forms_tags %}
{% block content %}
<div class="content-section">
<form method="POST">
{% csrf_token %}
<fieldset class="form-group">
<legend class="border-bottom mb-4">Join Today</legend>
{{ form|crispy }}
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" type="submit">Sign Up</button>
</div>
</form>
<div class="border-top pt-3">
<small class="text-muted">
Already Have An Account? <a class="ml-2" href="#">Sign In</a>
</small>
</div>
</div>
{% endblock content %}
This is my views.py
from django.shortcuts import render
from django.contrib.auth.forms import UserCreationForm
def register(request):
form = UserCreationForm()
return render(request, 'users/register.html', {'form':form})
I have also tried creating a separate urls.py for my 'users' app and adding the path there but I am getting the same error.
I am very new to programming so please excuse my inexperience.
Make sure you have a space after register>>> def register (request):
If it is not the issue please check the "views.py" for correct register function under the users folder.
from django.shortcuts import render
from django.contrib.auth.forms import UserCreationForm
# Create your views here.
def register (request):
form = UserCreationForm()
return render(request, 'users/register.html', {'form': form})
Your urls.py should be like this:
from django.contrib import admin
from django.urls import path, include
from .view.py import register
urlpatterns = [
path('admin/', admin.site.urls),
path('register/',register , name = 'register'),
path('', include('blog.urls')),
]
Note: if your views name is views.py
consider this arrange:
you have a users application in your base directory, this app has a users-views.py file that your register function is there.
then your urls.py must be like this:
from django.contrib import admin
from django.urls import path, include
from users import users-views as user_views
urlpatterns = [
path('admin/', admin.site.urls),
path('register/', user_views.register , name = 'register'),
path('', include('blog.urls')),
]
as you can see your users application has no views.py I recommend rename users-views.py to views.py and use your original urls.py.
Is your users/views.py file saved and up to date? Try stopping the server completely, ctrl+c on windows if it's started and double check all your files are up to date then try running the server again.

Django-CMS - Django Model Form not rendering

I'm building a new site in Django with Django-CMS that needs a form to filter JSON results and return the filtered set.
My issue is that, initially, I can't even get the Django Model Form to render yet I can get the CSRF token to work so the form is technically rendering, but the inputs/fields aren't showing up at all.
models.py:
from django.db import models
from .jobs.jobs import *
roles = get_filters()
loc = roles[0]
j_type = roles[1]
industry = roles[2]
class Filter(models.Model):
country = models.CharField(max_length=255)
job_type = models.CharField(max_length=255)
industry = models.CharField(max_length=255)
search = models.CharField(max_length=255)
jobs/jobs.py
try:
from BeautifulSoup import BeautifulSoup
except ImportError:
from bs4 import BeautifulSoup
import urllib3
import json
http = urllib3.PoolManager()
def get_filters():
response = http.request('GET', 'http://206.189.27.188/eo/api/v1.0/jobs')
jobs = json.loads(response.data.decode('UTF-8'))
job_list = []
for job, values in jobs.items():
job_list.append(values)
roles_data = []
for job in job_list[0]:
roles_data.append(job)
roles_data = sorted(roles_data, key=lambda role : role["id"], reverse=True)
loc = []
j_type = []
industry = []
for role in roles_data:
loc.append(role['location'])
j_type.append(role['type'])
industry.append(role['industry'])
return loc, j_type, industry
views.py
from django.shortcuts import render
from django.http import HttpResponseRedirect
from .forms import FilterForm
def index(request):
form = FilterForm()
context = {
'form': form,
}
return render(request, 'blog.html', context)
forms.py
from django.forms import ModelForm
from .models import Filter
class FilterForm(ModelForm):
class Meta:
model = Filter
fields = ['country', 'job_type', 'industry', 'search']
urls.py
from __future__ import absolute_import, print_function, unicode_literals
from cms.sitemaps import CMSSitemap
from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.i18n import i18n_patterns
from django.contrib import admin
from django.contrib.sitemaps.views import sitemap
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.views.static import serve
from . import views
admin.autodiscover()
urlpatterns = [
url(r'^sitemap\.xml$', sitemap,
{'sitemaps': {'cmspages': CMSSitemap}}),
url(r'^accounts/', admin.site.urls),
url(r'^services/latest-roles/', views.filter_form, name="filter_form" )
]
urlpatterns += i18n_patterns(
url(r'^admin/', include(admin.site.urls)), # NOQA
url(r'^', include('cms.urls')),
)
# This is only needed when using runserver.
if settings.DEBUG:
urlpatterns = [
url(r'^media/(?P<path>.*)$', serve,
{'document_root': settings.MEDIA_ROOT, 'show_indexes': True}),
] + staticfiles_urlpatterns() + urlpatterns
blog.html
{% extends 'includes/templates/layout.html' %}
{% load cms_tags i18n sekizai_tags zinnia %}
{% block main_content %}
{% include 'components-header-image.html' %}
<section class="module">
<div class="container">
<div class="row">
<div class="col-md-12 m-auto text-center">
<form action="POST" class="col-md-12">
{% csrf_token %}
{{ form.as_p }}
<button name="submit" class="btn btn-brand">Search</button>
</form>
{% get_all_roles%}
</div>
<div class="col-md-12">
<div class="space" data-MY="120px"></div>
</div>
<div class="col-md-12 flex-center text-center">
{% placeholder 'jobs-bottom-statement' %}
</div>
</div>
</div>
</section>
<!-- Image-->
{% include 'components-contact.html' %}
<!-- Image end-->
{% endblock %}
Sorry for the masses of information, just wanted to include anything anyone might need.
As I said, the CSRF token is displaying, nothing is throwing an error anywhere but it's just not displaying the fields at all.
Really appreciate any help or advice.
I'm 95% sure your view isn't being called.
You need to integrate your application as a CMS apphook or hard code your URLs into your root urls.py which is the easier integration test as it doesn't depend on CMS integration.
So Add your view to your URLs like this;
urlpatterns += i18n_patterns(
url(r'^admin/', include(admin.site.urls)), # NOQA
url(r'^blog/$', views.index, name='blog'),
url(r'^', include('cms.urls')),
)
Then go to localhost:8000/blog/ in your browser & you should hit your view.
To confirm you're hitting it you could make a simple amendment to your view;
def index(request):
form = FilterForm()
context = {
'form': form,
}
print "index hit"
return render(request, 'blog.html', context)
Then you'll see "index hit" in your console if your view is called.

accounts is not a registered namespace

in this django tutorial, we are creating a blogsite, at this pont we are creating a login form for users, unfortunately im getting and error saying that "accounts" is not a registered namespace, how do i fix this?
my urls.py file for the app "accounts":
from django.conf.urls import url
from.import views
appname= 'accounts'
urlpatterns=[
url(r'^signup/$', views.signup_view, name= "signup"),
url(r'^login/$', views.login_view, name = "login" ),
]
my views.py for the app:
from django.shortcuts import render, redirect
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
def signup_view(request):
if request.method== 'POST':
form= UserCreationForm(request.POST)
if form.is_valid():
form.save()
#log the user in
return redirect('narticle:list')
else:
form=UserCreationForm()
return render (request,'accounts/accounts_signup.html', {'form': form})
def login_view(request):
if request.method == "POST":
form = AuthenticationForm(data= request.POST)
if form.is_valid():
return redirect('narticle:list')
else:
form = AuthenticationForm()
return render(request, 'accounts/login.html',{'form': form})
my base layout is:
{% load static from staticfiles %}
<!DOCTYPE html>
<html>
<head>
<title>Narticle</title>
<link rel="stylesheet" href="{%static 'styles.css'%}">
</head>
<body>
<div class="wrapper">
<h1> narticle </h1>
{% block content %}
{% endblock %}
</div>
</body>
</html>
the template for login is:
{% extends 'base_layout.html'%}
{%block content%}
<h1> log in</h1>
<form class="site-form" action="{% url 'accounts:login' %}" method="post">
{% csrf_token %}
{{form}}
<input type="submit" name="log_in" value="login">
</form>
{% endblock %}
these are my base urls:
from django.conf.urls import url, include
from django.contrib import admin
from. import views
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^accounts/', include ('accounts.urls')),
url(r'^narticle/', include ('narticle.urls')),
url(r'^about/$', views.about),
url(r'^$',views.homepage),
]
urlpatterns+= staticfiles_urlpatterns()
urlpatterns+= static(settings.MEDIA_URL, document_root= settings.
MEDIA_ROOT)
Believe it's because you missed the underscore:
from django.conf.urls import url
from.import views
# app_name not appname
app_name= 'accounts'
urlpatterns = [
url(r'^signup/$', views.signup_view, name= "signup"),
url(r'^login/$', views.login_view, name = "login" ),
]
You missed namespace in project urls.
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^accounts/', include ('accounts.urls', namespace='accounts')),
url(r'^narticle/', include ('narticle.urls')),
url(r'^about/$', views.about),
url(r'^$',views.homepage),
]

Django unable to render logout template

Have the following problem; I am following Django by Example, Antonio Mele.The exercise here, is to set up user login and logout.Using the default contrib.auth views. When the code in the book is used. The logout view is that of the admin page logout; seems to be same issue as described here
django logout redirects me to administration page. Have tried all there no success
I have been working on this problem. My code now works, in that the admin template is no longer rendered. However, I am still unable to use my own logout.html. I can redirect to my own login.html... but not the logout.html.The logging out itself is working. User can log in, and out only this issue with the templates. I now only receive one browser error
The page isn't redirecting properly Iceweasel has detected that the >server is redirecting the request for this address in a way that will >never complete.This problem can sometimes be caused by disabling or >refusing to accept cookies.
checked the cookies can see csrf token is accepted
no traceback available no errors :-(
If I use the code below , all works with one exception. I am redirected at logout to the Django Administration logout template, and not my own logout.html....This is when using coede in the book.... My own modified code, with a seperate logout function also did not work generating a maximum recurson error.Editing the URLS.PY stops the rendering of the admin template. but the modified code seems to have an issue in the urls i.e .....
THIS IS NOT WORKING !!!!!
url(r'^logout/$', 'django.contrib.auth.views.logout',{'next_page': '/account/logout'}, name='logout'),
THIS WORKS PERFECTLY !!!!
url(r'^logout/$', 'django.contrib.auth.views.logout',{'next_page': '/account/login'}, name='logout'),
The code from the book is as follows
FROM BOOK SETTINGS.PY
from django.core.urlresolvers import reverse_lazy
LOGIN_REDIRECT_URL = reverse_lazy('dashboard')
LOGIN_URL = reverse_lazy('login')
LOGOUT_URL = reverse_lazy('logout')
FROM BOOK VIEWS.PY
from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from .forms import LoginForm
#login_required
def dashboard(request):
return render(request, 'account/dashboard.html', {'section': 'dashboard'})
def user_login(request):
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
user = authenticate(username=cd['username'], password=cd['password'])
if user is not None:
if user.is_active:
login(request, user)
return HttpResponse('Authenticated successfully')
else:
return HttpResponse('Disabled account')
else:
return HttpResponse('Invalid login')
else:
form = LoginForm()
return render(request, 'account/login.html', {'form': form})
FROM BOOK MAIN URLS.PY
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^account/', include('account.urls')),
]
MYAPP(account) URLS.PY
from django.conf.urls import url
from . import views
urlpatterns = [
# url(r'^login/$', views.user_login, name='login'),
url(r'^$', views.dashboard, name='dashboard'),
# login / logout urls
url(r'^login/$', 'django.contrib.auth.views.login', name='login'),
url(r'^logout/$', 'django.contrib.auth.views.logout', name='logout'),
url(r'^logout-then-login/$', 'django.contrib.auth.views.logout_then_login', name='logout_then_login'),
MY MODIFIFED CODE
I have now include a seperate logout definition in my view's and now also pass a {key:value} pair of {'next_page': '/account/logout'}.
if the logout def is used and mapped in the urls file it generates a maximum recursion error at line logout(request)
def logout(request):
logout(request)
request.session.flush()
request.user = AnonymousUser
# Redirect to a success page.
return HttpResponseRedirect(request,'/account/logout.html',context_instance = RequestContext(request))
without this def the only error generated is
"""
The page isn't redirecting properly
"""Iceweasel has detected that the server is redirecting the request for this address in a way that will never complete.
This problem can sometimes be caused by disabling or refusing to accept cookies.""""
"""
I checked cookies in the browser, and see the csrf_token being accepted
For me the strange thing is that if the code: {'next_page': '/account/logout'} is changed to {'next_page': '/account/login'} everything works perfectly. Have tried all suggestions found, am at a loss any help appreciated ....
MY CODE
VIEWS.PY
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib.auth import authenticate, login, logout
from .forms import LoginForm
from django.contrib.auth.decorators import login_required
from django.template import RequestContext
from django.contrib.auth.models import User
# Create your views here.
#login_required
def dashboard(request):
return render(request, 'account/dashboard.html',{'section': 'dashboard' })
def user_login(request):
cd = None
if request.method=='POST':
form = LoginForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
user = authenticate(username=cd['username'],
password=cd['password'])
if user is not None:
if user.is_active:
login(request, user)
return HttpResponse('Authenticated successfully')
else:
return HttpResponse('Disabled Account')
else:
return HttpResponse('Invalid Login')
else:
form = LoginForm()
return render(request, 'account/login.html',{'form': form},context_instance = RequestContext(request))
def logout(request):
logout(request)
request.session.flush()
request.user = AnonymousUser
# Redirect to a success page.
return HttpResponseRedirect(request,'/account/logout.html',context_instance = RequestContext(request))
MY CODE
account/urls.py
from django.conf.urls import url, patterns
from . import views
urlpatterns = [
# post views
#url(r'^login/$', views.user_login, name='login'),
# login/logout urls
url(r'^$', views.dashboard, name='dashboard'),
url(r'^login/$', 'django.contrib.auth.views.login', name='login'),
url(r'^logout/$', 'django.contrib.auth.views.logout',{'next_page': '/account/logout'}, name='logout'),
url(r'^logout-then-login/$','django.contrib.auth.views.logout_then_login', name='logout_then_login'),
]
MY CODE
MAIN URLS.PY
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^account/', include("account.urls")),
]
MYCODE
SETTINGS.PY
LOGIN_REDIRECT_URL = reverse_lazy('dashboard')
LOGIN_URL = reverse_lazy('login')
LOGOUT_URL = reverse_lazy('logout')
INSTALLED_APPS = (
'account',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
)
MIDDLEWARE_CLASSES = (
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
)
# urlpatterns += patterns('django.contrib.auth.views',
# #url(r'^login/$', 'login', { 'template_name': 'registration/login.html'}, name='login' ),
# #url(r'^logout/$', 'logout', { 'template_name': 'registration/logout.html', 'next_page':reverse('index') }, name='logout' ),
# )
MYCODE
logout.html
{% extends "base1.html" %}
{% block title %}Logged Out{% endblock %}
{% block content %}
<h1>
Logged Out
</h1>
<p>
You have been successfully logged out. You can Log-in again
</p>{% endblock %}
MYCODE
base1.html
{% load staticfiles %}
<!DOCTYPE html>
<html>
<head>
<title>{% block title %}{% endblock %}</title>
<link rel="stylesheet" type="text/css" href="{% static 'css/base.css' %}">
</head>
<body>
<div id="header">
<span class="logo">
BookMarks
</span>
{% if user.is_authenticated %}
<ul class="menu">
<li {% if section == "dashboard" %}class="selected"{% endif %}>
My dashboard
</li>
<li {% if section == "images" %}class="selected"{% endif %}>
Images
</li>
<li {% if section == "people" %}class="selected"{% endif %}>
People
</li>
</ul>
{% endif %}
{%if user.is_authenticated %}
<span class="user">
Hello {{ user.first_name }} {{ user.last_name }},
Logout
{% else %}
<a href='{% url "login" %}'>Log-in</a>
{% endif %}
</span>
</div>
<div id="content">
{% block content %}
{% endblock %}
</div>
</body>
</html>
I was having same issue, but then I kept reading
"If you are seeing the log out page of the Django administration site instead of your own log out page, check the INSTALLED_APPS setting of your project and make sure that django.contrib.admin comes after the account application. Both templates are located in the same relative path and the Django template loader will use the first one it finds."
You are using contrib.auth's logout view in your urls.py. This view redirects to the URL specified by 'next_page'. You provide '/account/logout' as next_page -- where again the logout view is called!
That leads to an (infinite) redirect loop: the view redirects to itself.
Try instead: in your own logout view:
# no redirecting here!
return render(request, 'account/logout.html',
context_instance=RequestContext(request))
Add a url for that view in account/urls.py:
url(r'^post-logout/$', logout, name='post-logout'),
# logout being your own view
Then provide that url as 'next_page' to the actual (auth) logout:
url(r'^logout/$', 'django.contrib.auth.views.logout',
{'next_page': '/account/post-logout'}, name='logout'),
The solution to the problem is to map the url as follows
url(r'^logout/$', 'django.contrib.auth.views.logout', { 'template_name': 'account/logout.html',}, name='logout' ),

Django login app at suburl, url redirection does not work properly

I have my page deployed at http://example.com. I also have my django application deployed at http://example.com/djangoapp.
I'm using Apache 2.2 with this configuration (/etc/apache2/apache2.conf): WSGIPythonPath /home/brian/djangoprojects/djangoapp.
I also added the line WSGIScriptAlias /djangoapp /home/brian/djangoprojects/djangoapp/djangoapp/wsgi.py to the default Apache Virtual Host file and it works really nice.
However, in my application I'm using the auth module to register and login users, and have some problems with it. Sometimes I got redirected to the main page, http://example.com/, sometimes to http://example.com/register instead of http://example.com/djangoapp/register.
Changes I made in my project:
Edited settings.py and added:
LOGIN_URL = '/djangoapp/accounts/login/'
USE_X_FORWARDED_HOST = True
FORCE_SCRIPT_NAME = '/djangoapp'
SUB_SITE = "/djangoapp"
My urls.py file looks like this:
from django.conf.urls import include, url
from django.contrib import admin
from djangoapp import views
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^$', 'django.contrib.auth.views.login'),
url(r'^logout/$', views.logout_page),
url(r'^accounts/login/$', 'django.contrib.auth.views.login'), # If user is not login it will redirect to login page
url(r'^register/$', views.register),
url(r'^register/success/$', views.register_success),
url(r'^home/$', views.home),
]
And here's my views.py file:
from django.contrib.auth.decorators import login_required
from django.contrib.auth import logout
from django.contrib.auth.models import User
from django.views.decorators.csrf import csrf_protect
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from django.template import RequestContext
from djangoapp.forms import RegistrationForm
#csrf_protect
def register(request):
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
user = User.objects.create_user(
username=form.cleaned_data['username'],
password=form.cleaned_data['password1'],
email=form.cleaned_data['email']
)
return HttpResponseRedirect('register/success/')
else:
form = RegistrationForm()
variables = RequestContext(request, {
'form': form
})
return render_to_response(
'registration/register.html',
variables,
)
def register_success(request):
return render_to_response(
'registration/success.html',
)
def logout_page(request):
logout(request)
return HttpResponseRedirect('/')
#login_required
def home(request):
return render_to_response(
'home.html',
{'user': request.user}
)
This is the production server and it's available online. I tried to use a work-around, but with no effect. I simply changed links on page and added djangoapp at the beginning, for instance:
{% extends "base.html" %}
{% block title %}Login{% endblock %}
{% block head %}Login{% endblock %}
{% block content %}
{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}
<form method="post" action=".">{% csrf_token %}
<table border="0">
<tr><th><label for="id_username">Username:</label></th><td>{{ form.username }}</td></tr>
<tr><th><label for="id_password">Password:</label></th><td>{{ form.password }}</td></tr>
</table>
<input type="submit" value="Login" />
<input type="hidden" name="next" value="/home" />
</form>
Register
{% endblock %}
And I tried to change Register to Register but I'm sure there's got to be a smarter solution. Any advice?
You need to use the {% url %} tag and the reverse function consistently. So:
Register
and
return HttpResponseRedirect(reverse('register_success'))
For this to work you also need to give your URL patterns names:
url(r'^register/$', views.register, name="register"),
url(r'^register/success/$', views.register_success, name="register_success"),
Aso, as I said in the comment, you do not need to set FORCE_SCRIPT_NAME yourself.

Categories

Resources