Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(Django) Reverse dynamic urls with multiple arguments using Django Views

I am trying to pass two arguments to make a dynamic URL for each post of a blog app I'm working on. I get it to work if I pass the id, but don't know what's the syntax when using +1 arguments (nor if I'm doing things right).

I want to make urls be 'post/<int:pk>/<slug:slug>/' but can only make it work with the id: 'post/<int:pk>/

Here's how I have it now:

URLS.PY

    urlpatterns = [
    ...
    path('post/<int:pk>/<slug:slug>/', PostDetailView.as_view(), name='post-detail'),
    path('post/new/', PostCreateView.as_view(), name='post-create'),
    path('post/<int:pk>/<slug:slug>/update/', PostUpdateView.as_view(), name='post-update'),
    path('post/<int:pk>/<slug:slug>/delete/', PostDeleteView.as_view(), name='post-delete'),
    ...
    ]

VIEWS.PY

   class PostDetailView(DetailView):
        model = Post

I am calling this in the template:

   <ul class="secondary-menu menu-list">
        <li class="menu-item"><a href="{% url 'post-update' object.slug %}">Edit Post</a></li>
    <li class="red-button"><a href="{% url 'post-delete' object.slug %}">Delete</a></li>
    </ul>

And have this function to retrieve the path to any specific instance in MODELS.py

   def get_absolute_url(self):
        return reverse('post-detail', kwargs={'pk': self.pk, 'slug':slug})

I get the following error during template rendering

Reverse for 'post-detail' with arguments '(1,)' not found. 1 pattern(s) tried: ['post/(?P<pk>[0-9]+)/(?P<slug>[-a-zA-Z0-9_]+)/$']
like image 542
Franco D'Angelo Avatar asked Mar 26 '26 19:03

Franco D'Angelo


1 Answers

    def get_absolute_url(self):
        return reverse('post-detail', kwargs={'pk': self.pk, 'slug':self.slug})

you missed the self in slug, else you need to pass slug as a parameter to the function if self is not needed.

like image 77
Exprator Avatar answered Mar 30 '26 00:03

Exprator



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!