我是Django 2.0的新手,在访问我的个人资料页面视图时遇到此错误。它正在使用path('users/<int:id>')
等网址,但我希望网址像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>
答案 0 :(得分:6)
您需要告诉您的视图使用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'
第一个确定在模型查找中使用哪个字段;第二个确定从URL模式使用的变量。
答案 1 :(得分:-1)
为什么你不能简单地改变你的路径:
url('(?P<username>[\w]+)', ProfileView.as_view(), name='profile')
然后在你的HTML中执行此操作:
{% url 'accounts:profile' username=user.username %}
另一种方法是:
url('accounts/profile', ProfileView.as_view(), name='profile')
在您的个人资料模板中,使用request.user来访问您的用户数据
编辑:
尝试按照here
所述覆盖get_object
方法
def get_object(self):
return get_object_or_404(User, pk=request.session['user_id'])