Django NoReverseMatch at /qw-1/

后端 未结 2 1255
旧时难觅i
旧时难觅i 2021-01-15 17:43

Im new to django and was struck by using slug, now Im confused how to use the ID parameter and convert to slug

URL.py



        
相关标签:
2条回答
  • 2021-01-15 18:24

    In my opionion, you dont want to convert the id to slug. You can just make your application flexible enough so that you could delete by either slug or id. You just need to handle the parameters accordingly.

    So, you can do something like this:

    urls.py

    url(r'^deletePost/(?P<slug>[\w-]+)/$', views.delete_post, name='delete_post_by_slug'),
    url(r'^deletePost/(?P<id>[0-9]+)/$', views.delete_post, name='delete_post_by_id')
    

    And in the views:

    def delete_post(request, slug=None, id=None):
        if slug:
            posts=Post.objects.get(slug=slug)
        if id:
            posts=Post.objects.get(id=id)
        #Now, your urls.py would ensure that this view code is executed only when slug or id is specified
    
        #You might also want to check for permissions, etc.. before deleting it - example who created the Post, and who can delete it.
        if request.method == 'POST':
            posts.delete()
            return redirect("home")
    

    Note that you can compress the 2 URL patterns into a single one - but this approach keeps it readable, and understandable. I shall let you figure out the URL consolidation once you are comfortable with the django framework, etc..

    0 讨论(0)
  • 2021-01-15 18:38

    If you want to use both slug and id, your URL pattern should look like this:

    url(r'^deletePost/(?P<slug>[\w-]+)-(?P<id>[0-9]+)/$',
        views.delete_post, name='delete_post')
    

    And your view should look like this:

    def delete_post(request, **kwargs):
        # Here kwargs value is {'slug': 'qw', 'id': '1'}
        posts = Post.objects.get(**kwargs)
        if request.method == 'POST':
            posts.delete()
            return redirect('home')
        # ... (I guess this view does not end here)
    

    And your template also have to set both:

    <form method="POST" action="{% url 'delete_post' slug=post.id id=post.id %}">{% csrf_token %}
    
        <button type="submit" class="btn btn-danger"> &nbsp Delete</button>
    </form>
    
    0 讨论(0)
提交回复
热议问题