NoReverseMatch django - not a valid view function or pattern - python

Currently using Django 1.11. I get an exception of
Reverse for 'book_details' not found. 'book_details' is not a valid view function or pattern name.
Request Method: GET
Request URL: http://localhost:8000/library/book/c7311ecf-eba7-4e9d-8b1a-8ba4e075245a/
Django Version: 1.11
Exception Type: NoReverseMatch
I want to use the get_absolute_url from my Model in the details page to go to a Update page. When I take out the reference to the .id and use the get_absolute_url. I checked to see the name "book_details" is referenced properly. I can go to the page and have books details render properly. In the admin console of Django, the "view on site" button also does not render properly it shows this localhost:8000/admin/r/13/c7311ecf-eba7-4e9d-8b1a-8ba4e075245a/ so it does not get the library/books either
current
Update
desired
Update
Where have I mistyped for this to not work?
Setup in files:
Yes, I do have UUID as the primary key.
In views.py
class BookDetailsView(generic.DetailView):
"""
Generic class-based detail view for a Book.
"""
model = Book
in urls.py
url(r'^book/(?P<pk>[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$', views.BookDetailsView.as_view(), name='book_details'),
url(r'^book/(?P<pk>[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/update/$', views.BookUpdate.as_view(), name='book_update'),
in models.py
class Book(models.Model):
def get_absolute_url(self):
"""Returns the URL of the book for details"""
return reverse('book_details', args=[str(self.id)])

Try providing the pk as keyword argument to the reverse function,
def get_absolute_url(self):
return reverse('book_details', kwargs={ 'pk': str(self.id) })
Also, you are missing a trailing slash at the end of the url,
url(r'^book/(?P<pk>[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/$', views.BookDetailsView.as_view(), name='book_details'),

Related

Why is my function get_absolute_url is merging my domain into my website name?

I'm using the Django sitemap framework, and I have to use the function get_absolute_url to render the site URL in the sitemap. However, I'm facing a problem because my link is becoming: exampleio.io instead of example.io.
My function in my model is it:
def get_absolute_url(self):
return reverse('packages', args=[self.name])
My function in the sitemap.py
class ExampleSitemap(Sitemap):
protocol = "https"
changefreq = "weekly"
priority = 0.7
limit = 500
def items(self):
return Example.objects.all()
I'm getting:
<sitemap>
<loc>http://exampleio.io/sitemap-examples.xml</loc>
</sitemap>
Check django /admin, under the Sites section. Make sure your site is correctly named there.

Django redirecting url with changed values

I have urls that take a parameter called board_slug. Before getting the template the view will replace the slug if its name is wrong and redirect it. I have already made the code for fixing the slug but do not know how insert the fixed board_slug into the new url. This code is run across multiple views so it has to work with all the following kinds urls:
url(r'^boards/(?P<board_slug>[^/]+)/$', views.BoardView.as_view(), name='board'),
url(r'^/front-thing/boards/(?P<board_slug>[^/]+)/new/$', views.BoardView.as_view(), name='new_board'),
url(r'^boards/(?P<board_slug>[^/]+)/etc...$', views.BoardView.as_view(), name='anything_with_board'),
class BoardView(View):
template_name = 'forums/board.html'
def get(self, request, board_slug):
if wrong:
url = get_django_url
url.board_slug = 'new-slug'
return redirect(url)
else:
return template

Django NoReverseMatch at /school/new-school/

What is wrong with my approach?
When I post new data, I want it to return back to the page with the input fileds empty. But it gives me this error
NoReverseMatch at /school/new-school/
Reverse for 'new-school' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []
This is my model. Please note, reverse_lazy was imported
class SchoolList(models.Model):
name = models.CharField(max_length=15, null=False)
def __str__(self):
return '%s' % (self.name)
def get_absolute_url(self):
return reverse_lazy('new-school')
This is my url.py
url(r'^school-list/$', SchoolListtView.as_view(), name='school-list'),
url(r'^new-school/$', CreateSchoolListView.as_view(), name='new-school'),
url(r'^school(?P<pk>\d+)/update/$', SchoolListUpdate.as_view(), name='update-school')
This is my view for create.
class CreateSchoolListView(CreateView):
template_name = 'school\create_form.html'
model = SchoolList
fields = ['name']
This is how I specified the urls in the template.
Create New School
View all Schools
When the page is displayed, I can click the links and it will go to the correct pages. But when I post a data, the it throws the above error. I have been on this for hours and read many of the answers online. It seems mine is a unique case.
Try adding namespace to get_absolute_url().
def get_absolute_url(self):
return reverse_lazy('school:new-school')
Make sure you import your app's urls in your project's urls with namespace like:
url(r'^school/', include('school.urls', namespace="school"))
to use namespace in your templates like this:{% url 'school:new-school' %}
Or remove namespace:
url(r'^school/', include('school.urls'))
to use url without namespace in template:{% url 'new-school' %}
Using get_absolute_url would be a bad approach in this case, since it's an instance method, designed to get url for single model instance.
If you want to add method to model, you should use something like this:
#classmethod
def get_create_url(cls):
return reverse_lazy('school:new-school')

Inherit AdminSite but can't get access to get_app_list in parent class (object has no attribute 'get_app_list')

I am customizing my admin page and having some trouble accessing django.contrib.admin.AdminSite methods. I am new to Django so take it easy if I my mistake is dumb
Here I try to extend AdminSite and override indexin my admin.py
class MyAdmin(admin.AdminSite):
#never_cache
def index(self, request, extra_context=None):
"""
Displays the main admin index page, which lists all of the installed
apps that have been registered in this site.
"""
app_list = super(MyAdmin, self).get_app_list(request)
context = dict(
self.each_context(request),
title=self.index_title,
app_list=app_list,
)
context.update(extra_context or {})
request.current_app = super(MyAdmin, self).name
return TemplateResponse(request, super(MyAdmin, self).index_template or
'admin/testing.html', context)
admin_site = MyAdmin(name='myadmin')
I have also tried to keep the
self.get_app_list(request)
but both gave me the same problem
AttributeError at /myadmin/ 'super' object has no attribute
'get_app_list'
or
AttributeError at /myadmin/ 'self' object has no attribute
'get_app_list'
I have already changed my urls.py and settings.py with the proper setup.
Any help is much appreciated
Not sure where you got this idea, but looking at the source code, the get_app_list helper method was introduced in django 1.9.
Here are the links to the source code.
Django 1.8.5
Django 1.9a1
And clearly, it looks like you are using django <= 1.8.5

Django class-based view

Django
Following the official documentation, I am creating a Django app (the same poll app as in the documentation page). While using the class-based view, I got a error. I did not understand much about class based view, for instance, may someone explain, what is the difference between a class based view from a normal view?
Here's my code:
class DetailView(generic.DetailView):
model = Poll
template_name = 'polls/details.html'
def get_queryset(self):
def detail(request, poll_id):
try:
poll = Poll.objects.get(pk=poll_id)
except Poll.DoesNotExist:
raise Http404
return render(request, 'polls/details.html', {'poll': poll})
*********************Error ********************
TypeError at /polls/2/results/
as_view() takes exactly 1 argument (3 given)
Request Method: GET
Request URL: <app-path>/polls/2/results/
Django Version: 1.5.1
Exception Type: TypeError
Exception Value:
as_view() takes exactly 1 argument (3 given)
*****the url***
url(r'^(?P<pk>\d+)/$', views.DetailView.as_view, name='detail')
as_view should be called, not referenced, according to the docs, your url should look like:
url(r'^(?P<pk>\d+)/$', views.DetailView.as_view(), name='detail')
Note the usage of parenthesis.
Also, you should rather call your class PollDetailView to avoid confusion for code readers.
Also, the detail() method you have defined will not be called at all. So you shouldn't define it at all. Also, leave the get_queryset() method alone for the moment, try to get the basic View to work first.
When you use url for the CBV ensure that you can not use the reference of the of the url filed, so first you need to add change the as_view to as_view().
And you can use DetailView like this.,
class PollDetail(DetailView):
model=Book
def get_context_data(self,*args,**kwargs):
context=super(PollDetail,self).get_context_data(*args,**kwargs)
print(context) #It will give you the data in your terminal
return context
And for accessing data you need to use {{object}},
and if you want to access other fields at that time use like this {{object.fieldname}}
In CBV the template name is automatically named as per class name so you don't need to give it.
Note:Don't give class name same as DetailView,In future you will confuse.
Since you are not modifying the view functionality, to use this generic view, you can simply do this:
in your urls.py (along with other stuff):
from django.views.generic.detail import DetailView
from poll.models import Poll
url(r'^(?P<pk>\d+)/$',
DetailView.as_view(model=Poll,
template_name='polls/details.html'), name='detail')
Then in poll/details.html, you just need:
{{ object }}

Categories