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
Related
I'm trying to highlight specific buttons in the navigation bar when I'm on a specific page and hyperlink to it when i'm not. The url for this page is a dynamic url however and using the {% url ... as var %} syntax is not making the specific buttons highlighted when they should be.
The issue here is that the button does not even show up at all. I narrowed it down to the request.path not matching with the dynamic url path. Normal urls (without the /str:something) seem to match perfectly.
in navbar.html i've tried to define the comparison_url (before all other code) as follows, but nothing seems to work so far:
{% url 'comparison' as comp_url %}
{% url 'comparison' sub_name as comp_url %}
{% url 'comparison' suburb_name as comp_url %}
{% url 'comparison' sub_name=suburb_name as comp_url %}
{% url 'comparison' vergelijking.suburb as comp_url %}
urls are defined as follows in urls.py:
urlpatterns = [
path("vergelijking/<str:sub_name>", views.ComparisonView.as_view(), name="comparison"),
path("signalen/<str:sub_name>", views.RadarView.as_view(), name="signals"),
path("oorzaken/<str:sub_name>", views.CausationsView.as_view(), name="causation"),
]
in navbar.html, where the actual problem lies:
{% url 'comparison' sub_name as comp_url %}
{% url 'signals' sub_name as sig_url %}
{% url 'causation' sub_name as comp_url %}
{% if request.path == comp_url %}
<li class="nav-item mx-0 mx-lg-1"><a class="nav-link py-3 px-0 px-lg-3 rounded active">Vergelijking</a></li>
{% elif request.path == sig_url or request.path == caus_url %}
<li class="nav-item mx-0 mx-lg-1"><a class="nav-link py-3 px-0 px-lg-3 rounded" href="{% url 'comparison' sub_name=suburb_name%}">Vergelijking</a></li>
{% endif %}
my base.html includes the navbar.html and the comparison.html extends base.html. There is no view for the navbar.html or base.html. My comparisonview looks like this (municipality details are loaded into the context):
class ComparisonView(LoginRequiredMixin, TemplateView):
"""map of municipality and suburbs with tooltip info"""
template_name = 'comparison.html'
def get_context_data(self, **kwargs):
context = super(ComparisonView, self).get_context_data(**kwargs)
context['suburb_name'] = self.kwargs['sub_name']
municipality_name = Suburb.objects.get(name=self.kwargs['sub_name']).municipality.name
context['municipality_name'] = municipality_name
suburb_list = Suburb.objects.filter(municipality__name=municipality_name)
suburbs_signals_dict = {}
for s in suburb_list:
suburbs_signals_dict[s.name] = s.get_signals()
context['suburb_signals'] = dumps(suburbs_signals_dict)
return context
I think the mistake is in the way i define my comp_url but i'm not exactly sure. Does anyone know what I'm doing wrong?
the view was missing a request as a parameter (whenever i was calling on request.path, it was equating the to be matched link with null as request.path did not exist). I solved this by adding the path to the context:
context['path'] = quote(self.request.path)
The quote was in my case necessary since self.request.path can have spaces in a url whereas comp_url has '%20' for spaces. After I could call on path like so:
{% if path == comp_url %}
And the problem was solved
my url.py
app_name="application_name"
urlpatterns=[
url(r"^staff/",include('application_name.staff_url', namespace='staff')),
url(r"^customer/",include('application_name.customer_url', namespace='customer')),
]
staff_url.py
from application_name import views
app_name="staff"
urlpatterns=[
url(r"^customers/",views.customers, name='customers'),
url(r"^orders/$", views.orders, name='orders'),
url(r"^payments/$", views.payments, name='payments'),
]
customer_url.py
from application_name import views
app_name="customer"
urlpatterns=[
url(r"^items/",views.items, name='items'),
url(r"^checkout/$", views.checkout, name='checkout'),
url(r"^make_payment/$", views.make_payment, name='make_payment'),
]
staf url would be staff/orders or staff/payments customer urls would be customer/items or customer/checkout etc
In my view file I have put every link inside a list which would be iterated inside the template and placed it inside a session
This is my view.py
staffLink=[
{'linkfield':"customers", 'name':"Customers",'slug':"staff"},
{'linkfield':"orders", 'name':"Orders",'slug':"staff"},
{'linkfield':"payments", 'name':"payments",'slug':"staff"}]
links=staffLink
request.session['links']= links
request.session['sub']= 'staff'
context_dict = {'links':links}
This is my html template
{% for link in request.session.links %}
{% if request.session.sub =="staff" %}
<a href="{% url 'application_name:staff' link.linkfield as the_url %}" class="nav-link">
{% elif request.session.sub =="customer" %}
<a href="{% url 'application_name:customer' link.linkfield as the_url %}" class="nav-link">
{% endif %}
{% endfor %}
Pl
This are the following result
When I include the if statement i.e. {% if request.session.sub =="staff" %}. The following error is produced
django.template.exceptions.TemplateSyntaxError: Could not parse the remainder: '=="staff"' from '=="staff"'
When I exclude the if statement so making it just <a href="{% url 'application_name:staff' link.linkfield as the_url %}" class="nav-link">
I did this for testing purposes. I get the following error
django.urls.exceptions.NoReverseMatch: Reverse for 'staff' not found. 'staff' is not a valid view function or pattern name.
Please what am I to do to get the if statement working alongside the anchor statement
You should write a space between the == and the "staff" string, so:
{% if request.session.sub == "staff" %}
…
{% endif %}
as for the URL, you not refer to a URL which is an include(…) since that is a collection of URLs. For example:
<a href="{% url 'staff:customers' link.linkfield as the_url %}" class="nav-link">
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 %}
Have this html, that i want to pass 2 arguments to a function when that url is pressed:
htmlpage
{% for n in notifications %}
<li style="..."><b>{{ n.title }}</b> - {{ n.description }}
<a href="{% url 'update-notify-status' n.id n.title %}" >Don't show again</a>
{% endfor %}
urls.py
url(r'^notification_htmlv2/update_status/([0-9]{4})/([0-9]{4})$', 'Notifications.views.updateStatus',
name="update-notify-status"),
views.py
def updateStatus(request,noteId,noteTile):
q=History.objects.filter(notification_id=noteId,title=noteTile).order_by('-id')[0]
When i start the program it gives an error of "NoReverseMatch".
Im following this example:https://docs.djangoproject.com/en/1.8/topics/http/urls/
reverse resolution of url's chapter
I bet neither n.id nor n.title matches ([0-9]{4}).
You should update your url pattern to handle any possible id and title values.
Something like:
r'^notification_htmlv2/update_status/([0-9]+)/([a-zA-Z0-9]+)$'
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