Related
I am using custom forms to override the Django templates but when a user clicks reset password and receives the email with the password reset link, etc (EDITED QUESTION TO CHANGE ORDER FROM reset-password to password-reset)
/reset/OA/50l-94673624f6b9fa5a060a/
When the link is clicked it redirects to
/account/login/
It should be directing them to
/password-reset/confirm/
and then to
/password-reset/complete/
The command line looks like this when reset link is clicked
GET /reset/OA/50l-94673624f6b9fa5a060a/ HTTP/1.1" 302 0
GET /account/login/ HTTP/1.1" 200 2237
LOGIN_EXEMPT_URLS
LOGIN_EXEMPT_URLS = {
r'^account/logout/$',
r'^account/register/$',
r'^account/password-reset/$',
r'^account/password-reset/done/$',
r'^account/password-reset/confirm/(?P<uidb64>[0-9A-Za-z]+)-(?P<token>,+)/$',
r'^account/password-reset/complete/$',
}
urls.py
app_name='accounts'
from django.conf.urls import url
from . import views
from django.contrib.auth.views import LoginView, LogoutView, PasswordResetView, PasswordResetDoneView, PasswordResetConfirmView, PasswordResetCompleteView
from django.conf import settings
from django.conf.urls.static import static
from django.urls import reverse_lazy
urlpatterns = [
url(r'^$', views.home, name='home'),
url(r'^login/$', LoginView.as_view(template_name='accounts/login.html'), name='login'),
url(r'^logout/$', LogoutView.as_view(template_name='accounts/logout.html'), name='logout'),
url(r'^register/$', views.register, name='register'),
url(r'^profile/$', views.view_profile, name='view_profile'),
url(r'^profile/edit$', views.edit_profile, name='edit_profile'),
url(r'^change-password/$', views.change_password, name='change_password'),
url(r'^password-reset/$',
PasswordResetView.as_view(template_name='accounts/password_reset.html',
success_url=reverse_lazy('accounts:password_reset_done')),
{'email_template_name': 'accounts/password_reset_email.html'},
name='password_reset'),
url(r'^password-reset/done/$',
PasswordResetDoneView.as_view(template_name='accounts/password_reset_done.html'),
name='password_reset_done'),
url(r'^password-reset/confirm/(?P<uidb64>[0-9A-Za-z]+)-(?P<token>,+)/$',
PasswordResetConfirmView.as_view(template_name='accounts/password_reset_confirm.html'),
name='password_reset_confirm'),
url(r'^password-reset/complete/$',
PasswordResetCompleteView.as_view(template_name='accounts/password_reset_complete.html'),
name='password_reset_complete'),
]
settings.py
INSTALLED_APPS = [
'accounts',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
middleware.py
import re
from django.conf import settings
from django.urls import reverse
from django.shortcuts import redirect
from django.contrib.auth import logout
EXEMPT_URLS = [re.compile(settings.LOGIN_URL.lstrip('/'))]
if hasattr(settings, 'LOGIN_EXEMPT_URLS'):
EXEMPT_URLS += [re.compile(url) for url in settings.LOGIN_EXEMPT_URLS]
class LoginRequiredMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
response = self.get_response(request)
return response
def process_view(self, request, view_func, view_args, view_kwargs):
assert hasattr(request, 'user')
path = request.path_info.lstrip('/')
url_is_exempt = any(url.match(path) for url in EXEMPT_URLS)
if path == reverse('accounts:logout').lstrip('/'):
logout(request)
if request.user.is_authenticated and url_is_exempt:
return redirect(settings.LOGIN_REDIRECT_URL)
elif request.user.is_authenticated or url_is_exempt:
return None
else:
return redirect(settings.LOGIN_URL)
password_reset_email.html
{% load i18n %}{% autoescape off %}
{% blocktrans %} You're recieving this email because you requested a password reset
for your user account at {{ site_name }}.{% endblocktrans %}
{% trans "Please go to the following page and choose a new password:" %}
{% block reset_link %}
{{ protocol }}://{{ domain }}{% url 'password_reset_confirm' uidb64=uid token=token %}
{% endblock %}
{% trans "Your username, in case you've forgotten:" %} {{ user.get_username }}
{% trans "Thank you for using x!" %}
{% blocktrans %}The {{ site_name }} team{% endblocktrans %}
{% endautoescape %}
change in the settings seption the confirm part to just account/password-rest/confirm/ without dollar sign so everything after that url will be exempt aswell.
LOGIN_EXEMPT_URLS = {
r'^account/logout/$',
r'^account/register/$',
r'^account/password-reset/$',
r'^account/password-reset/done/$',
r'^account/password-reset/confirm/',
r'^account/password-reset/complete/$',
}
You should change from PasswordResetConfirmView to PasswordResetCompleteView.
PasswordResetCompleteView presents a view which informs the user that password has been successfully changed. You don't need to write PasswordResetConfirmView twice.
Change to
url(r'^reset-password/complete/$',
PasswordResetCompleteView.as_view(template_name='accounts/reset_password_complete.html'),
name='reset_password_complete'),
For more detail, check django docs. (https://docs.djangoproject.com/en/2.1/topics/auth/default/#django.contrib.auth.views.PasswordResetCompleteView)
You have included your password reset URLs in a urls.py which has app_name = 'accounts', therefore you need to include the accounts namespace when reversing the URLs.
{% url 'accounts:password_reset_confirm' uidb64=uid token=token %}
As an aside, I've seen several questions on Stack Overflow where namespacing the password reset URLs caused problems. In my opinion, it's simpler to include the password reset URLs in a urls.py that does not use a namespace.
The log line GET /reset/OA/50l-94673624f6b9fa5a060a/ suggests that you have included the password reset URLs in a second place. I would try to track down this extra include and remove it.
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' ),
I am new to Django 1.9 and I am currently coding a website. I am trying to make a contact form to go on the contact page. I have used the following code - which is in the a file called email.html:
{% extends 'blog/base.html' %}
<form method="post">
{% csrf_token %}
{{ form }}
<div class="form-actions">
<button type="submit">Send</button>
</div>
</form>
I've defined it in the view.py file:
from .forms import PostForm, ContactForm
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import redirect
from django.core.mail import send_mail, BadHeaderError
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, redirect
def email(request):
if request.method == 'GET':
form = ContactForm()
else:
form = ContactForm(request.POST)
if form.is_valid():
subject = form.cleaned_data['subject']
from_email = form.cleaned_data['from_email']
message = form.cleaned_data['message']
try:
send_mail(subject, message, from_email, ['nmam.ltd#gmail.com'])
except BadHeaderError:
return HttpResponse('Invalid header found.')
return redirect('thanks')
return render(request, "blog/email.html", {'form': form})
def thanks(request):
return HttpResponse('Thank you for your message.')
.....
As well as in the forms.py file:
from django import forms
class ContactForm(forms.Form):
from_email = forms.EmailField(required=True)
subject = forms.CharField(required=True)
message = forms.CharField(widget=forms.Textarea)
Also, in the urls.py file:
from django.conf.urls import patterns, url
from . import views
urlpatterns = [
url(r'^general.html/$', views.general, name='general'),
url(r'^dcmain.html/$', views.dcmain, name='dcmain'),
url(r'^dcmain.html/big_data.html/$', views.big_data, name='big_data'),
url(r'^dcmain.html/Data_Architecture.html/$', views.Data_Architecture, name='Data_Architecture'),
url(r'^dcmain.html/BI_MI.html/$', views.BI_MI, name='BI_MI'),
url(r'^dcmain.html/Master_Data.html/$', views.Master_Data, name='Master_Data'),
url(r'^dcmain.html/Data_Q.html/$', views.Data_Q, name='Data_Q'),
url(r'^dcmain.html/Project_M.html/$', views.Project_M, name='Project_M'),
url(r'^email.html/$', views.email, name='email'),
url(r'^thanks/$', views.thanks, name='thanks'),
]
When I link the email.html file to the main page and click on the link and it just shows the home page even though the url says I am on the email.html page (shown below):
I am totally new to programming in Django. I have tried researching it however, I can't find a solution. Please can someone help me.
Your URLs are most likely the problem. You can read more on Django URLs here.
Note, as the Django docs mention, the first URL pattern which matches the requested URL will be used. As a basic rule of thumb, I recommend putting your more specific URL patterns before your blank url patterns. For instance:
urlpatterns = [
url(r'^email.html/$', views.email, name='email'),
url(r'^thanks/$', views.thanks, name='thanks'),
url(r'^$', views.index, name='some_name'),
]
If this urls.py file is being included from a project urls.py file, you'll want these urls to be included before your root url pattern.
urlpatterns = [
url(r'^blog/', include('blog.urls', namespace='blog'),
url(r'', views.site_home, name='site_home'),
]
Which would then make your url to this page
Email
Which would render as
Email
I am new to django and I am currently trying to build a website that allows users to sign in and view other users profiles. So far I have managed to let users sign in but I can't work out how to view other peoples profiles.
Each profile uses the users username to create a url for their profile. Currently if I sign in as one user and change the URL to another users profile URL, it still displays the current users profile. I want something similar to pinterest where any person whether they are signed in or not can view peoples profiles.
Any help would be appreciated!
View
from django.http import HttpResponse
from django.shortcuts import render
from howdidu.forms import UserProfileForm
from howdidu.models import UserProfile
from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404
from django.contrib.auth.models import User
def index(request):
context_dict = {'boldmessage': "I am bold font from the context"}
return render(request, 'howdidu/index.html', context_dict)
#user profile form
#login_required
def register_profile(request):
profile = UserProfile.objects.get(user=request.user)
if request.method == 'POST':
form = UserProfileForm(request.POST, request.FILES, instance=profile)
if form.is_valid():
form.save()
return index(request)
else:
print form.errors
else:
form = UserProfileForm()
return render(request, 'howdidu/register_profile.html', {'form': form})
#profile page using user name as url
#login_required
def profile_page(request, username):
user = get_object_or_404(User, username=username)
return render(request, 'howdidu/profile.html', {'profile_user': user})
project url
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.conf import settings
from registration.backends.simple.views import RegistrationView
class MyRegistrationView(RegistrationView): #redirects to home page after registration
def get_success_url(self,request, user):
return '/register_profile'
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'howdidu_project.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'', include('howdidu.urls')),
url(r'^accounts/register/$', MyRegistrationView.as_view(), name='registration_register'), #redirects to home page after registration
(r'^accounts/', include('registration.backends.simple.urls')),
url(r'^(?P<username>\w+)/', include('howdidu.urls')), #do i need this?
)
# media
if settings.DEBUG:
urlpatterns += patterns(
'django.views.static',
(r'^media/(?P<path>.*)',
'serve',
{'document_root': settings.MEDIA_ROOT}), )
app url
from django.conf.urls import patterns, url
from howdidu import views
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^register_profile/$', views.register_profile, name='register_profile'),
url(r'^(?P<username>\w+)/$', views.profile_page, name='user_profile'),
)
template
{% extends 'howdidu/base.html' %}
{% load staticfiles %}
{% block title %}{{ user.username }}{% endblock %}
{% block body_block %}
{% if user.is_authenticated %}
<h1>{{ user.username }} welcome to your profile page</h1>
<img src="{{ user.userprofile.profile_picture.url }}" width = "150" height = "150" />
<h2>{{ user.userprofile.first_name }}</h2>
<h2>{{ user.userprofile.second_name }}</h2>
<h2>{{ user.userprofile.user_country }}</h2>
{% endif %}
{% endblock %}
Register urls of your app in the configuration folder project_name/urls.py :
E.g :
from django.conf.urls import include, url
from django.contrib import admin
from django.conf import settings
urlpatterns = [
url(r'^user/', include('<app_name>.urls')),
url(r'^admin/', include(admin.site.urls)),
]
Add a new route in your <app_name>/urls.py.
E.g :
from . import views
urlpatterns = [
url(r'profile/(?P<username>[a-zA-Z0-9]+)$', views.get_user_profile),
]
Add a view in <app_name>/views.py that take username (username of the user) to retrieve its information and send them into a template
E.g :
from django.shortcuts import render
def get_user_profile(request, username):
user = User.objects.get(username=username)
return render(request, '<app_name>/user_profile.html', {"user":user})
Create a template file in <app_name>/templates/<app_name>/user_profile.htmlto display user object :
{{ user.username }}
{{ user.email }}
{{ user.first_name }}
{{ user.last_name }}
Replace <app_name> by the name of your app and it should be good.
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.