必须使用对象pk或slug调用泛型详细信息视图ProfileView

2024-04-26 03:34:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我是Django 2.0的新手,在访问我的profile页面视图时遇到了这个错误。它使用的是path('users/<int:id>')这样的url,但我希望url像path('<username>')。不知道到底是什么问题。我希望你能帮忙。在

#views.py
class ProfileView(views.LoginRequiredMixin, generic.DetailView):
    model = models.User
    template_name = 'accounts/profile.html'


#urls.py
urlpatterns = [
    path('', HomePageView.as_view(), name='home'),
    path('signup', SignUpView.as_view(), name='signup'),
    path('login', LoginView.as_view(), name='login'),
    path('logout', logout_view, name='logout'),
    path('<username>', ProfileView.as_view(), name='profile')
]


#base.html
<ul class="dropdown-menu">
    <li><a href="{% url 'accounts:profile' user.username %}">View Profile</a></li>
    <li><a href="#">Edit Profile</a></li>
</ul>

Tags: pathnamepyviewurlhtmlasusername
2条回答

为什么不简单地改变你的路径:

url('(?P<username>[\w]+)', ProfileView.as_view(), name='profile')

然后在html中执行以下操作:

^{pr2}$

另一种方法是:

url('accounts/profile', ProfileView.as_view(), name='profile')

在你的配置文件模板中使用请求.用户访问用户数据

编辑:

尝试重写get_object方法,如here所述

def get_object(self):
    return get_object_or_404(User, pk=request.session['user_id'])

您需要告诉您的视图使用username作为查找字段。您可以通过在模型上定义slug_field和{}来实现这一点,或者重写{}。例如:

class ProfileView(views.LoginRequiredMixin, generic.DetailView):
    model = models.User
    template_name = 'accounts/profile.html'
    slug_field = 'username'
    slug_url_kwarg = 'username'

第一个决定在模型查找中使用哪个字段;第二个决定从URL模式使用什么变量。在

相关问题 更多 >