Milostown22
Milostown22

Reputation: 33

Django - Adding {% url %} in template with slug

I am trying to create the URL in order to access the EDIT and DELETE views directly from the post detail instead of typing it in the browser.

I am having trouble finding the right url pattern and template {% url %} code since there is a slug.

posts.urls

urlpatterns = [
url(r'^$', post_list, name='list'),
url(r'^create/$', post_create),
url(r'^(?P<slug>[\w-]+)/$', post_detail, name='detail'),
url(r'^(?P<slug>[\w-]+)/edit/$', post_update, name='update'),
url(r'^(?P<slug>[\w-]+)/delete/$', post_delete, name='delete'),

post_detail.html

{% block content %}
<div class='col-sm-6 col-sm-offset-3'>
{% if instance.image %}
<img src='{{ instance.image.url }}' class='img-responsive' />
{% endif %}
<h1>
{{ title }} 
<small>
  {% if instance.draft %}
    <span style='color:red;'>Draft</span> 
       {% endif %}{{ instance.publish }}  
    <div class=''>
    <a href="{% url 'update' %}"> Edit </a> |
    <a href="{% url 'delete' %}"> Delete</a> 
    </div>
  </small>
</h1>

Upvotes: 3

Views: 6718

Answers (1)

zaidfazil
zaidfazil

Reputation: 9235

You need to pass the slug into the url tag in the html.

Try something like this,

<a href="{% url 'update' slug=instance.slug %}"> Edit </a>
<a href="{% url 'delete' slug=instance.slug %}"> Delete</a> 

Upvotes: 9

Related Questions