Django reverse url with parameters to a class based view - python

I just started learning python and django and I have a question.
I got the assignment to turn function views into class based views. But my links wont work now.
these are from urls.py:
url(r'^$', ContactIndex.as_view()),
url(r'^add$', ContactAdd.as_view()),
url(r'^([0-9]+)/update$', ContactUpdate.as_view()),
url(r'^([0-9]+)/view$', ContactView.as_view()),
This is my link :
{% url rtr_contact.views.ContactView contact.id %}
but this doesnt work it says:
Caught NoReverseMatch while rendering: Reverse for 'rtr_contact.views.ContactView' with arguments '(20L,)' and keyword arguments '{}' not found.

To make url reversing easy, I recommend that you always name your url patterns.
url(r'^$', ContactIndex.as_view(), name="contact_index"),
url(r'^add$', ContactAdd.as_view(), name="contact_add"),
url(r'^([0-9]+)/update$', ContactUpdate.as_view(), name="contact_update"),
url(r'^([0-9]+)/view$', ContactView.as_view(), name="contact_view"),
Then in the template:
{% url contact_view contact.id %}

Related

Django 3 - NoReverseMatch

I'm somehow new to Django, and I don't know how to resolve what seems to be a simple bug. A lot of peoples asked more or less the same question here but any to their fixes worked for me.
So I have 2 apps, one that will work as the main menu for other apps:
Main Menu urls.py :
re_path(r'^elec/boq/', include('a0101_boq_elec_main.urls', namespace="SAMM")),
Then in the urls.py of that app I have this:
app_name='BoqElecMM'
urlpatterns = [
path('', views.boq_index.as_view(), name='boqIndex'),
path('search/', views.SearchResultView.as_view(), name='searchResult'),
path('<int:boq_project_id>', views.BoqProjectInfo.as_view(), name='BPInfo'),
]
But when I'm trying to use this in my template: <a href="{% url 'BoqElecMM:BPInfo' %}"> , I'm getting this Django error :
NoReverseMatch at /elec/boq/
Reverse for 'BPInfo' not found. 'BPInfo' is not a valid view function or pattern name.
Could some of you tell me please, what I'm doing wrong here?
Thank you in advance.
You need to pass a value for the boq_project_id parameter, so for example
{% url 'BoqElecMM:BPInfo' boq_project_id=42 %}
Of course the value you pass to the boq_project_id is normally the id of the project object. So for example, if in your template you have a project object, you can write:
{% url 'BoqElecMM:BPInfo' boq_project_id=project.pk %}
if you have an namespace=… as well, then this should also be prefixed, so with the data in your view, it is:
{% url 'SAMM:BoqElecMM:BPInfo' boq_project_id=project.pk %}

Django NoReverseMatch with correct arguments

After looking through pages of similar answers, I regret to say that I'm still stumped. I'm pretty sure it's an error in the urlconf but anywho, here's all the relative info:
URLCONF in APP
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^tenants/$', views.tenant_index, name = 'tenant_index'),
url(r'^(?P<property_alias>[\w\-]+)/$', views.property_detail, name='property_detail'),
url(r'^tenants/(<?P<first>\w+)/(<?P<last>)\w+/$', views.tenant_detail, name = 'tenant_detail'),)
index.html
<h1> List of Tenants</h1>
{% for tenant in tenants %}
<ul> {{ tenant}} </ul>
<h2> details </h2>
{% endfor %}
segment of views.py
def tenant_detail(request, first, last):
tenant = Tenant.objects.filter(first_name__startswith = first,
last_name__startswith = last)
tenant = get_object_or_404(Tenant, pk=tenant[0].pk)
return render(request, 'my_properties/tenants/tenant_detail.html', {'tenant': tenant})
the error itself is:
NoReverseMatch at /properties/tenants/
Reverse for 'tenant_detail' with arguments '()' and keyword arguments '{u'last': u'no', u'first': u'yay'}' not found. 1 pattern(s) tried: ['properties/tenants/(<?P<first>\\[0-9A-Za-z._%+-]+)/(<?P<last>)\\[0-9A-Za-z._%+-]+/$']
Request Method: GET
Request URL: http://127.0.0.1:8000/properties/tenants/
Django Version: 1.6
Exception Type: NoReverseMatch
Exception Value:
Reverse for 'tenant_detail' with arguments '()' and keyword arguments '{u'last': u'no', u'first': u'yay'}' not found. 1 pattern(s) tried: ['properties/tenants/(<?P<first>\\[0-9A-Za-z._%+-]+)/(<?P<last>)\\[0-9A-Za-z._%+-]+/$']
Does anyone know what's wrong? Seems like I'm following the correct general procedure
The error is in your regexp.
The \w+ of the 'last' group was outside the bracket, and there is a typo on the named group syntax.
This should work: r'^tenants/(?P<first>\w+)/(?P<last>\w+)/$'

Django password reset form

I'd like users to be be able to reset their passwords via a link on my site. I'm trying to use the built in django password reset form, but having a little difficulty. I have the following included in my urls.py
urlpatterns = patterns('',
url(r'^admin/password_reset/$', 'django.contrib.auth.views.password_reset', name='admin_password_reset'),
url(r'^admin/password_reset/done/$', 'django.contrib.auth.views.password_reset_done'),
url(r'^reset/(?P<uidb36>[0-9A-Za-z]+)-(?P<token>.+)/$', 'django.contrib.auth.views.password_reset_confirm'),
url(r'^reset/done/$', 'django.contrib.auth.views.password_reset_complete'),
url(r'^admin/', include(admin.site.urls)),
I access the link in the following way:
<h3>Forgot your password?</h3>
I've also tried including it like this:
{% url django.contrib.auth.views.password_reset_confirm uid, token %}
{% url django.contrib.auth.views.password_reset_confirm uidb36=uid, token=token %}
I get the following error:
NoReverseMatch at /account/
Reverse for 'password_reset' with arguments '()' and keyword arguments '{}' not found.
I've tried a bunch of different tings without any luck. Do I need to pass in the uid/token? If so, how do I define them?
Thank you for your help
Your url is named admin_password_reset
<h3>Forgot your password?</h3>
This sounds very similar to an issue I had. You might check my solution: Django {% url %} reverse not working if you are using {% load url from future %}.
Good luck!

Django NoReverseMatch exception with cache_page in urls.py

Question
Why does using the cache_page function in urls.py under Django 1.4 cause a NoReverseMatch error when using the url tag in a template?
Setup
views.py
from django.shortcuts import render
def index(request):
'''Display the home page'''
return render(request, 'index.html')
urls.py
Following the cache_page directions:
from django.conf.urls import patterns, include, url
from django.views.decorators.cache import cache_page
from my_project.my_app import views
urlpatterns = patterns('',
url(r'^$', cache_page(60 * 60)(views.index)),
)
index.html
{% url my_project.my_app.views.index %}
Error Message
NoReverseMatch at /
Reverse for 'my_project.my_app.views.index' with arguments '()' and keyword arguments '{}' not found.
The offending line the error message points out is, of course:
{% url my_project.my_app.views.index %}
What I've tried so far
A ton of googling and searching on SO
Simplifying code down to the example above to rule out other conflicts
Used cache_page in views.py as a decorator successfully (not recommended according to docs)
Offerings to our all-powerful Django overlords
When doing reverse, Django tries to match by
URL label
dotted path
callable
In your code, 'my_project.my_app.views.index' is dotted path, then Django would get the actual function index() and use it as the key to match the reversed URL, by looking up in the mapping dictionary django.core.urlresolvers.get_resolver(None).reverse_dict.
However, when you wrap the view.index by cache_view, the key in the mapping dictionay becomes the wrapper. Thus the lookup fails and NoReverseMatch is raised. This is inconvenient and error-prone, but I'm not sure whether it is a bug.
You could then solve this by either use URL label
url(r'^$', cache_page(60 * 60)(views.index), name='my_index'),
{# in template #}
{% url my_index %}
or used cache_page in views.py as a decorator as you mentioned.

Reverse for ''*'' with arguments '()' and keyword arguments '{}' not found

I am trying to use the {% url %} tag to send my user to a new template, called payment.html. I am receiving the error above. Here's what I have:
In some Javascript in my template:
{% url 'payment' %}
In my urls:
urlpatterns = patterns('',
(r'media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}),
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
url(r'^pc-admin/', include(pcAdminSite.urls)),
(r'^$', index),
(r'^signup/', signup),
(r'^info_submit/', info_submit),
(r'^payment/', payment, name="payment"),
In my views:
def payment(request):
return render_to_response('payment.html', {})
Based on similar posts, I've made sure that only 1 URL points to my payment view and have used named URLs. Can anyone help with what I might be doing wrong? Thanks.
There shouldn't be any '' surrounding the view name in the url tag - check the documentation out.
(Unless you're using the Django's 1.5 future {% url %} tag.)
this error also occurs this way :
My account
the message will be this one
Reverse for ''profiles_profile_detail'' with arguments '(u'mynick',)' and keyword arguments '{}' not found.
once the two '' dropped like explain erlier everything works fine ;)

Categories