我是django的新手,并且使用slug ,现在我很困惑如何使用ID参数并转换为slug
URL.py
url(r'^deletePost/(?P<slug>[\w-]+)/$', views.delete_post, name='delete_post')
模板
<form method="POST" action="{% url 'delete_post' id=post.id %}">{% csrf_token %}
<button type="submit" class="btn btn-danger">   Delete</button>
</form>
Views.py
def delete_post(request,slug):
posts=Post.objects.get(slug=slug)
if request.method == 'POST':
posts.delete()
return redirect("home")
我如何使用slug&amp; id删除创建的帖子
感谢任何帮助。提前致谢
答案 0 :(得分:4)
在我的意见中,你不想将id转换为slug。您可以使应用程序足够灵活,以便可以slug
或id
删除。您只需要相应地处理参数。
所以,你可以这样做:
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')
在观点中:
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")
请注意,您可以将2个URL模式压缩为单个模式 - 但这种方法使其可读且易于理解。一旦你对django框架等感到满意,我会让你弄清楚URL合并。
答案 1 :(得分:1)
如果你想同时使用slug和id,你的URL模式应如下所示:
url(r'^deletePost/(?P<slug>[\w-]+)-(?P<id>[0-9]+)/$',
views.delete_post, name='delete_post')
您的观点应如下所示:
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)
您的模板还必须同时设置:
<form method="POST" action="{% url 'delete_post' slug=post.id id=post.id %}">{% csrf_token %}
<button type="submit" class="btn btn-danger">   Delete</button>
</form>