can solve this error ? ( NoReverseMatch ) - django

I'm ratherly amatour in django and cant solve this problem,
error:
NoReverseMatch at /blog/
Reverse for 'single' with keyword arguments '{'pid': ''}' not found. 1 pattern(s) tried: \['blog/(?P\<pid\>\[0-9\]+)\\Z'\]
urls.py :
from django.urls import path
from blog.views import \*
from django.conf.urls.static import static
app_name= 'blog'
urlpatterns = \[
path('',home,name='home'),
path('\<int:pid\>',single, name='single'),
\]
views.py :
from django.shortcuts import render
from blog.models import Post
import datetime
def single(request,pid):
single_post= Post.objects.filter(pk=pid)
def counting_single_views(n):
n.counted_views += 1
n.save()
counting_single_views(single_post)
context = {'single_post':single_post}
return render(request,'blog/blog-single.html',context)
def home(request):
now = datetime.datetime.now()
posts= Post.objects.filter(published_date__lte= now)
context={'posts':posts}
return render(request,'blog/blog-home.html',context)
blog-home.html :
{% for post in posts %}
\<a href="{% url 'blog:single' pid=post.pk %}"\>\<h3\>{{post.title}}\</h3\>\</a\>
\<p class="excert"\>
{{post.content}}
\</p\>
{% endfor %}
i tried with id instead of pk , but no differ,

In your url file
path('\<int:pid\>',single, name='single'),
Replace it with
path('<int:pid>',single, name='single'),
and also note [#Manoj Kamble] point that can also happen

i got my answer,
infact i didn't change any of url tag,
i used
{% url 'blog:single' pid=post.pk %}
but in 'base.html' used
{% url 'blog:single' %}
i changed this and NoReverseMatch solved. thanks everyone.

Related

Switch language in Django with the translated url redirect

I have internationalization correctly installed.
It's works with urls like:
/en/bookings/ #English
/es/reservas/ #Spanish
In the home page the language switching works fine too.
- What's the issue?
When I change the language in a translated page, like /en/bookings/, if I turn the language to Spanish (es) I am redirected to /en/bookings/ again and I see the page in English.
If I change the prefix (like this answer) the redirection goes to /es/bookings/ that doesn't exists.
I don't want to be redirected to the home page.
- What I like?
If I am in the /en/bookings/ and switch to Spanish I want to be redirected to /es/reservas/, for all the translated urls.
What is the best way?
Thanks.
I had similar problem so I sending my resolution to save Your time.
main(urls.py)
from django.conf.urls import include, url
from django.conf.urls.i18n import i18n_patterns
urlpatterns = [
url(r'^i18n/', include('django.conf.urls.i18n')),
]
urlpatterns += i18n_patterns(
url(r'^', include('index.urls', namespace='index')),
)
(index.urls.py)
from django.conf.urls import url
from django.views.generic import TemplateView
from django.utils.translation import ugettext_lazy as _
urlpatterns = [
url(r'^$', TemplateView.as_view(template_name='index/index.html'), name='index'),
url(_(r'^python-programming/$'), TemplateView.as_view(template_name='index/new_page.html'),
name='new_page'),
]
Creating template tag to return urls for current location in all languages that we support (index.templatetags.helper_tags.py)
from django.template import Library
from django.core.urlresolvers import resolve, reverse
from django.utils.translation import activate, get_language
register = Library()
#register.simple_tag(takes_context=True)
def change_lang(context, lang=None, *args, **kwargs):
"""
Get active page's url by a specified language
Usage: {% change_lang 'en' %}
"""
path = context['request'].path
url_parts = resolve(path)
url = path
cur_language = get_language()
try:
activate(lang)
url = reverse(url_parts.view_name, kwargs=url_parts.kwargs)
finally:
activate(cur_language)
return "%s" % url
Creating middleware to change site language when user will click at alternative link to this sub site but in different language
(middleware.py)
from django.utils import translation
from django.conf import settings
from django.utils.deprecation import MiddlewareMixin
class LangBasedOnUrlMiddleware(MiddlewareMixin):
#staticmethod
def process_request(request):
if hasattr(request, 'session'):
active_session_lang = request.session.get(translation.LANGUAGE_SESSION_KEY)
if active_session_lang == request.LANGUAGE_CODE:
return
if any(request.LANGUAGE_CODE in language for language in settings.LANGUAGES):
translation.activate(request.LANGUAGE_CODE)
request.session[translation.LANGUAGE_SESSION_KEY] = request.LANGUAGE_CODE
Adding it to (settings.py) just after LocaleMiddleware
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'our_app.middleware.LangBasedOnUrlMiddleware',
]
Sample usage in template:
{% load i18n %}
{% load helper_tags %}
{% get_available_languages as languages %}
{% for lang_code, lang_name in languages %}
<a href="{{ request.scheme }}://{{ request.META.HTTP_HOST }}{% change_lang lang_code %}">
{% endfor %}
When I had the same problem, I implemented a custom template tag (current_url) that, given the request in context, re-renders the url for the active language:
{% load custom_tags %}
<ul>
{% get_language_info_list for LANGUAGES as languages %}
{% for language in languages %}
{# IMPORTANT! enclose the 'current_url' tag in a 'language' block #}
{% language language.code %}
<li {% if language.code == LANGUAGE_CODE %}class="active"{% endif %}>
{{ language.name_local }}
</li>
{% endlanguage %}
{% endfor %}
</ul>
Here is the code for the custom tag (custom_tags.py):
import six
import sys
from django.template import Node, TemplateSyntaxError, Library
from django.conf import settings
register = Library()
class CurrentURLNode(Node):
def __init__(self, asvar=None):
self.asvar = asvar
def render(self, context):
request = context['request']
from django.core.urlresolvers import reverse, NoReverseMatch
url = ''
try:
url = reverse(request.resolver_match.view_name, args=request.resolver_match.args, kwargs=request.resolver_match.kwargs, current_app=context.current_app)
except NoReverseMatch:
exc_info = sys.exc_info()
if settings.SETTINGS_MODULE:
project_name = settings.SETTINGS_MODULE.split('.')[0]
try:
url = reverse(project_name + '.' + request.resolver_match.view_name,
args=request.resolver_match.args, kwargs=request.resolver_match.kwargs,
current_app=context.current_app)
except NoReverseMatch:
if self.asvar is None:
six.reraise(*exc_info)
else:
if self.asvar is None:
raise
if self.asvar:
context[self.asvar] = url
return ''
else:
return url
#register.tag
def current_url(parser, token):
bits = token.split_contents()
bits = bits[1:]
asvar = None
if len(bits) >= 2 and bits[-2] == 'as':
asvar = bits[-1]
bits = bits[:-2]
if len(bits):
raise TemplateSyntaxError("Unexpected arguments to current_url tag")
return CurrentURLNode(asvar)
There is no need to use the 'set_language' django view. There is no need to make a POST request to change the active language. With only html archors linking all your internationalized content together, it's better for SEO.

Django NoReverseMatch when all others seems to work

Every other reverse url (edit, delete, etC) seems to work, in my templates, models, etc but not this one in my business app views.py (jump down for error):
from django.views.generic import ListView, DetailView
from django.views.generic.edit import UpdateView, DeleteView, CreateView
from django.core.urlresolvers import reverse
from business.models import Country
{...}
# Delete
class CountryDeleteView(DeleteView):
model = Country
template_name_suffix = '_delete_form'
success_url = reverse('country_listview') # commenting this out makes everything work
The project urls.py:
from django.conf.urls import patterns, include, url
urlpatterns += patterns('',
url(r'^business/', include('business.urls')),
)
The business app urls.py:
from django.conf.urls import patterns, url
from business.views import CountryListView, CountryDetailView
from business.views import CountryCreateView, CountryUpdateView, CountryDeleteView
urlpatterns = patterns('',
url(r'^country/$', CountryListView.as_view(), name='country_listview'),
url(r'^country/(?P<pk>\d+)/$', CountryDetailView.as_view(), name='country_detailview'),
url(r'^country/create/$', CountryCreateView.as_view(), name='country_createview'),
url(r'^country/(?P<pk>\d+)/update/$', CountryUpdateView.as_view(), name='country_updateview'),
url(r'^country/(?P<pk>\d+)/delete/$', CountryDeleteView.as_view(), name='country_deleteview'),
)
I use model_listview instead of just model_list because the ListView generic edit view already passes model_list in the context by default (I haven't specified in my ListView subclass what I should want my context variable to be named) and it clashed with this code in template country_list.html:
<ul>
{% for c in country_list %}
<li>{{ c.name }}<br>
Detalii
Modifica
Sterge
</li>
{% endfor %}
</ul>
And error:
NoReverseMatch at /business/country/
Reverse for 'country_listview' with arguments '()' and keyword
arguments '{}' not found.
Request Method: GET
Request URL: _removed_ip_:8000/business/country/
Django Version: 1.4.3
Exception Type: NoReverseMatch
Exception Value:
Reverse for 'country_listview' with arguments '()' and keyword
arguments '{}' not found.
Exception
Location: /usr/lib/python2.7/site-packages/django/core/urlresolvers.py
in _reverse_with_prefix, line 396
Python Executable: /usr/bin/python
Python Version: 2.7.3
It could be that the form is defined before the urls have been loaded. Try reverse_lazy and see if that works.
Untested:
from django.core.urlresolvers import reverse_lazy
...
success_url = reverse_lazy('country_listview')

NoReverseMatch in render_to_response with django-social-auth

I would like to make just a page that has link to login to twitter/facebook/google with django-social-auth.
but I get a error NoReverseMatch: Reverse for '' with arguments '(u'twitter',)' and keyword arguments '{}' not found.
def index(request):
ctx = {}
return render_to_response('index_before_login.html', {}, RequestContext(request))
index_before_login.html is following
<li>Enter using Twitter</li>
urls.py is following
urlpatterns = patterns('',
url(r'^$', 'lebabcartoon.views.index'),
#url(r'^socialauth_', 'lebabcartoon.views.index'),
url('', include('social_auth.urls')),
my environment is
Django ver1.5
Python Version: 2.7.3
django-social-auth: 0.7.5
anyideas?
Wrap url name in quotes
{% url 'socialauth_begin' 'twitter' %}
To save someone using the new python-social-auth and django > 1.4
Use this :
{% url 'social:begin' 'twitter' %}
I had a similar problem, try adding the following to the url.py file in your project.
url(r'auth/', include('social_auth.urls'))
And also make sure your url parameters are wrapped in quotes like so.
{% url "socialauth_begin" "twitter" %}

Django NoReverseMatch

I have the following setup:
/landing_pages
views.py
urls.py
In urls.py I have the following which works when I try to access /competition:
from django.conf.urls.defaults import *
from django.conf import settings
from django.views.generic.simple import direct_to_template
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^competition$', 'landing_pages.views.page', {'page_name': 'competition'}, name="competition_landing"),
)
My views.py has something like this:
def page(request, page_name):
return HttpResponse('ok')
Then in a template I'm trying to do this:
{% load url from future %}
<a href="{% url 'landing_pages.views.page' page_name='competition'%}">
Competition
</a>
Which I apparently can't do:
Caught NoReverseMatch while rendering: Reverse for 'landing_pages.views.page' with arguments '()' and keyword arguments '{'page_name': u'competition'}' not found.
What am I doing wrong?
You ask in your comment to DrTyrsa why you can't use args or kwargs. Just think about it for a moment. The {% url %} tag outputs - as the name implies - an actual URL which the user can click on. But you've provided no space in the URL pattern for the arguments. Where would they go? What would the URL look like? How would it work?
If you want to allow the user to specify arguments to your view, you have to provide a URL pattern with a space for those arguments to go.
{% url [project_name].landing_pages.views.page page_name='competition' %}
Or better
{% url competition_landing 'competition' %}

django {% tag %} problem

I don't know if its me but {% tag ??? %} has bee behaving a bit sporadically round me (django ver 1.2.3). I have the following main.html file:
<html>
{% include 'main/main_css.html' %}
<body>
test! logout
test! logout
</body>
</html>
with the urls.py being:
from django.conf.urls.defaults import *
import settings
from login.views import *
from mainapp.views import *
from client.views import *
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Example:
# (r'^weclaim/', include('weclaim.foo.urls')),
(r'^login/$', 'login.views.login_view'),
(r'^logout/$', 'login.views.logout_view'),
(r'^$', 'mainapp.views.main_view'),
(r'^client/search/last_name/(A-Za-z)/$', 'client.views.client_search_last_name_view'),
#(r'^client/search/post_code/(A-Za-z)/$', 'client.views.client_search_last_name_view'),
# Uncomment the next line to enable the admin:
(r'^admin/', include(admin.site.urls)),
(r'^static/(?P<path>.*)$', 'django.views.static.serve',{'document_root': settings.MEDIA_ROOT}),
)
and the views.py for login being:
from django.shortcuts import render_to_response, redirect
from django.template import RequestContext
from django.contrib import auth
import mainapp.views
def login_view(request):
if request.method == 'POST':
uname = request.POST.get('username', '')
psword = request.POST.get('password', '')
user = auth.authenticate(username=uname, password=psword)
# if the user logs in and is active
if user is not None and user.is_active:
auth.login(request, user)
return redirect(mainapp.views.main_view)
else:
return render_to_response('loginpage.html', {'login_failed': '1',}, context_instance=RequestContext(request))
else:
return render_to_response('loginpage.html', {'dave': '1',}, context_instance=RequestContext(request))
def logout_view(request):
auth.logout(request)
return render_to_response('loginpage.html', {'logged_out': '1',}, context_instance=RequestContext(request))
and the views.py for clients being:
from django.shortcuts import render_to_response, redirect
from django.template import RequestContext
import login.views
def client_search_last_name_view(request):
if request.user.is_authenticated():
return render_to_response('client/client_search_last_name.html', {}, context_instance=RequestContext(request))
else:
return redirect(login.views.login_view)
Yet when I login it django raises an 'NoReverseMatch' for {% url client.views.client_search_last_name_view %} but not for {% url login.views.logout_view %}
Now why would this be?
The "client.views.client_search_last_name_view" url's regex capatures a value (with the parens), so in order to {% url %} it, you need to pass it a value for that parameter.
If you are creating a URL which is supposed to accept a last name the correct way would be as follows:
(r'^client/search/last_name/(?P<last_name>[a-zA-Z]+)/$',
'client.views.client_search_last_name_view'),
The (?P<last_name>[a-zA-Z]+) part of the regex allows you to capture the last name which is at least one character in length and then have it passed as an argument to your view function.
However you then need to ensure that your view does accept this argument:
def client_search_last_name_view(request, last_name):
...
The reason you cannot then do:
{% url client.views.client_search_last_name_view %}
is because your regex states (like the view) that it needs one argument, which is a string consisting of lower or upper cases letters from A to Z. So for example this would work:
{% url client.views.client_search_last_name_view 'somelastname' %}
If you want to give your URL a name as another answer has suggested you can, but that is a separate matter and has no effect other than shortening that template tag.
The reason {% url login.views.logout_view %} does work is because its entry in urls.py does not specify any arguments to be passed to the view and, through default alone you have not passed any.
AFAIK you want to add a name='foo' arg to each of your url regexes. That name is what is used in the reverse match. Like this:
urls.py
(r'^login/$', 'login.views.login_view', name="login"),
template.html
{% url login %}