Django NoReverseMatch when all others seems to work - django

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')

Related

can solve this error ? ( NoReverseMatch )

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.

Could not parse the remainder: '-save' from 'waypoints-save'

I am trying a simple app in geodjango by following http://invisibleroads.com/tutorials/geodjango-googlemaps-build.html.
My view function is
# Import django modules
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.template.loader import render_to_string
# Import system modules
import json
# Import custom modules
from waypoints.models import Waypoint
def save(request):
'Save waypoints'
for waypointString in request.POST.get('waypointsPayload', '').splitlines():
waypointID, waypointX, waypointY = waypointString.split()
waypoint = Waypoint.objects.get(id=int(waypointID))
waypoint.geometry.set_x(float(waypointX))
waypoint.geometry.set_y(float(waypointY))
waypoint.save()
return HttpResponse(simplejson.dumps(dict(isOk=1)), mimetype='application/json')
And urls.py is
from django.conf.urls import patterns, include, url
urlpatterns = patterns('waypoints.views',
url(r'^$', 'index', name='waypoints-index'),
url(r'^save$', 'save', name='waypoints-save'),
)
It is showing an error http://dpaste.com/3EJVX0G
Template index.html is here http://pastebin.com/125Dm6Bz
Please help me.I am new to django.
The parameter to the {% url %} tag must always be in quotes if it's a literal string (this has been the case since version 1.5, which is quite a long time).
The one that's causing the error is this:
$.post("{% url waypoints-save %}"
which should be:
$.post("{% url "waypoints-save" %}"
but you make the same mistake several times in that template.

NoReverseMatch at / after upgrade from 1.3 to 1.4

The project was working fine with Django 1.3, once I updated to 1.4 results on this error:
NoReverseMatch at /
Reverse for 'app_list' with arguments '()' and keyword arguments '{'app_label': ''}' not found.
urls.py:
from views import home
urlpatterns = patterns('',
(r'^$', home),
(r'^projects/', include('projects.urls')),
(r'^admin/', include(admin.site.urls)),
)
projects.url:
from django.conf.urls.defaults import *
from views import *
urlpatterns = patterns('projectcenter.projects.views',
url(r'project/(\d+)/$', project_detail, name = 'project_detail' ),
)
views.py
from django.http import HttpResponse
from django.template import RequestContext
from django.shortcuts import render_to_response
from projects.models import Project
def home(request):
template = 'index.html'
user = request.user
projects = Project.objects.current()
if projects:
map_center = projects[0].location
else:
map_center = (0, 0)
data = {'user': user,
'projects': projects,
'map_center': map_center ,
}
return render_to_response(template, data,
context_instance=RequestContext(request))
I ran into this today and solved it by just updating the relevant line to:
url(r'^admin/', include(admin.site.urls)),
Not sure why that fixed it though.
In the index.html template I was inheriting from this template:
{% extends "admin/change_list.html"%}
I removed the line above and it worked fine.
I really don't know why it worked.
Thanks.

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' %}

How to use different form in Django-Registration

Django-Registration has several form classes in the forms.py file. One is "class RegistrationFormTermsOfService(RegistrationForm) ..
What do I change in the rest of Django Registration code to enable this form in my registration flow instead of RegistrationForm?
Updating the accepted answer to conform with Django 1.5 and the latest version of django-registration:
in urls.py:
from registration.forms import RegistrationFormTermsOfService
from registration.backends.default.views import RegistrationView
urlpatterns = patterns('',
url(r'^accounts/register/$', RegistrationView.as_view(form_class=RegistrationFormTermsOfService), name='registration_register'),
# your other URLconf stuff follows ...
)
then update the registration_form.html template and add a tos field, e.g.:
<p>
<label for="id_tos">I accept the terms of service</label>
{% if form.tos.errors %}
<p class="errors">{{ form.tos.errors.as_text }}</p>
{% endif %}
{{ form.tos }}
</p>
You can simply go into your urls.py and override the form class by doing something like:
from registration.forms import RegistrationFormTermsOfService
(r'^accounts/register/$', 'registration.views.register', {'form_class' : RegistrationFormTermsOfService}),
Here is a practical example using a custom form and backend which sets username == email address, and only prompts the user for an email address at registration. In, for e.g. my_registration.py:
from django.conf import settings
from django.contrib.sites.models import RequestSite
from django.contrib.sites.models import Site
from registration import signals
from registration.forms import RegistrationForm
from registration.models import RegistrationProfile
from registration.backends.default import DefaultBackend
class EmailRegistrationForm(RegistrationForm):
def __init__(self, *args, **kwargs):
super(EmailRegistrationForm,self).__init__(*args, **kwargs)
del self.fields['username']
def clean(self):
cleaned_data = super(EmailRegistrationForm,self).clean()
if 'email' in self.cleaned_data:
cleaned_data['username'] = self.cleaned_data['username'] = self.cleaned_data['email']
return cleaned_data
class EmailBackend(DefaultBackend):
def get_form_class(self, request):
return EmailRegistrationForm
In my_registration_urls.py:
from django.conf.urls.defaults import *
from django.views.generic.simple import direct_to_template
from registration.views import activate
from registration.views import register
urlpatterns = patterns('',
url(r'^activate/complete/$',
direct_to_template,
{ 'template': 'registration/activation_complete.html' },
name='registration_activation_complete'),
# Activation keys get matched by \w+ instead of the more specific
# [a-fA-F0-9]{40} because a bad activation key should still get to the view;
# that way it can return a sensible "invalid key" message instead of a
# confusing 404.
url(r'^activate/(?P<activation_key>\w+)/$',
activate,
{ 'backend': 'my_registration.EmailBackend' },
name='registration_activate'),
url(r'^register/$',
register,
{ 'backend': 'my_registration.EmailBackend' },
name='registration_register'),
url(r'^register/complete/$',
direct_to_template,
{ 'template': 'registration/registration_complete.html' },
name='registration_complete'),
url(r'^register/closed/$',
direct_to_template,
{ 'template': 'registration/registration_closed.html' },
name='registration_disallowed'),
(r'', include('registration.auth_urls')),
)
Then in your core urls.py, ensure you include:
url(r'^accounts/', include('my_registration_urls')),
You'll need to write a new registration form somewhere in your project. You can inherit off of the existing authentication form if you're just expanding new fields. You'll then want to write a new backend to process the form. Finally you'll need to write your own url and auth_urls and redefine the urls to switch the backend and authentication form in the views by changing the variables that get passed to the view.
It's helpful to break open the source to see how things are working. I base my structure off of the original django-registration code to keep things consistent.
As to django 1.11 and django-registration 2.2 there are some updated imports... so if you get "No module named 'registration'" this could be the problem...
Replace:
from registration.backends.hmac.views import RegistrationView
by from django_registration.backends.activation.views import RegistrationView
from registration.forms import RegistrationForm
by from django_registration.forms import RegistrationForm
include('django_registration.backends.hmac.urls') in urls
by include('django_registration.backends.activation.urls')
Just to name a few... ;)
Src: https://django-registration.readthedocs.io/en/3.0/custom-user.html