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 %}
Related
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/
I have a url defined in urls.py of an application
urlpatterns = [
url(r'^group/create', create_group, name='create_group'),
url(r'^account/create', create_account, name='create_account'),
]
context contains
{'buttons': {'create_account': {'btn_text': 'Create Account',
'secondary': 'Add a new accounting ledger',
'url': 'create_account'}}
How should I use url in the template.
{% for button in buttons %}
<li class="collection-item">
<div>
{% with btn_url=button.url %}
<a class="btn" href="{% url btn_url %}">{{ button.btn_text }}</a>
{% endwith %}
<span class="black-text">{{ button.secondary }}</span>
</div>
</li>
{% endfor %}
The above code in the template throws
Reverse for '' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []
How should I pass the url name as a variable into the url template tag?
Or if should I some how generate the whole url in my view itself, how should the url be generated?
I personally don't think it's possible. I suggest you using reverse in your views.py to interpret the url first, then pass the interpreted result into template:
from django.core.urlresolvers import reverse
url = reverse('create_account')
# add url to your context
According to django docs, reverse would have the same result as you use url template tag in the template.
In your context, buttons is a dictionary, so looping through {% for button in buttons %} will only loop through the keys of the dictionary, i.e. ['btn_text',]
You might want to loop through the items or values instead:
{% for key, value in buttons.items %}
<a class="btn" href="{% url value.btn_url %}">{{ value.btn_text }}</a>
{% endfor %}
or, if you don't need the keys, you can loop through the values
{% for value in button.values %}
<a class="btn" href="{% url value.btn_url %}">{{ value.btn_text }}</a>
{% endfor %}
Note that dictionaries are not ordered. If you are worried about the order of the items in the dictionary, then use a different data structure like a list or ordered dict.
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.
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
I want to simply render a built-in comment form in a template, using Django's builtin commenting module, but this returns a TemplateSyntaxError Exception.
I need help debugging this error, please, because after googling and using the Django API reference, I'm still not getting any farther.
Info:
This is the template '_post.html'[shortened]:
<div id="post_{{ object.id }}">
<h2>
{{ object.title }}
<small>{{ object.pub_date|timesince }} ago</small>
</h2>
{{ object.body }}
{% load comments %}
{% get_comment_count for object as comment_count %}
<p>{{ comment_count }}</p>
<!-- Returns 0, because no comments available -->
{% render_comment_form for object %}
<!-- Returns TemplateSyntaxError -->
This is the Exception output, when rendering:
Caught an exception while rendering: Reverse for 'django.contrib.comments.views.comments.post_comment'
with arguments '()' and keyword arguments '{}' not found.1
{% load comments i18n %}
<form action="{% comment_form_target %}" method="post">
{% if next %}<input type="hidden" name="next" value="{{ next }}" />{% endif %}
{% for field in form %}
{% if field.is_hidden %}
{{ field }}
{% else %}
{% if field.errors %}{{ field.errors }}{% endif %}
<p
{% if field.errors %} class="error"{% endif %}
{% ifequal field.name "honeypot" %} style="display:none;"{% endifequal %}>
{{ field.label_tag }} {{ field }}
/posts/urls.py[shortened]:
queryset = {'queryset': Post.objects.all(),
'extra_context' : {"tags" : get_tags}
}
urlpatterns = patterns('django.views.generic.list_detail',
url('^$', 'object_list', queryset,
name='posts'),
url('^blog/(?P<object_id>\d+)/$', 'object_detail', queryset,
name='post'),
)
/urls.py[shortened]:
urlpatterns = patterns('',
(r'', include('posts.urls')),
(r'^comments/$', include('django.contrib.comments.urls')),
)
I had the same exact problem, render_comment_form template tag was triggering it.
The issue is certainly with your URL config, you had it set the same way i did:
(r'^comments/$', include('django.contrib.comments.urls'))
The correct way is to remove the '$' after 'comments/':
(r'^comments/', include('django.contrib.comments.urls'))
Otherwise django can't properly include all necessary urls under the path comments/...
Hope this helps.
The error message is indicated that it can't find a reverse url for:
django.contrib.comments.views.comments.post_comment
So basically something isn't configured right in your urls. Without being able to see more of how things are setup it's difficult to know exactly what.
Maybe try re-ordering the urls pattern includes in your urls.py, to force the django comments urls to the top?
I had this same problem today. I was referencing a view in urls.py that I hadn't created yet.
From http://docs.djangoproject.com/en/dev/topics/http/urls/#reverse
As part of working out which URL names
map to which patterns, the reverse()
function has to import all of your
URLconf files and examine the name of
each view. This involves importing
each view function. If there are any
errors whilst importing any of your
view functions, it will cause
reverse() to raise an error, even if
that view function is not the one you
are trying to reverse.
Make sure that any views you reference
in your URLconf files exist and can be
imported correctly. Do not include
lines that reference views you haven't
written yet, because those views will
not be importable.
This error is saying that it found the view django.contrib.comments.views.comments.post_comment
but no args () or kwargs{} were passed.
Its not passing a value for object.id into the url.
Take out the url tag and see if the id of the <div id="post_{{object.id}}"> reflects a proper object.id