我是 django 的新手并且被 slug 击中了,现在我很困惑如何使用 ID 参数并转换为 slug
网址.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>
View .py
def delete_post(request,slug):
posts=Post.objects.get(slug=slug)
if request.method == 'POST':
posts.delete()
return redirect("home")
我如何使用 slug 和 id 删除创建的帖子
感谢任何帮助。提前致谢
请您参考如下方法:
在我看来,您不想将 id 转换为 slug。您可以让您的应用程序足够灵活,以便您可以通过 slug 或 id 进行删除。您只需要相应地处理参数。
所以,你可以这样做:
网址.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')
在 View 中:
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 合并。
