posts.models.blog.doesnotexist:不存在博客匹配查询

发布于 2025-02-03 01:32:48 字数 2187 浏览 3 评论 0 原文

我正在尝试使用Slug进行导航。这是html标签

<a href="{% url 'blog_details' blog.slug|slugify %}">Read More</a>

urls.py

path('details/<slug:slug>/', views.blog_details, name='blog_details'),

型号。

slug= models.SlugField(max_length=264,unique=True,null=True,allow_unicode=True)

这是我创建自动slug的方式,

def Creating_blog(request):
    form=BlogForm()
    if User.is_authenticated:
        if request.method=='POST':
                form=BlogForm(request.POST,request.FILES)
                if form.is_valid:
                    blog_obj=form.save(commit=False)
                    blog_obj.author=request.user
                    title=blog_obj.blog_title
                    blog_obj.slug = title.replace(' ','-') + '-'+ str(uuid.uuid4())
                    blog_obj.save()
                    return redirect('index')
    return render(request,'blogs/creatingblog.html',context={'form':form})

这是博客详细信息页面的视图,

def blog_details(request, slug):
    if User.is_authenticated:
        blog = Blog.objects.get(slug=slug)
        already_liked = Likes.objects.filter(blog=blog, user= request.user)
        if already_liked:
           liked = True
        else:
          liked = False
        comments=Comment.objects.filter(blog=blog)
        commet_form=CommentForm()
        if request.method=='POST':
          commet_form=CommentForm(request.POST)
        if commet_form.is_valid():
            comment=commet_form.save(commit=False)
            comment.user=request.user
            comment.blog=blog
            comment.save()
            return HttpResponseRedirect(reverse('blog_details',kwargs={'slug':slug}))
        return render(request,'blogs/blogdetails.html',context={'blog':blog,'comment_form':commet_form,'comments':comments,'like':liked})
    else:
        HttpResponseRedirect(reverse('login'))

必须出现问题

C:\Users\ITS\Desktop\blogger\Blog\posts\views.py, line 51, in blog_details
        blog = Blog.objects.get(slug=slug) 

如果我使用pk = id而不是slug,则 。但是,每当我试图用slug抓住错误时,错误就会上升。我在这里呆了几天,我找不到问题。

i am trying to use slug to navigate. here's the html tag

<a href="{% url 'blog_details' blog.slug|slugify %}">Read More</a>

urls.py

path('details/<slug:slug>/', views.blog_details, name='blog_details'),

models.py

slug= models.SlugField(max_length=264,unique=True,null=True,allow_unicode=True)

this is how i am creating auto slug

def Creating_blog(request):
    form=BlogForm()
    if User.is_authenticated:
        if request.method=='POST':
                form=BlogForm(request.POST,request.FILES)
                if form.is_valid:
                    blog_obj=form.save(commit=False)
                    blog_obj.author=request.user
                    title=blog_obj.blog_title
                    blog_obj.slug = title.replace(' ','-') + '-'+ str(uuid.uuid4())
                    blog_obj.save()
                    return redirect('index')
    return render(request,'blogs/creatingblog.html',context={'form':form})

this is the view of the blog details page

def blog_details(request, slug):
    if User.is_authenticated:
        blog = Blog.objects.get(slug=slug)
        already_liked = Likes.objects.filter(blog=blog, user= request.user)
        if already_liked:
           liked = True
        else:
          liked = False
        comments=Comment.objects.filter(blog=blog)
        commet_form=CommentForm()
        if request.method=='POST':
          commet_form=CommentForm(request.POST)
        if commet_form.is_valid():
            comment=commet_form.save(commit=False)
            comment.user=request.user
            comment.blog=blog
            comment.save()
            return HttpResponseRedirect(reverse('blog_details',kwargs={'slug':slug}))
        return render(request,'blogs/blogdetails.html',context={'blog':blog,'comment_form':commet_form,'comments':comments,'like':liked})
    else:
        HttpResponseRedirect(reverse('login'))

the problem is must be in

C:\Users\ITS\Desktop\blogger\Blog\posts\views.py, line 51, in blog_details
        blog = Blog.objects.get(slug=slug) 

if i use pk=id instead of slug, it works. But whenever i am trying to catch with the slug the error rises. i am stuck for days here i can't find what's wrong.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

む无字情书 2025-02-10 01:32:48

通过将slag通过 /code> 模板过滤器&nbsp; [django-doc] 它可能会转换一些sl,因此不再可能链接到原始slug。您应该删除模板过滤器,然后使用:

<a href="{% url 'blog_details' blog.slug %}">Read More</a>

但是,无论如何,不是不是一个好主意。您可以使用django's 函数&nbsp; [django-doc] 进行正确的操作。该视图还包含一些问题,例如 user.is_authenticated 将始终具有真实性 true ,因此永远不会失败, .is_valid() &nbsp; < sup> [django-doc] 是一种方法,因此您需要 call this:

from django.contrib.auth.decorators import login_required
from django.utils.text import slugify

@login_required
def creating_blog(request):
    form = BlogForm()
    if request.method == 'POST':
        form = BlogForm(request.POST, request.FILES)
        if form.is_valid():
            form.instance.author = request.user
            form.instance.slug = slugify(f'{form.instance.title} {uuid.uuid4()}')
            form.save()
            return redirect('index')
    return render(request, 'blogs/creatingblog.html', {'form':form})

注意:您可以将视图限制在视图中
/code> 装饰器&nbsp; [django-doc]


注意:您可以使用 django -autoslug &nbsp; [github] 自动创建基于其他字段的slug。



Note: It is often better to use

By passing the slug through the |sligify template filter [Django-doc] it might transform some slugs, such that linking to the original slug is no longer possible. You should remove the template filter, and work with:

<a href="{% url 'blog_details' blog.slug %}">Read More</a>

But regardless, slugifying yourself is not a good idea. You can use Django's slugify(…) function [Django-doc] to do this properly. The view also contains some problems, for example User.is_authenticated will always have truthiness True, and thus never fail, and .is_valid() [Django-doc] is a method, so you need to call this:

from django.contrib.auth.decorators import login_required
from django.utils.text import slugify

@login_required
def creating_blog(request):
    form = BlogForm()
    if request.method == 'POST':
        form = BlogForm(request.POST, request.FILES)
        if form.is_valid():
            form.instance.author = request.user
            form.instance.slug = slugify(f'{form.instance.title} {uuid.uuid4()}')
            form.save()
            return redirect('index')
    return render(request, 'blogs/creatingblog.html', {'form':form})

Note: You can limit views to a view to authenticated users with the
@login_required decorator [Django-doc].


Note: You can make use of django-autoslug [GitHub] to automatically create a slug based on other field(s).


Note: It is often better to use get_object_or_404(…) [Django-doc],
then to use .get(…) [Django-doc] directly. In case the object does not exists,
for example because the user altered the URL themselves, the get_object_or_404(…) will result in returning a HTTP 404 Not Found response, whereas using
.get(…) will result in a HTTP 500 Server Error.

心是晴朗的。 2025-02-10 01:32:48

终于有效。我刚刚做出了一些更改。 锚标签

<a href="{% url 'blog_details' slug=blog.slug %}">Read More</a>

更改此另一个错误后的

NoReverseMatch at /blogs/
Reverse for 'blog_details' with keyword arguments '{'slug': '9Analysing-the-FIA-Rulebook-after-the-Abu-Dhabi-Grand-Prix-—-A-Lawyer’s-Perspective-9861e7b8-1c14-4fdd-abb6-e2d8398cf318'}' not found. 1 pattern(s) tried: ['details/(?P<slug>[-a-zA-Z0-9_]+)/

是我更改了urls.py

path('details/<slug>/', views.blog_details, name='blog_details'),
]

是我更改了urls.py


Finally it works. I have just made a little changes. The anchor tags

<a href="{% url 'blog_details' slug=blog.slug %}">Read More</a>

after changing this one other error was

NoReverseMatch at /blogs/
Reverse for 'blog_details' with keyword arguments '{'slug': '9Analysing-the-FIA-Rulebook-after-the-Abu-Dhabi-Grand-Prix-—-A-Lawyer’s-Perspective-9861e7b8-1c14-4fdd-abb6-e2d8398cf318'}' not found. 1 pattern(s) tried: ['details/(?P<slug>[-a-zA-Z0-9_]+)/

i changed the urls.py

path('details/<slug>/', views.blog_details, name='blog_details'),
]

i changed the urls.py



    
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文