NoReverseMatch in Django for username pass to view - django

I'm working on a basic Django app (just learning, this is my third small project), and I'm trying to add links to allow a list of every post a user has made. I've got the URLS being created OK (domain/posts/username), and I want this to link to a view (that I've already created, and which works when the parameters I want to pass are hard-coded to a single value), passing the positional arguments to the view. However, I'm running aground on the RegEx / Urls part of things. I think this is the relevant info:
urls.py:
urlpatterns = [
url(r'^create/', views.create, name='create'),
url(r'^(?P<pk>[0-9]+)/upvote', views.upvote, name='upvote'),
url(r'^(?P<pk>[0-9]+)/downvote' , views.downvote, name='downvote'),
url(r'^userposts/(?P<user>[.]+)', views.userposts, name='userposts')
views.py
def userposts(request,user):
posts = models.Post.objects.filter(url__contains=user)
return render(request, 'posts/userposts.html', {'posts': posts})
home.html
a href="{{ post.url}}">{{ post.title }}</a><br/>{{ post.pub_date_pretty }} by
{{ post.author.username }}</td>
With the (?P[.]+) part of the last url line removed, the page will render OK, but the links don't work (as there's no user parameter being passed). With the regex present (not only this one, but the many others I've tried), I get a NoReverseMatch error:
NoReverseMatch at /
Reverse for 'userposts' with no arguments not found. 1 pattern(s) tried: ['posts/userposts/(?P<user>[.]+)']
Request Method: GET
Request URL: http://127.0.0.1:8000/
Django Version: 1.11
Exception Type: NoReverseMatch
Exception Value:
Reverse for 'userposts' with no arguments not found. 1 pattern(s)
tried: ['posts/userposts/(?P<user>[.]+)']
Exception Location: /usr/local/lib/python3.5/dist-
packages/django/urls/resolvers.py in _reverse_with_prefix, line 497
Python Executable: /usr/bin/python3
Python Version: 3.5.2
Python Path:
['/home/darren/redditclone/redditclone',
'/usr/lib/python35.zip',
'/usr/lib/python3.5',
'/usr/lib/python3.5/plat-x86_64-linux-gnu',
'/usr/lib/python3.5/lib-dynload',
'/home/darren/.local/lib/python3.5/site-packages',
'/usr/local/lib/python3.5/dist-packages',
'/usr/lib/python3/dist-packages']
Server time: Thu, 18 May 2017 18:21:11 +0000

Your userposts is defined like
url(r'^userposts/(?P<user>[.]+)', views.userposts, name='userposts')
which means it requires a user argument to resolve.
To pass such an argument, you'd do
{% url 'posts:userposts' user_goes_here %}
Try this instead
{{ post.author.username }}

Related

adding a url in django-template

i tried to add a url in django template which is supposedly to log out a user
<div>logout</div>
but it threw a NoReverseMatch
the template:
<header class="grid-header header">
<div class='logo-text'>Nitro fleet</div>
<div class="profile-detail">
{% if user.is_authenticated %}
<img class="profile-img" src="{{user.picture.url}}" />
<div>
<div>{{user.username}}</div>
<div>logout</div>
</div>
{%endif%}
</div>
</header>
the url of the app (accounts) that has the logout view:
from django.urls import path
from . import views
appname = 'accounts'
urlpatterns = [
path('register', views.register_view , name='user_register'),
path('login', views.user_login , name='user_login'),
path('logout', views.user_logout , name='user_logout'),
]
the view function:
def user_logout(request):
logout(request)
return HttpResponseRedirect(request.path_info)
the complete error log:
NoReverseMatch at /maintenance/
Reverse for 'accounts.views.user_logout' not found. 'accounts.views.user_logout' is not a valid view function or pattern name.
Request Method: GET
Request URL: http://127.0.0.1:8000/maintenance/
Django Version: 3.2.9
Exception Type: NoReverseMatch
Exception Value:
Reverse for 'accounts.views.user_logout' not found. 'accounts.views.user_logout' is not a valid view function or pattern name.
Exception Location: C:\Users\PC\AppData\Local\Programs\Python\Python310\lib\site-packages\django\urls\resolvers.py, line 694, in _reverse_with_prefix
Python Executable: C:\Users\PC\AppData\Local\Programs\Python\Python310\python.exe
Python Version: 3.10.0
Python Path:
['C:\\Users\\PC\\Desktop\\nitrofleet',
'C:\\Users\\PC\\AppData\\Local\\Programs\\Python\\Python310\\python310.zip',
'C:\\Users\\PC\\AppData\\Local\\Programs\\Python\\Python310\\DLLs',
'C:\\Users\\PC\\AppData\\Local\\Programs\\Python\\Python310\\lib',
'C:\\Users\\PC\\AppData\\Local\\Programs\\Python\\Python310',
'C:\\Users\\PC\\AppData\\Local\\Programs\\Python\\Python310\\lib\\site-packages']
Server time: Mon, 31 Jan 2022 20:43:51 +0000
Just use the name of the view:
{% url 'accounts:user_logout' %}

Django error: Reverse for 'password_reset_confirm' with no arguments not found

I am using Django 1.11 to build an user account application. My urls for my account app is as Code 1 as below. And also I have a templates/registrations folder and several template files there:
enter image description here
After I input the email address and I receive the email with the following link:
http://127.0.0.1:8000/account/password-reset/confirm/MQ/4ra-66d3672f1d340589fbf9/
I click the above link and the browser redirects to this link:
http://127.0.0.1:8000/account/password-reset/confirm/MQ/set-password/
And the error prompts:
NoReverseMatch at /account/password-reset/confirm/MQ/set-password/
Reverse for 'password_reset_confirm' with no arguments not found. 1 pattern(s) tried: ['account/password-reset/confirm/(?P[-\w]+)/(?P[-\w]+)/$']
Request Method: GET
Request URL: http://127.0.0.1:8000/account/password-reset/confirm/MQ/set-password/
Django Version: 1.11.7
Exception Type: NoReverseMatch
Exception Value:
Reverse for 'password_reset_confirm' with no arguments not found. 1 pattern(s) tried: ['account/password-reset/confirm/(?P[-\w]+)/(?P[-\w]+)/$']
Please help me how to solve this problem. It seems that after I click the link, the Django fails to render the password_reset_confirm.html under templates/registration folder.
Code 1:
# restore password urls
url(r'^password-reset/$', auth_views.PasswordResetView.as_view(), name='password_reset'),
url(r'^password-reset/done/$', auth_views.PasswordResetDoneView.as_view(), name='password_reset_done'),
url(r'^password-reset/confirm/(?P<uidb64>[-\w]+)/(?P<token>[-\w]+)/$',
auth_views.PasswordResetConfirmView.as_view(), name='password_reset_confirm'),
url(r'^password-reset/complete/$',
auth_views.PasswordResetCompleteView.as_view(), name='password_reset_complete'),
Django's error message is saying that your code has tried to reverse password_reset_confirm to its url, but you haven't supplied the uid64 and token arguments that the url pattern requires. You should locate the section of your code where you perform the reverse() and update it to supply the arguments:
reverse('password_reset_confirm',args=(uid64, token))
Go to the password reset confirm template file and get rid off the action on the form like this
<form method="post"> </form>
instead of this :
<form action={% url 'your template file name'%} method="post"></form>
urls.py:
path('accounts/reset_password_confirm/<uidb64>/<token>/', PasswordResetConfirmView.as_view(), name='reset_password_confirm'),
Changing URL as above worked for me. Although, I am still not getting email. The error disappeared.
path('users/password_reset/', PasswordResetView.as_view(
template_name='commons/password_reset_form.html',
subject_template_name='commons/password_reset_subject.txt',
email_template_name='commons/password_reset_email.html',
success_url='done',), name="password_reset"),
path('users/password_reset/done/',
PasswordResetDoneView.as_view(
template_name='commons/password_reset_done.html'),name="password_reset_done"),
path('users/reset/<uidb64>/<token>/', PasswordResetConfirmView.as_view(
template_name='commons/password_reset_confirm.html',
success_url='/users/reset/done/'),name="password_reset_confirm"),
path('users/reset/done/',
PasswordResetCompleteView.as_view(template_name='commons/password_reset_complete.html'),
name="password_reset_complete"),

Could not parse the remainder Django

I've been trying to write a custom template tag to shorten links with bitly, I've attached the code and error I've been getting below. I've tried to look into the documentation provided by Django but cannot see what it is that I am doing wrong.
I've put my templatetag in the following layout:
scribbler/
models.py
templatetags/
__init__.py
shortenlink.py
views.py
the custom tag file that I've written:
shortenlink.py
from django import template
from django.conf import settings
from urllib import urlencode
from urllib2 import urlopen
register = template.Library()
#register.simple_tag
def bitlyshort(the_url):
endpoint = 'https://api-ssl.bitly.com/v3/shorten?access_token={0}&longUrl={1}&format=txt'
req = urlencode(endpoint.format(settings.ACCESS_KEY, the_url))
return urlopen(req).read()
part of the template that uses the template tag:
template
{% load shortenlink %}
<p>{{ bitlyshort "http://www.google.com" }}</p>
error
TemplateSyntaxError at /user/sankaetp/
Could not parse the remainder: ' "http://www.google.com"' from 'bitlyshort "http://www.google.com"'
Request Method: GET
Request URL: http://localhost:8000/user/sankaetp/
Django Version: 1.4.1
Exception Type: TemplateSyntaxError
Exception Value:
Could not parse the remainder: ' "http://www.google.com"' from 'bitlyshort "http://www.google.com"'
Exception Location: /Users/sankaetp/virtualenvs/myproject/lib/python2.7/site-packages/django/template/base.py in __init__, line 563
Python Executable: /Users/sankaetp/virtualenvs/myproject/bin/python
Python Version: 2.7.3
Python Path:
['/Users/sankaetp/virtualenvs/myproject/bin/django_worksquid',
'/Users/sankaetp/virtualenvs/myproject/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg',
'/Users/sankaetp/virtualenvs/myproject/lib/python2.7/site-packages/pip-1.1-py2.7.egg',
'/Users/sankaetp/virtualenvs/myproject/lib/python2.7/site-packages/djangoembed-0.1.1-py2.7.egg',
'/Users/sankaetp/virtualenvs/myproject/lib/python2.7/site-packages/httplib2-0.7.4-py2.7.egg',
'/Users/sankaetp/virtualenvs/myproject/lib/python2.7/site-packages/BeautifulSoup-3.2.1-py2.7.egg',
'/Users/sankaetp/virtualenvs/myproject/lib/python27.zip',
'/Users/sankaetp/virtualenvs/myproject/lib/python2.7',
'/Users/sankaetp/virtualenvs/myproject/lib/python2.7/plat-darwin',
'/Users/sankaetp/virtualenvs/myproject/lib/python2.7/plat-mac',
'/Users/sankaetp/virtualenvs/myproject/lib/python2.7/plat-mac/lib-scriptpackages',
'/Users/sankaetp/virtualenvs/myproject/lib/python2.7/lib-tk',
'/Users/sankaetp/virtualenvs/myproject/lib/python2.7/lib-old',
'/Users/sankaetp/virtualenvs/myproject/lib/python2.7/lib-dynload',
'/Users/sankaetp/.pythonbrew/pythons/Python-2.7.3/lib/python2.7',
'/Users/sankaetp/.pythonbrew/pythons/Python-2.7.3/lib/python2.7/plat-darwin',
'/Users/sankaetp/.pythonbrew/pythons/Python-2.7.3/lib/python2.7/lib-tk',
'/Users/sankaetp/.pythonbrew/pythons/Python-2.7.3/lib/python2.7/plat-mac',
'/Users/sankaetp/.pythonbrew/pythons/Python-2.7.3/lib/python2.7/plat-mac/lib-scriptpackages',
'/Users/sankaetp/virtualenvs/myproject/lib/python2.7/site-packages',
'/Users/sankaetp/virtualenvs/myproject/lib/python2.7/site-packages/PIL']
Server time: Sun, 26 Aug 2012 18:54:26 -0500
The error is on this line:
<p>{{ bitlyshort "http://www.google.com" }}</p>
Template tags use {% ... %} (template filters use {{ ... }}). Try:
<p>{% bitlyshort "http://www.google.com" %}</p>
There is an alternative way to cause this error:
Instead of:
{{ data|filter }}
If you use:
{{ data | filter }} <!-- Note Spaces -->
The spaces on either side of the | character will cause an exception during page render.

Exception Value: Caught NoReverseMatch while rendering: Reverse for 'begin' with arguments '(u'google-oauth2',)'

I make google authorization (Oauth 2.0) with django-social-auth and getting error
Django Version: 1.3
Exception Type: TemplateSyntaxError
Exception Value:
Caught NoReverseMatch while rendering: Reverse for 'begin' with arguments '(u'google-oauth2',)' and keyword arguments '{}' not found.
Exception Location: /usr/local/lib/python2.6/site-packages/django/template/defaulttags.py in render, line 450
Python Executable: /usr/local/bin/python
Python Version: 2.6.6
Template
<a rel="nofollow" href="{% url begin "google-oauth2" %}" ><img src="{{ MEDIA_URL }}social/google.png" id="google"></a>
url.py
urlpatterns = patterns('',
url(r'', include('social_auth.urls')),
)
social_auth.urls
urlpatterns = patterns('',
url(r'^login/(?P<backend>[^/]+)/$', auth, name='begin'),
url(r'^complete/(?P<backend>[^/]+)/$', complete, name='complete'),
url(r'^associate/(?P<backend>[^/]+)/$', associate, name='associate_begin'),
url(r'^associate/complete/(?P<backend>[^/]+)/$', associate_complete,
name='associate_complete'),
url(r'^disconnect/(?P<backend>[^/]+)/$', disconnect, name='disconnect'),
)
What am I doing wrong?
Please help to find the solution.
You are on django 1.3. Have you included the new url template tag with {% load url from future %}. If you have then your syntax for the url tag is incorrect and would need to be {% url 'begin' 'google-oauth2' %}. If you haven't then your syntax is correct.
Have you ensured that your social_auth.urls is being included correctly? To do this (with debug enabled) manually go to http://yourdevserver/login/google-oauth2/ and ensure you don't see a 404 page. If you do you will be able to see what url's where attempted and that should give you direction on how to fix it.

NoReverseMatch Error

I keep getting this error for the django login system. Here is part of my urls.py:
(r'^contractManagement/login', 'django.contrib.auth.views.login', {'template_name': 'login.html'}),
The exact error I am getting:
Exception Type: NoReverseMatch
Exception Value: Reverse for ''django.contrib.auth.views.login'' with arguments '()' and keyword arguments '{}' not found.
I can't understand why i am getting this error. If you need anything else let me know.
You don't show where you are trying to reverse this URL, but it looks like you have double-quoted it. If you're using the url tag, note that you don't need quotes around the url name:
{% url django.contrib.auth.views.login %}
not
{% url 'django.contrib.auth.views.login' %}
You see that ''the.unknown.view'' is reported including too many qoutes.
It is because the quoted syntax will be valid in Django 1.5 and higher. For Django 1.3 or 1.4, you should activate the future behavior by this line in the template:
{% load url from future %}
which is valid also for Django 1.5.
Example for Django 1.5+
{% url "path.to.some.view" %}
Classic syntax for Django <= 1.4.x (without "future" command) is:
{% url path.to.some.view %}
I would give your url a name (in order to do that, you need to use the url method) Also you should add a trailing slash to all your urls, cause the django CommonMiddleware is going to be doing a 302 redirect on all your urls if you don't:
from django.conf.urls.defaults import *
urlpatterns = patterns('',
url(r'^contractManagement/login/', 'django.contrib.auth.views.login', {'template_name': 'login.html'}, name='contract_login'),
)
Then you can use reverse in your code, or url in your templates, and if you ever decide to change the actual url (ie: changedCotractManagement/login/), as long as the name is the same, your code will still be good.
in code:
from django.core.urlresolvers import reverse
reverse('contract_login')
in template:
{% url contract_login %}
Edit: per MrOodles