我是Django 2.0的新手,访问个人资料页面视图时出现此错误。它与urls类似,path('users/<int:id>')但是我想urls like 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>
Run Code Online (Sandbox Code Playgroud)
您需要告诉您的视图username用作查找字段。您可以通过在模型上定义slug_field和slug_url_kwarg或通过重写来做到这一点get_object。例如:
class ProfileView(views.LoginRequiredMixin, generic.DetailView):
model = models.User
template_name = 'accounts/profile.html'
slug_field = 'username'
slug_url_kwarg = 'username'
Run Code Online (Sandbox Code Playgroud)
其中的第一个确定在模型查找中使用哪个字段。第二个参数根据URL模式确定要使用的变量。
Ale*_*rri -1
为什么你不简单地将路径更改为:
url('(?P<username>[\w]+)', ProfileView.as_view(), name='profile')
Run Code Online (Sandbox Code Playgroud)
然后在你的 html 中执行以下操作:
{% url 'accounts:profile' username=user.username %}
Run Code Online (Sandbox Code Playgroud)
另一种方法是这样做:
url('accounts/profile', ProfileView.as_view(), name='profile')
Run Code Online (Sandbox Code Playgroud)
并在您的个人资料模板中使用 request.user 来访问您的用户数据
编辑:
尝试重写这里get_object解释的方法
def get_object(self):
return get_object_or_404(User, pk=request.session['user_id'])
Run Code Online (Sandbox Code Playgroud)