Python/Django URLs - python

Disclaimer.....this is an assignment!
Can someone tell me why I am getting
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/%7B%20%25%20url%20'detail'%20user%20%25%20%7D
Using the URLconf defined in bobbdjango.urls, Django tried these URL patterns, in this order:
[name='home']
profile [name='profile']
user_detail/<str:user_id> [name='detail']
The current path, { % url 'detail' user % }, didn’t match any of these.
You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.
I think its a problem with my URL but I am not seeing source of error. I would just like to click on the link on the home page and move to the user details page. See code below...
My Home page
<body>
{% block content %}
<h1>This is home page</h1>
<div>
<!-- Your profile -->
{% for user in users %}
<a href="{ % url 'detail' user % }">
<h3>{{user.first_name}}</h3>
</a>
{% endfor %}
</div>
{% endblock %}
</body>
My main URL
urlpatterns = [
## path('admin/', admin.site.urls),
path('', include('bobbpets.urls') ),
## path('bobbpets/<int:user.id/>', views.userDetails, name='userDetails'),
]
My app URL
urlpatterns = [
## path('admin/', admin.site.urls),
path('', views.home, name='home'),
path('profile', views.profile, name='profile'),
path('user_detail/<str:user_id>', views.userdetail, name='detail'),
]
My Views
def home(request):
users = User.objects.all()
return render(request, 'home.html', {'users': users})
def userdetail(request,user_id):
user = User.objects.get(id=user_id)
return render(request, 'user_detail.html', {'user': user})
def profile(request):
return render(request, 'profile.html')
My Model
from django.db import models
class User(models.Model):
first_name=models.CharField(max_length=30)
last_name=models.CharField(max_length=30)
email=models.EmailField()
def __str__(self):
return '{} {}'.format(self.first_name, self.last_name)

Your template URL should look like this: <a href="{% url 'detail' user %}
Remove the spaces that you have between your percent signs and parenthesis. That will cause an error.

Try this:
<a href="{ % url 'detail' user.id % }">
but I think you should change
'user_detail/<str:user_id>'
as
'user_detail/<int:user_id>'

Related

How to unfollow url in django?

I created this simple code to learn about login and registration in django. My views.py is
def index(request):
products = Product.objects.all()
return render(request,'index.html',{'products':products})
def register(request):
return render(request,'register.html')
def login(request):
return render(request,'login.html')
def logout(request):
return HttpResponse('logout')
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index),
path('register/', views.register),
path('login/', views.login),
path('logout/', views.logout),
]
base.html
Register
Login
<h3>Base html </h3>
{% block content %}
{% endblock %}
register.html
{%extends 'base.html'%}
<h1>Register</h1>
{% block content %}
{% endblock %}
login.html
{%extends 'base.html'%}
<h1>Login</h1>
{% block content %}
{% endblock %}
At http://127.0.0.1:8000/ when I click Register link it follows to http://127.0.0.1:8000/register page but when I click the 'Register link at that page it follows to http://127.0.0.1:8000/register/register which gives 404 error. How do I unfollow url that is instead of going to http://127.0.0.1:8000/register/register it has to go http://127.0.0.1:8000/register/?
in your base. html you should generally specify a link with {% url 'register' %}
So like that:
Register
But to use it, in you settings.py you should specify the directory where your templates are stored relative to the base directory of your project
TEMPLATES = [
{
...
'DIRS': [
os.path.join(BASE_DIR, 'your/way/to/templates'),
],
...
]
Also import os.path at the top of settings.py
EDIT
when you specify your urls.py, you should give name to every url.
path('register/', views.register, name='register'),
so in Register you call the name of the url
Haven't seen your base urls from project side but seems your are doing this way in my guess
you can remove register from base urls of project file
path(
'register/',
include('register.urls'),
),
The best practice for this problem to name the URLs. Just give them names and refer to that names in the HTML file
My solution:
urls.py
urlpatterns = [
path('', views.index),
path('register/', views.register,name="register"),
path('login/', views.login,name="login"),
path('logout/', views.logout,name="logout"),
]
base.html
Register
Login
<h3>Base html </h3>

Django URL error when using forms

I am fairly new to Django and I am totally stuck on what is causing this error. I have done lots of searching but to no avail! Any help would be super appreciated.
The actual form works fine but when I try and submit the input data I get the error:
Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order:
^admin/
^$ [name='home']
^patientlist [name='patient_list']
^patientdetail/(?P<pk>\d+)/$ [name='patient_detail']
^add_patient/$ [name='add_patient']
The current URL, spirit3/add_patient/, didn't match any of these.
My urls.py in the mysite directory looks like:
from django.conf.urls import url
from django.contrib import admin
from django.conf.urls import include
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'', include('spirit3.urls')),
]
My urls.py in the app looks like:
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.home, name='home'),
url(r'^patientlist', views.patient_list, name='patient_list'),
url(r'^patientdetail/(?P<pk>\d+)/$', views.patient_detail, name='patient_detail'),
url(r'^add_patient/$', views.add_patient, name='add_patient'),
]
The relevant part of views.py:
def add_patient(request):
if request.method == 'POST':
form = PatientForm(request.POST)
if form.is_valid():
form.save(commit=True)
return redirect('home')
else:
print form.errors
else:
form = PatientForm()
return render(request, 'spirit3/add_patient.html', {'form':form})
And the html looks like:
{% extends 'spirit3/base.html' %}
{% block content %}
<body>
<h1> Add a Patient </h>
<form action="/spirit3/add_patient/" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Create Patient" />
</form>
</body>
{% endblock %}
Thanks in advance! :)
the form "action" attribute is wrong... seeing your urls configuration you dont have a /spirit3/add_patient/ url, I think It is /add_patient/
or you could just use a form tag without an "action" it will post to the current page:
<form role="form" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Create Patient" />
</form>
Hope this helps
As pleasedontbelong mentionned, there's indeed no url matching "/spirit3/add_patient/" in your current url config. What you have in tour root urlconf is:
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'', include('spirit3.urls')),
]
This means that urls with path starting with "/admin/" are routed to admin.site.urls, and all other are routed to spirit3.urls. Note that this does NOT in any way prefixes urls defined in spirit3.urls with '/spirit3/', so in your case, all of these urls:
urlpatterns = [
url(r'^$', views.home, name='home'),
url(r'^patientlist', views.patient_list, name='patient_list'),
url(r'^patientdetail/(?P<pk>\d+)/$', views.patient_detail, name='patient_detail'),
url(r'^add_patient/$', views.add_patient, name='add_patient'),
]
will be served directly under the root path "/" - ie, the add_patient view is served by "/add_patient/", not by "/spirit3/add_patient/".
If you want your spirit3 app's urls to be routed under "/spirit3/*", you have to specify this prefix in your root urlconf, ie:
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^spirit3/', include('spirit3.urls')),
]
Note that you can use any prefix, it's totally unrelated to your app name.
As a last note: never hardcode urls anywhere, django knows how to reverse an url from it's name (and args / kwargs if any). In a template you do this with the {% url %} templatetag, in code you use django.core.urlresolvers.reverse().

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 urls.py not rendering correct template

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.

Django: URL template tag leads to 404, but correct when hard coded

Going through polls tutorial modifying it to make a blog. (Django 1.6)
In index.html I can get a hyperlink to lead to the correct URL when it's hard coded like so:
<h2>{{ entry.title }}</h2>
But when I use the URL template tag, I get a 404 (I namespaced blog in the project urls.py)
<h2>{{ entry.title }}</h2>
The 404 page I get passes raw Django code into the URL
Page not found (404)
Request Method: GET
Request URL: http://localhost:8000/blog/%7B$%20url%20'blog:detail'%20entry.id%20%%7D/
Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order:
^polls/
^blog/ ^$ [name='index']
^blog/ ^(?P<entry_id>\d+)/$ [name='detail']
^blog/ ^(?P<entry_id>\d+)/comment/$ [name='comment']
^admin/
The current URL, blog/{$ url 'blog:detail' entry.id %}/, didn't match any of these.
Here's urls.py in the blog app
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^(?P<entry_id>\d+)/$', views.detail, name='detail'),
url(r'^(?P<entry_id>\d+)/comment/$', views.comment, name='comment'),
)
And here are the relevant views:
def index(request):
latest_entries = Entry.objects.order_by('-pub_date')[:5]
tags = Tags.objects.filter()
context = {'latest_entries': latest_entries, 'tags': tags}
return render(request, 'entries/index.html', context)
def detail(request, entry_id):
entry = get_object_or_404(Entry, pk=entry_id)
return render(request, 'entries/detail.html', {'entry': entry})
Change {$ to {%:
<h2>{{ entry.title }}</h2>
Try replacing your template tag, instead of
{$ url 'blog:detail' entry.id %}
write
{% url 'blog:detail' entry.id %}
take care with dollar signs and use percent ones

Categories

Resources