[英]Why this code doesn't work, how do I grab a specific part of url?
I have the following url http://localhost:8000/enthusiastically-synergize-optimal-results-after-proactive-total-linkage/edit/
and would like to access that slug from this url in this function so I can use it. 我有以下网址
http://localhost:8000/enthusiastically-synergize-optimal-results-after-proactive-total-linkage/edit/
并希望在此函数中从该网址访问该链接,以便使用。 In class based view I could use self.kwargs.get('smthng')
and grab that but don't know how do I do that here: 在基于类的视图中,我可以使用
self.kwargs.get('smthng')
并抓住它,但不知道我该怎么做:
def permission_of_user_for_posts(request):
post = get_object_or_404(Blog, slug= request.GET.get('blog_slug'))
if request.user.username == post.author:
return True
return False
@user_passes_test(permission_of_user_for_posts)
def blog_update(request, blog_slug):
blog = get_object_or_404(Blog, slug=blog_slug)
if request.method == 'POST':
form = BlogForm(request.POST, request.FILES, instance=blog)
if form.is_valid():
form.instance.author = request.user
form.save()
return redirect('/')
form = BlogForm(instance=blog)
context= {
'form': form
}
return render(request, 'blogs/form.html', context)
or is there something else that I am doing it wrong in permission_of_user_for_posts
function? 还是在
permission_of_user_for_posts
函数中我做错了什么? please help me thank you 请帮我谢谢
edit: this is url 编辑:这是网址
urlpatterns = [
path('', blogs_view.home, name='home'),
path('blogs/', blogs_view.blogs, name='blogs'),
path('<slug:blog_slug>', blogs_view.blog_detail, name='blog_detail'),
path('post/', blogs_view.blog_create, name='blog_create'),
path('<slug:blog_slug>/edit/', blogs_view.blog_update, name='blog_update'),
path('<slug:blog_slug>/delete/', blogs_view.blog_delete, name='blog_delete'),
]
The way to do this is not to use the decorator or a separate function at all. 做到这一点的方法是根本不使用装饰器或单独的功能。 Just check the post in the view:
只需查看视图中的帖子即可:
def blog_update(request, blog_slug):
blog = get_object_or_404(Blog, slug=blog_slug)
if not request.user == blog.author:
raise PermissionDenied
if request.method == 'POST':
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.