Django NoReverseMatch - python

I'm making a simple login app in django 1.6 (and python 2.7) and I get an error at the beggining that is not letting me continue.
This is the site's url.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
import login
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$', include('login.urls', namespace='login')),
url(r'^admin/', include(admin.site.urls)),
)
And this is login/urls.py:
from django.conf.urls import patterns, url
from login import views
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^auth/', views.auth, name='auth'),
)
This is login/views,py
from django.shortcuts import render
from django.contrib.auth import authenticate
def auth(request):
user = authenticate(username=request.POST['username'], password=request.POST['password'])
if user is not None:
# the password verified for the user
if user.is_active:
msg = "User is valid, active and authenticated"
else:
msg = "The password is valid, but the account has been disabled!"
else:
# the authentication system was unable to verify the username and password
msg = "The username and password were incorrect."
return render(request, 'login/authenticate.html', {'MESSAGE': msg})
def index(request):
return render(request, 'login/login_form.html')
I have a form that has this as action:
{% url 'login:auth' %}
And that's where the problem is, when I try to load the page, I get:
Reverse for 'auth' with arguments '()' and keyword arguments '{}' not found. 1 pattern(s) tried: [u'$auth/']
But if I set the url pattern to
url(r'', views.auth, name='auth')
it works fine, only it sets the action as '/'.
I've been looking all around for an answer and I don't understand why it doesn't work.
I tried changing the login url pattern to url(r'^login/$', include('login.urls', namespace='login')), and it didn't change anything.

The problem is in the way you include the auth URLs in the main one.
Because you use both ^ and $, only the empty string matches. Drop the $.

I had html anchor tag: <a href="{% url 'url-name' url=someUUID %}">
in my urls.py
...
path('some_name/<slug:slug>/', views.someDetailView.as_view(), name='url-name'),
...
Solution for this:
This: <a href="{% url 'url-name' someUUID %}">
Or this: <a href="{% url 'url-name' slug=someUUID %}">
not: <a href="{% url 'url-name' url=someUUID %}">
DetailView uses slug_field = 'someUUIDField'
For some reason I wrote url instead of slug. Now it works.
Maybe you wrote wrong also, make sure you use slug=, if you use <slug:slug>.

Related

how to format a a url to return something like this "product/4/improved-led-lamp" in the template

I'm trying to return a formatted url that will look like this "edit-book/4/improved-led-lamp" using the {% url %} tag
I've tried {% url 'dashboard:editbook' 4 slug %}
here is the root url.py
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('', include('home.urls')),
path('dashboard/', include('dashboard.urls')),
path('admin/', admin.site.urls),
]
here is my dashboard app's urls,py
from django.urls import path
from . import views
app_name = 'dashboard'
urlpatterns = [
path('edit-book/<int:id>/<slug:title>', views.BookView.as_view(), name='editbook'),
]
if I visit "edit-book/4/improved-led-lamp" in my browser, it resolves, but when I try to reproduce this in the view using {% url %} tag, it throws noReverseMatch error
this is the error
screenshot of error
Your syntax looks correct and if slug variable consists of slug ([-a-zA-Z0-9_]+) it should be working.
Look into contents of slug. Error screenshot shows that it's an empty string.

How to change URLs based on a column data from the Database

I tried a lot but I am just not able to reach the exact solution.
I want to change the URLs of the list which is being generated by a for loop in HTML.
Here is my code for that view in views.py file:
class DashboardHomeViewClass(View):
def get(self, request, *args, **kwargs):
device_objects = device_user_data.objects.filter(User_Name = request.user.username)
device_list = []
for device in device_objects:
device_list.append(device.Device_Alias_Data)
context_logged = {'device_list': device_list}
return render(request, "dashboardhometemplate.html", context_logged)
Here is the code where this context is being used in the HTML template:
{%for item in device_list%}
<li> <i class="fa fa-bar-chart"></i><span class="hide-menu">{{item}}</span>
{% endfor %}
Now what I need exactly is: Different links should open on clicking different list view items based on device_Alias_Data.
eg : http://127.0.0.1:8000/dashboard/{{Device_Alias_Data}}
where Device_Alias_Data is character varying field in a table named device_user_data in my database.
Here is my urls.py file :
from django.conf.urls import url
from django.contrib import admin
from dashboardhome.views import DashboardHomeViewClass
from dashboardhome.views import login_view
from django.contrib.auth.views import login
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^login/$', login ,{'template_name': 'login_template.html'}),
url(r'^dashboard/$', DashboardHomeViewClass.as_view()),
]
First you should make some tweaks to your urls.py file for this to work:
app_name = "dashboardhome"
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^login/$', login ,{'template_name': 'login_template.html'}),
url(r'^dashboard/$', DashboardHomeViewClass.as_view(), name="dashboard"),
]
Here we added app_name and name attribute of the url method, this way we can make use of Django Reverse Resolution of urls
After that you can use template builtin url tag, like this:
{%for item in device_list%}
<li> <i class="fa fa-bar-chart"></i><span class="hide-menu">{{item}}</span>
{% endfor %}
And this gonna result in a url like this:
http://127.0.0.1:8000/dashboard/{{item}}
Make sure to check out the links for more info.
I hope this will help.
can use def get_absolute_url() method in model.py by importing django.url.reverse
and using url name.

NoReverseMatch in Django 1.10

Here is my url.py
from django.conf.urls import url
from django.contrib import admin
from app import views, auth
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', views.index, name = 'index'),
url(r'^login/', auth.login, name = 'login'),
url(r'^logout/', auth.logout, name = 'logout'),
]
When I'm using in template <li>Administration</li> get error
NoReverseMatch at /
Reverse for 'admin' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []
So can any one tell me how to solve this? Thank you very much.
Use admin:index if you want to have an url to /admin/ site.
If you install django-extensions you can use ./manage.py show_urls to get the list of urls for your app
Set admin url in your project urls.py, same folder as your settings.py
Url(r'^admin/', admin.site.urls),
Then call it in your template:
<a href="{% url 'admin:index' %} > link </a>
You should use admin namespace, like written in the docs. You could also look on other admin urls in that namespace.
{% url 'admin:index' %}

Logout Page not working in Django

I'm trying to create a logout page for django.
This is the views.py file:
def index(request):
if not request.user.is_authenticated():
return redirect('webapp/login.html')
else:
result = Hello_World.delay()
somethingDownByCelery = result.get(timeout=2)
context = {'somethingDownByCelery': somethingDownByCelery, 'userName': request.user.username}
return render(request, 'webapp/index.html', context)
def loginUser(request):
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
return redirect('webapp/index.html')
else:
return redirect('webapp/disabled.html')
else:
condition = "Invalid Login"
context = {'condition', condition}
return render(request, 'webapp/index.html', context)
def logoutUser(request):
logout(request)
return redirect('webapp/index.html')
This is the index page after the logout is initiated.
{% load staticfiles %}
<link rel="stylesheet" type="text/css" href="{% static 'WebApp/style.css' %}"/>
Hello World, this will call celery!
<html>
<br>
</html>
{{ somethingDownByCelery }}
<html>
<br>
<br>
</html>
Hello! {{ userName }}
<html>
<br>
<br>
</html>
<form action="{% url 'WebApp:logout'%}" method="post">
{% csrf_token %}
<p> Logout </p>
<input type="submit" value="Submit">
</form>
What should happen is that the user would logout, and get redirected to the index page, whereas since the user is not logged in, it will redirect the user to a login page.
However, it only shows me: The view django.contrib.auth.logout didn't return an HttpResponse object.
This is the project root urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
from WebApp import views
from StripCal import views
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'Dashboard_Web.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^webapp/', include('WebApp.urls', namespace="WebApp")),
)
This is the app's urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
from WebApp import views
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^login', views.login, name='login'),
url(r'^logout', views.logout, name='logout'),
)
try this:
from django.shortcuts import HttpResponseRedirect
def logoutUser(request):
logout(request)
return HttpResponseRedirect('/loginpage/')
instead of webapp/index.html, you should give the URL of your login page like /loginpage/ inside HttpResponseRedirect
Instead of writing your own, use Djangos builtin logout view for this.
#urls.py
from django.contrib.auth.views import logout
url(r'^sign-out/$', logout, {'template_name': 'index.html', 'next_page': '/'}, name='sign-out'),
Docs are found here and now you can link to this without the use of a form and Django will take care of doing the redirection for you.
I know that this is a old post, but no answer addressed what went wrong in the code so here it is.
In the webapp urls.py file view must be pointing to logoutUser view and not logout view.
and similarly with the login view
from django.contrib import admin
from WebApp import views
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^login', views.loginUser, name='login'),
url(r'^logout', views.logoutUser, name='logout'),
)
Now the url function is taking the intended view method as an argument
First things first.
Your function should look similar to this one:
def logout_view(request):
logout(request)
return redirect('/login')
To use logout, you have to import logout like this:
from django.contrib.auth import logout
If you are redirecting user on the basis of User.is_authenticated, it would never redirect because if the user is not logged in, an anonymous user it created.
You can do something like ths:
def home(request):
if request.user.is_anonymous == True:
return redirect('/login')
else:
return render(request,"index.html",{'nav':request.user})

Django SyntaxError on url tag in template

I have a Django app that continues to be fussy about the {% url ... %} templating tag. I've fixed this before, but it now it's giving me a SyntaxError on loading the template.
Working backwards
Start with the relevant template lines:
<a href="{% url 'project-index' %}">
<img src="{{ STATIC_URL }}images/logo.png" alt="Logo">
</a>
Function I'm trying to reverse() to in views.py:
def index (request):
return render(request, "project/index.html", { "user" : request.user })
Url patterns (urls.py):
urlpatterns = patterns("project.views",
url(r'^$', "index", name="project-index"),
url(r'^login/?$', "login", name="project-login"),
url(r'^logout/?$', "logout", name="project-logout"),
)
Main app included urls (urls.py):
urlpatterns = patterns('',
url('', include('project.urls')),
)
Here is a gist of the traceback.
The traceback doesn't show the exact line number for the template error, so here's what it gives me:
Error during template rendering
In template /Users/josh/Dropbox/Projects/app/sc/templates/layouts/base.html, error at line 47
The "old" url tag doesn't accept quotes but this will be deprecated. Use {% load url from future %} in Django <1.5. Check the Forwards compatibility section in documentation https://docs.djangoproject.com/en/1.4/ref/templates/builtins/#url

Categories