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