【问题标题】:Django url (slug)Django 网址(蛞蝓)
【发布时间】:2021-04-04 06:17:48
【问题描述】:

问题是,我有一个迷你博客,里面有文章和用户简介(页面)。
我在站点/articlename
上显示文章 我想在站点/用户名

上显示用户帐户

views.py(文章):

def post_detail(request, slug):  
    post = get_object_or_404(Post, slug=slug)
    return render(request, 'post_detail.html', {'post': post })

views.py(个人资料用户):

class UserProfileView(DetailView):
    template_name = 'users/profile/profile-user-view.html'
    queryset = User.objects.all()

    def get_object(self):
        username = self.kwargs.get("username")
        return get_object_or_404(User, username=username)

网址:

path('<str:username>', UserProfileView.as_view(), name='user_detail')
path('<slug:slug>', views.post_detail, name='post_detail')

现在我的用户个人资料在 site/username 打开,但文章没有在以下位置打开 网站/文章名称

我怀疑 URL 中存在某种冲突(slug)。我怎样才能在没有其他目录的情况下打开站点/地址上的文章和帐户。如果有任何帮助,我将不胜感激。

【问题讨论】:

    标签: django django-models django-rest-framework django-views django-templates


    【解决方案1】:

    您可以只使用一个路径,然后在视图中检查给定字符串是否作为用户名或文章存在于您的数据库中,然后执行适当的操作。

    path('<str:path_string>', YourView.as_view(), name='yourview')
    

    然后在视图中只需对用户和帖子进行 2 次查询,并使用 path_string 作为过滤器。如果其中一个查询集不为空,则您获得了匹配项,您可以呈现适当的模板。 类似的东西

    post=Post.objects.filter(title=path_string)
    user=User.objects.filter(username=path_string)
    If post:
    ....
    

    【讨论】:

    • 谢谢,但我不知道如何用语法表达
    • 我更新了我的答案..这对你有帮助吗?
    • tjanks,你能写出完整的views.py吗?我似乎很困惑(
    【解决方案2】:

    谢谢@Razenstein,我想我明白了:

    def two_href(request, path_string):
        
            username = User.objects.filter(username=path_string)
            slug = Post.objects.filter(slug=path_string)
        
            if username:
                ...       
            elif slug:   
                ... 
            else:
                raise Http404("404 error")
    

    网址:

    path('<str:path_string>', views.two_href, name='two_href')
    

    【讨论】:

      猜你喜欢
      • 2014-07-30
      • 2018-04-22
      • 2018-08-27
      • 2010-09-30
      相关资源
      最近更新 更多