Skip to content Skip to sidebar Skip to footer

Django Noreversematch At /qw-1/

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 url(r'^deletePost/(?P[\w-]+)/$', views.delete_pos

Solution 1:

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:

defdelete_post(request, slug=None, id=None):
    if slug:
        posts=Post.objects.get(slug=slug)
    ifid:
        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..

Solution 2:

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:

<formmethod="POST"action="{% url 'delete_post' slug=post.id id=post.id %}">{% csrf_token %}

    <buttontype="submit"class="btn btn-danger"> &nbsp Delete</button></form>

Post a Comment for "Django Noreversematch At /qw-1/"