NoReverseMatch Error when adding slug to url - python

quite new to Django and Python. Hoping to get some help on what went wrong with the below code. Basically, I am trying to create a url with and id and a slugfield e.g. something.com/1/arts-and-crafts.
Stucked and getting a NoReverseMatch error below:
Reverse for 'category' with arguments '(2, u'arts-and-crafts')' and keyword arguments '{}' not found. 2 pattern(s) tried: ['(?P\d+)/[-\w]+/$', '(?P\d+)/$']
Below is the code that I am using, would greatly appreciate any help in understanding what went wrong:
template html
<ul class="list-unstyled">
{% for category in categories %}
{% if forloop.counter < 10 %}
<li><a href="{% url 'category' category.id category.slug %}">
{{ category.cat_name}}</a></li>
{% endif %}
{% endfor %}
</ul>
url.py
url(r'^(?P<cat_id>\d+)/[-\w]+/$', 'guides.views.category', name='category'),
views.py
def category(request, cat_id):
categories = Category.objects.all()
guides = Guide.objects.filter(category__id=cat_id).order_by("created_date").reverse()
is_featured = Guide.objects.filter(category__id=cat_id).filter(featured=True)
selected_category = get_object_or_404(Category, pk=cat_id)
return render(request, 'guides/category.html', {'categories': categories, 'guides': guides, 'is_featured': is_featured, 'selected_category': selected_category})

Your URL doesn't capture the slug as a parameter, so it can't be used in the reverse call. Either change the second pattern to (?P<slug>[-\w]+) or don't use category.id in the {% url %} tag.

Related

Reverse for 'equipment_categories' with arguments '('',)' not found. 1 pattern(s) tried: ['equipments/equipment_categories/$']

I am trying to make a website that sorts equipment based on their category and i am getting the reverse match error when i link the urls on the webpage. Please i need advice on how i can properly pull this off. Thanks in advance.
urls.py
from django.urls import path
from . import views
app_name = 'equipments_catalogue'
urlpatterns = [
path('equipment_list/', views.EquipmentListView.as_view(), name='equipment_list'),
path('equipment_categories/', views.EquipmentCategoryView.as_view(),
name='equipment_categories'),
path('equipment_by_category/<str:cats>/', views.EquipmentListByCategory,
name='equipment_by_category')
]
views.py
from django.shortcuts import render
from django.views.generic import ListView
from . import models
# Create your views here.
class EquipmentCategoryView(ListView):
model = models.Category
template_name = 'equipment_categories.html'
def EquipmentListByCategory(request, cats):
equipment_category = models.Equipment.objects.filter(category=cats)
return render(request, 'equipment_by_category.html', {'cats': cats , 'equipment_category':
equipment_category})
class EquipmentListView(ListView):
model = models.Equipment
template_name = 'equipment_list.html'
template
{% extends 'base.html' %}
{% load static %}
{% block title %}Home{% endblock %}
{% block content %}
<h1>Welcome to JPI Equipment Categories Page</h1>
{% for category in object_list %}
<a href="{% url 'equipments_catalogue:equipment_categories' equipment_by_category.category
%}">{{ category.name }}</a><br><br>
{% endfor %}
{% endblock %}
You're calling it wrong. The correct way to call it is {% url '<app_name>:<url_name>' %}
Your app name is equipments_catalogue, your url name is equipment_by_category, not equipment_categories, which is correct, and the argument you should be passing should be a string, something like category.name:
{% url 'equipments_catalogue:equipment_by_category' category.name %}

How can I pass multiple arguements from Django Template to View via URL?

I am trying a simple thing User clicks a question displayed. The link when clicked would take in the question id and pass it as an argument to display the relevant Choices. The user is asked to chose a Choice and then the next page would display how many people has voted for that Choice(including the user's current decision).
The Error I am getting is when I start the app using 127.0.0.1:8000/polls/ it displays the question. Then when I click the question the url becomes 127.0.0.1:8000/polls/3/ which is correct as 3 is the question id. So it is expected to show the Choices for the Question ID. But it is not showing.
The Error is:
NoReverseMatch at /polls/3/
Reverse for 'results' with arguments '()' and keyword arguments '{'q_id': 3, 'c_test': 'May Be'}' not found. 1 pattern(s) tried: ['polls/(?P<q_id>[0-9]+)/(?P<c_test>\\w+)/results/$']
Request Method: GET
Request URL: http://127.0.0.1:8000/polls/3/
Django Version: 1.10.3
Exception Type: NoReverseMatch
Exception Value:
Reverse for 'results' with arguments '()' and keyword arguments '{'q_id': 3, 'c_test': 'May Be'}' not found. 1 pattern(s) tried: ['polls/(?P<q_id>[0-9]+)/(?P<c_test>\\w+)/results/$']
Exception Location: /home/usr/.local/lib/python3.5/site-packages/django/urls/resolvers.py in _reverse_with_prefix, line 392
Python Executable: /usr/bin/python3.5
Python Version: 3.5.2
My code is:
views.py
class IndexView(generic.ListView):
template_name = "polls/index.html"
context_object_name = "latest_question_list"
model = Question
def get_queryset(self):
return Question.objects.filter(
pub_date__lte=timezone.now()
).order_by('-pub_date')[:5]
class DetailView(ListView):
model = Choice
context_object_name = "latest_choice_list"
template_name = "polls/detail.html"
def get_queryset(self):
print(self.args[0])
'''Return list of choices'''
return Choice.objects.filter(question_id=self.args[0])
# return Choice.objects.all()
def pollvote(request, q_id, c_test):
if c_test:
p = Choice.objects.filter(question_id=q_id).get(choice_test=c_test)
count = p.votes
count += 1
p.votes = count
p.save()
return HttpResponseRedirect('/polls/%s/%s/results/' % c_test, q_id)
detail.html (error says problem at the href line)
{% load staticfiles %}
<link rel="stylesheet" type="text/css" href="{% static 'polls/style.css' %}" />
{% if latest_choice_list %}
<p>Cast your Choice</p>
<ul>
{% for choice in latest_choice_list %}
<li>{{ choice.choice_test }}</li>
{% endfor %}
</ul>
{% else %}
<p>No choice are available.</p>
{% endif %}
results.html:
{% load staticfiles %}
<link rel="stylesheet" type="text/css" href="{% static 'polls/style.css' %}" />
{% if latest_choice_list %}
<p>Choices Made So Far</p>
<ul>
{% for choice in latest_choice_list %}
<li>{{ choice.choice_test }} - {{ choice.votes }} </li>
{% endfor %}
</ul>
{% else %}
<p>No choice are available.</p>
{% endif %}
urls.py
urlpatterns = [
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^([0-9]+)/$', views.DetailView.as_view(), name='detail'),
url(r'^(?P<q_id>[0-9]+)/(?P<c_test>\w+)/results/$', views.pollvote, name='results'),]
Why is the detail.html is throwing error? Why is it not taking the two keyword named arguement and passing it to the result?
Try this:
{{ choice.choice_test }}
Django will automatically assign the args in given order.
P.S.
I am assuming that Choice model has question_id and choice_test field.
If you have question_id as an integer field as a reference to any Question object then instead of doing this, you can use Foreign key field of django.medels . https://docs.djangoproject.com/en/1.10/topics/db/examples/many_to_one/

NoReverseMatch at / Python Django

I'm taking a Django course, and I'm having the next error:
Reverse for 'products.views.product_detail' with arguments '(1,)' and keyword arguments '{}' not found. 0 pattern(s) tried: []
I'm trying to send an argument to a view from a file that is called index.html
My index.html looks like this:
{% for pr in product %}
<li>
{{ pr.name }}
| {{ pr.description }}
<img src="{{ pr.imagen.url }}" alt="">
</li>
{% endfor%}
I already declared the url that is associated:
urlpatterns = [
url(r'^product/(?P<pk>[0-9]+)/$', views.product_detail, name='views.product_detail')
]
And my views.py looks like this:
def product_detail(request, pk):
product = get_object_or_404(Product, pk = pk)
template = loader.get_template('product_detail.html')
context = {
'product': product
}
return HttpResponse(template.render(context, request))
Does someone know why is this error happening?
Thanks.
From "Features to be removed in 1.10":
The ability to reverse() URLs using a dotted Python path is removed.
The {% url %} tag uses reverse(), so the same applies. As elethan mentioned in the comments, you need to use the name parameter provided in your URLconf instead, in this case views.product_detail:
{% for pr in product %}
<li>
{{ pr.name }}
| {{ pr.description }}
<img src="{{ pr.imagen.url }}" alt="">
</li>
{% endfor %}

Django 1.7 Dashes in URL

I feel like I'm tripping. I am trying to add a url with-dashes. I'm not sure what I'm doing wrong using non-classbased views. I don't think I can render a definition like blog_post.as_view() since it doesn't have it.
Does anyone see an obvious error?
Error Message:
Reverse for 'blog_post' with arguments '(u'i-prefer-debian',)'
and keyword arguments '{}' not found. 1 pattern(s) tried:
['blog/$post/(?P<slug>[\\w-]+)/$']
urls.py
url(r'^post/(?P<slug>[\w-]+)/$', 'blog_post', name="blog_post"),
views.py
def blog_post(request, slug):
print 1 # To see if it gets hit
context = {
'post': get_object_or_404(Posts, slug=slug)
}
return render(request, 'blog_post.html', context)
blog_list.html
{% for post in posts %}
<div>
{{ post.title }}
{{ post.created_at }}
</div>
{% endfor %}
The problems comes from the urls.py file where you include the urls.py you are showing.
It looks like you did:
url(r'^blog/$', include('blog.urls'))
You need to drop the $ (ref).

Django NoReverseMatch error with valid url config and views

I'm getting a NoReverseMatch error in my template rendering.
Here's the relevant template:
<ul id='comments'>
{% for comment in comments %}
<li class='comment'>
<img class='gravatar' src='{{ comment.User|gravatar:50}}' alt='{{ comment.User.get_full_name }}' \>
<a href='{% url 'dashboard.views.users.profile' comment.User.id %}' class='user'>
{{comment.User.get_full_name}}
</a>
<p class='comment-timestamp'>{{comment.created}}</p>
<p class='comment-content'>{{comment.comment|striptags}}<br>
{% if user == comment.user or user = report.user %}
Delete</p>
{% endif %}
</li>
{% endfor %}
The error is given on the url 'mokr.delete_comment' line
Here's the view:
def delete_comment(request, comment_id):
comment = get_object_or_404(ReportComment, id = comment_id)
report = comment.MgmtReport
comment.delete()
project = report.project
return HttpResponseRedirect(reverse('show_post', args=(project.url_path, report.id)))
and the section of urls.py
(r'^mokr/comment/(\d+)/delete/$', mokr.delete_comment),
url(r'^mokr/show/([^\.]*)/(\d+)/$', mokr.show, name='show_post'),
You're passing two arguments to the template in your call to reverse in the delete_comment view; args=(project.url_path, report.id) but your urls.py lists;
(r'^mokr/comment/(\d+)/delete/$', mokr.delete_comment),
Which can only accept one parameter.
Alter your urls.py to add a name argument to your delete comment url.
(r'^mokr/comment/(\d+)/delete/$', mokr.delete_comment, name="delete_comment"),
Then try using this in your template;
{% url 'delete_comment' comment.id %}
See naming URL patterns and reverse resolution of URLs

Categories

Resources