I am trying to use get_absolute_url to follow DRY rules. If I code the class to build the href directly from the slug it all works fine. Ugly, messy but working...
So I am trying to get this done right using get_absolute_url() and I am getting stuck with a NoReverseMatch exception using the code below. I know this must be some kind of newbie error, but I have been up and down all the docs and forums for days, and still can't figure this one out!
I get this error:
NoReverseMatch at /calendar
Reverse for 'pEventsCalendarDetail' with arguments '()' and keyword arguments '{u'slug': u'Test-12014-05-05'}' not found. 0 pattern(s) tried: []
Request Method: GET
Request URL: http://127.0.0.1:8000/calendar
Django Version: 1.6
Exception Type: NoReverseMatch
Exception Value:
Reverse for 'pEventsCalendarDetail' with arguments '()' and keyword arguments '{u'slug': u'Test-12014-05-05'}' not found. 0 pattern(s) tried: []
Exception Location: /usr/local/lib/python2.7/site-packages/django/core/urlresolvers.py in _reverse_with_prefix, line 429
Python Executable: /usr/local/opt/python/bin/python2.7
Python Version: 2.7.6
using the following models.py excerpt:
#python_2_unicode_compatible
class Event(models.Model):
eventName = models.CharField(max_length=40)
eventDescription = models.TextField()
eventDate = models.DateField()
eventTime = models.TimeField()
eventLocation = models.CharField(max_length=60, null=True, blank=True)
creationDate = models.DateField(auto_now_add=True)
eventURL = models.URLField(null=True, blank=True)
slug = AutoSlugField(populate_from=lambda instance: instance.eventName + str(instance.eventDate),
unique_with=['eventDate'],
slugify=lambda value: value.replace(' ','-'))
#models.permalink
def get_absolute_url(self):
from django.core.urlresolvers import reverse
path = reverse('pEventsCalendarDetail', (), kwargs={'slug':self.slug})
return "http://%s" % (path)
The complete urls.py file:
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
url(r'^$', 'electricphoenixfll.views.home', name='home'),
url(r'^home$', 'electricphoenixfll.views.home', name='home'),
url(r'^calendar$', 'electricphoenixfll.views.calendar', name='calendar'),
url(r'^forum$', 'electricphoenixfll.views.forum', name='forum'),
url(r'^donate$', 'electricphoenixfll.views.donate', name='donate'),
url(r'^donate_thanks$', 'electricphoenixfll.views.donate_thanks', name='donate_thanks'),
url(r'^what_is_fll$', 'electricphoenixfll.views.what_is_fll', name='what_is_fll'),
url(r'^core_values$', 'electricphoenixfll.views.core_values', name='core_values'),
url(r'^follow_the_phoenix$', 'electricphoenixfll.views.follow_the_phoenix', name='follow_the_phoenix'),
url(r'^followEnter/$', 'electricphoenixfll.views.followEnter', name='followEnter'),
url(r'^followList/$', 'electricphoenixfll.views.followList', name='followList'),
url(r'^about_us$', 'electricphoenixfll.views.about_us', name='about_us'),
url(r'^calendarDetail/(?P<slug>[\w-]+)/$', 'phoenixEvents.views.calendarDetail', name='pEventsCalendarDetail'),
url(r'^admin/', include(admin.site.urls)),
)
The second positional argument to reverse() is urlconf argument:
reverse(viewname[, urlconf=None, args=None, kwargs=None, current_app=None])
To make it work use keyword argument for setting args:
path = reverse('pEventsCalendarDetail', args=(), kwargs={'slug':self.slug})
Or, don't set args at all:
path = reverse('pEventsCalendarDetail', kwargs={'slug':self.slug})
Don't use both the permalink decorator and the reverse() call. They both do the same thing. Drop the decorator: it is deprecated.
Related
I'm trying to create an app that stores problems (specifically math problems), and displays them to the user. I haven't add much of the functionality that I want to yet, and as I'm fairly new to Django, I have been following along with the Django Tutorial project, and changing it according to my needs. However, I'm encountering a NoReverseMatch error even though I seem to be passing in the correct parameters. My code is below.
models.py
import imp
from django.db import models
from django.urls import reverse
import uuid
# Create your models here.
class Source(models.Model):
'''Model that represents the source of a problem (e.g. AMC, AIME, etc.)'''
problem_source = models.CharField(max_length=20)
problem_number = models.PositiveSmallIntegerField()
def __str__(self):
'''toString() method'''
return f'{self.problem_source} #{self.problem_number}'
class Topic(models.Model):
'''Model that represents the topic of a problem (e.g. Intermediate Combo)'''
problem_topic = models.CharField(max_length=50)
problem_level = models.CharField(max_length=15)
def __str__(self):
return f'{self.problem_level} {self.problem_topic}'
class Problem(models.Model):
'''Model that represents each problem (e.g. AIME #1, AMC #11, etc.)'''
id = models.UUIDField(primary_key=True, default=uuid.uuid4)
source = models.OneToOneField(Source, on_delete=models.RESTRICT, null=True, unique=True)
problem_text = models.TextField()
topic = models.ManyToManyField(Topic)
def __str__(self):
"""String for representing the Model object."""
return f'{self.source}'
def get_absolute_url(self):
"""Returns the url to access a detail record for this book."""
return reverse('problem-detail', args=[str(self.id)])
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('problems/', views.ProblemListView.as_view(), name='problems'),
path('problem/<int:pk>', views.ProblemListView.as_view(), name='problem-detail'),
]
views.py
import imp
from django.shortcuts import render
# Create your views here.
from .models import Problem, Source, Topic
def index(request):
'''View function for home page of site'''
# generate counts of the main objects
num_problems = Problem.objects.all().count()
context = {
'num_problems': num_problems,
}
return render(request, 'index.html', context=context)
from django.views import generic
class ProblemListView(generic.ListView):
model = Problem
class ProblemDetailView(generic.DetailView):
model = Problem
Links to my HTML files are below:
base_generic.html: link
problem_list.html: link
problem_detail.html: link
My workspace is structured as follows:
trivial
catalog
migrations
static/css
styles.css
templates
catalog
problem_detail.html
problem_list.html
base_generic.html
index.html
__init.py
admin.py
apps.py
models.py
tests.py
urls.py
views.py
trivial
__init__.py
asgi.py
settings.py
urls.py
wsgi.py
db.sqlite3
manage.py
I have read other StackOverflow posts, but none seem to apply to my situation. Also, in problem_list.html, if the value in the href link is Problem.get_absolute_url, the site will load, but clicking the link for "all problems" will lead back to the same page. But, if I put prob.get_absolute_url in the href link, I get a NoReverseMatch error.
Here is the exact error that I am getting:
NoReverseMatch at /catalog/problems/
Reverse for 'problem-detail' with arguments '('41b936f7-3c08-4fb9-a090-2d466348d34d',)' not found. 1 pattern(s) tried: ['catalog/problem/(?P<pk>[0-9]+)\\Z']
Request Method: GET
Request URL: http://127.0.0.1:8000/catalog/problems/
Django Version: 4.0.2
Exception Type: NoReverseMatch
Exception Value:
Reverse for 'problem-detail' with arguments '('41b936f7-3c08-4fb9-a090-2d466348d34d',)' not found. 1 pattern(s) tried: ['catalog/problem/(?P<pk>[0-9]+)\\Z']
Django is telling me that the error stems from calling prob.get_absolute_url in problem_list.html
The problem is that your id on the Problem model is a UUID, but your URL pattern is expecting an integer value as the pk - because you have prefixed the named pattern with int::
path('problem/<int:pk>', views.ProblemListView.as_view(), name='problem-detail'),
It should work if you change it to:
path('problem/<uuid:pk>', views.ProblemListView.as_view(), name='problem-detail'),
I would like to pass kwargs to my view function through URL.
urls.py
urlpatterns = [
# ------------- set relations --------------------
url(r'^approve-form/$', views.approve_form,
{'content_type':None, 'form_id':None,}, name='approve-form'),]
views.py
def approve_form(request, content_type=None, form_id=None):
return HttpResponse('Working')
Now I am using reverse_lazy function to call the url from on of the model instance
models.py
class FormStatus(models.Model):
content_type = models.ForeignKey(ContentType)
form_id = models.IntegerField(verbose_name='Form Ref ID')
def __str__(self):
return "{}".format(self.content_type)
def get_approve_link(self):
return reverse_lazy("flow-control:approve-form", kwargs={'form_id':self.form_id,
'content_type':self.content_type})'
ERROR
Reverse for 'approve-form' with arguments '()' and keyword arguments '{'content_type': <ContentType: admin sanc model>, 'form_id': 12}' not found. 1 pattern(s) tried: ['flow-control/approve-form/$']
Is something wrong with the approach or is there any better approach for this ?
Thanks in advance.
PS: I tried the url documentation but couldn't figure it out.
Change your url to and check if its worked or not-
urlpatterns = [
# ------------- set relations --------------------
url(r'^approve-form/(?P<content_type>\w+)/(?P<form_id>\d+)/$', views.approve_form, name='approve-form'),]
views
def approve_form(request, content_type=None, form_id=None):
return HttpResponse('Working')
This seems to be a "classic" problem :
NoReverseMatch at /tr/showroom/
Reverse for 'project-list' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []
But the problem is, when I check the different topic on the internet and then my files, I don't get it.
So it's working perfectly on the native language. It happens when I try to change the language on this showroom page only.
Every page that have been copy with the commad cms copy works fine except this one.
Well, here is the model :
def get_slug(self):
return self.safe_translation_getter(
'slug',
language_code=get_language(),
any_language=False)
def get_absolute_url(self, current_app=None):
"""
Warning: Due to the use of django application instance namespace
(for handle multi instance of an application)we add the possibility
to use it with the reverse.
So if get_absolute_url is call without app instance it may failed (
for example in django_admin)
"""
lang = get_language()
if self.has_translation(lang):
kwargs = {'slug': self.get_slug()}
return reverse('djangocms_showroom:project-detail',
kwargs=kwargs,
current_app=current_app)
return reverse('djangocms_showroom:project-list', current_app=current_app)
def get_full_url(self, site_id=None):
return self._make_full_url(self.get_absolute_url(), site_id)
def _make_full_url(self, url, site_id=None):
if site_id is None:
site = Site.objects.get_current()
else:
site = Site.objects.get(pk=site_id)
return get_full_url(url, site)
The url :
from django.conf.urls import patterns, url
from .views import (ProjectListView, ProjectDetailView)
urlpatterns = patterns(
'',
url(r'^$', ProjectListView.as_view(), name='project-list'),
url(r'^project/(?P<slug>\w[-\w]*)/$', ProjectDetailView.as_view(), name='project-detail'),
)
And the html error :
Error during template rendering
In template /var/www/webapps/blippar_website/app/blippar/templates/djangocms_showroom/project_list.html, error at line 14
Which is :
<form id="projects-filter" action="{% url 'djangocms_showroom:project-list' %}">
Well, I am not very good yet with django and django-cms, if someone has any clue, it would be marvellous !
I have an affiliate program app with redirects and link statistics tracking. A read-only field in the Django Admin should display the full URL of the affiliate link, (so the user can copy+paste this into their editor) but the reverse() call in the model instance's get_absolute_url() method is failing when called from a callable in the admin class. For example:
from project urls.py
urlpatterns = patterns(
'',
url(r'^a/', include('shop.affiliates.urls', namespace='affiliates')),
...
from shop.affiliates.urls.py
urlpatterns = patterns(
'',
url(r'^(?P<slug>[\w]+)/$', redirect_to_affiliate_link, name='affiliate_redirect'),
)
from shop.affiliates.models.py
class AffiliateLink(models.Model):
...
slug = models.SlugField(
max_length=4,
help_text='The slug for this link, used to generate url.',
)
...
def get_absolute_url(self):
return reverse(
'affiliates:affiliate_redirect',
kwargs={'slug': self.slug},
)
Note: for the sake of debugging simplicity, it's safe to assume that the slug field has already been populated in the database previously. So I'm not trying to create a new object where slug has not yet been set.
from shop.affiliates.admin.py
class AffiliateLinkInline(admin.StackedInline):
model = AffiliateLink
extra = 0
fields = (
..., 'hyperlink', ...
)
readonly_fields = (
'hyperlink', ...
)
def hyperlink(self, obj):
url = 'http://example.com{}'.format(obj.get_absolute_url())
return '{0}'.format(url)
hyperlink.allow_tags = True
When loading the appropriate admin page, I get a NoReverseMatch exception.
Exception value:
Reverse for 'affiliate_redirect' with arguments '()' and keyword arguments '{u'slug': u''}' not found. 1 pattern(s) tried: [u'a/(?P<slug>[\\w]+)/$']
so the proper regex is found, but the slug parameter is empty. I verified that obj.slug within the admin callable exists, and it is the correct AffiliateLink slug. To make matters more strange, if I switch the kwargs in get_absolute_url() like so:
def get_absolute_url(self):
return reverse(
'affiliates:affiliate_redirect',
kwargs={'bug': self.slug},
)
Then the exception value changes to:
Reverse for 'affiliate_redirect' with arguments '()' and keyword arguments '{u'bug': u'7aeB'}' not found. 1 pattern(s) tried: [u'a/(?P<slug>[\\w]+)/$']
So the kwarg value for key 'slug' disappears from the exception value, but the value for 'bug' stays.
What am I doing wrong here? Any help is greatly appreciated.
URL patterns are sometime evaluated before URLconf has been loaded. Try reverse_lazy instead of reverse
https://docs.djangoproject.com/en/dev/ref/urlresolvers/#reverse-lazy
I'm having problem using {% url %} tag in django template.
LINK
Throwing this error:
Caught NoReverseMatch while rendering: Reverse for 'baza.views.thread' with arguments '('',)' and keyword arguments '{}' not found.
What's weird, it works used like this:
{{ category.last_post.thread.pk }}
returns correct value which is '8', also doesn't throw error when I'm using it like this:
LINK
Above code works fine, and redirects to thread.
my urls.py :
...
(r"^temat/(\d+)/$", "thread"),
...
post model:
class Post(models.Model):
title = models.CharField(max_length=60)
created = models.DateTimeField(auto_now_add=True)
creator = models.ForeignKey(User, blank=True, null=True)
thread = models.ForeignKey(Thread)
body = models.CharField(max_length=10000)
thread view:
def thread(request, pk):
posts = Post.objects.filter(thread=pk).order_by("created")
posts = mk_paginator(request, posts, 20) # ZMIEN TAKZE W get_thread_page
t = Thread.objects.get(pk=pk)
return render_to_response("baza/thread.html", add_csrf(request, posts=posts, pk=pk, title=t.title,
element_pk=t.element.pk, media_url=MEDIA_URL, path = request.path))
category model has "last_post" metod which returns last msg posted in this category.
Could someone help me with this annoying problem?
Regards.
Ps. I'm using Django Version: 1.3.1
The problem is that the value of the next expression category.last_post.thread.pk is None or ''. And no Reverse for 'baza.views.thread' with arguments '('',)'.
Arguments ('',) implies that category.last_post.thread.pk is None or ''