通用详细视图ProfileView必须使用对象pk或slug之一进行调用。

30 浏览
0 Comments

通用详细视图ProfileView必须使用对象pk或slug之一进行调用。

我是Django 2.0的新手,当访问我的个人资料页面时遇到了这个错误。它可以使用类似于path('users/')的URL正常工作,但我希望URL像path('')这样。不确定问题出在哪里。希望你能帮助我。

#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('', ProfileView.as_view(), name='profile')
]
#base.html

0
0 Comments

问题出现的原因是在使用Generic detail view的时候,ProfileView必须使用对象的pk或者slug进行调用,但是在代码中并没有提供这两个参数。解决方法可以通过修改路径来传递username参数,或者在ProfileView中重写get_object方法,通过request对象获取用户数据。具体的修改代码如下:

将路径修改为:

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

在html中使用如下代码:

{% url 'accounts:profile' username=user.username %}

另一种方法是将路径修改为:

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

在profile模板中使用request.user来访问用户数据。

在ProfileView中重写get_object方法,代码如下:

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

需要注意的是,以上方法中的path不接受正则表达式。

希望以上的解决方法能够解决问题,如有其他问题,请留言。

0
0 Comments

问题原因:在编写视图时,没有明确告诉视图要使用username作为查找字段。

解决方法:可以通过在模型上定义slug_fieldslug_url_kwarg,或者通过重写get_object来指定username作为查找字段。

例如:

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

其中,slug_field确定在模型查找中使用的字段,slug_url_kwarg确定从URL模式中使用的变量。

别忘了接受答案,作为对未来搜索者的提示。

0