【发布时间】:2021-10-27 14:23:08
【问题描述】:
对于 Django 来说还是很新的东西,并试图弄清楚如何在通过导航栏点击“查看个人资料”时显示当前用户的个人资料,以及在其他人的项目页面上点击“查看个人资料”时如何显示特定用户。目前,点击导航栏时,它正确返回当前用户的个人资料,但是,当在项目详情页面点击查看其他人的页面时,它仍然返回当前用户,而不是所需用户的个人资料页面。
我仍然希望 url 像这样显示: 'accounts/username/view_profile' 而不是 'accounts/pk/view_profile'
我已尝试在 ViewProfileView 中使用“get_context_data”方法,但它返回有关使用 slugs 或对象 pk 调用 url 的错误。
models.py 我想我已经正确设置了 slug,但我不确定如何实现它,或者这是否甚至可以解决我的问题 - 我已经尝试将 slug 添加到url-conf 并通过 views.py 中的 get_context_data 传递它,但我永远无法让它正常工作,只是一个又一个错误。
...
class Profile(models.Model):
user = models.OneToOneField(User, null=True, on_delete=models.CASCADE)
slug = models.SlugField(blank=True, db_index=True, unique=True)
about = models.TextField(max_length=500, null=True, blank=True)
profile_pic = models.ImageField(null=True, blank=True, upload_to="images/profile")
facebook_url = models.CharField(max_length=255, null=True, blank=True)
twitter_url = models.CharField(max_length=255, null=True, blank=True)
instagram_url = models.CharField(max_length=255, null=True, blank=True)
linkedin_url = models.CharField(max_length=255, null=True, blank=True)
github_url = models.CharField(max_length=255, null=True, blank=True)
def save(self, *args, **kwargs):
if not self.slug:
self.slug = self.user.username
super(Profile, self).save(*args, **kwargs)
...
views.py 在这里您可以看到我对 get_context_data 的尝试。 get_object 返回当前用户,该用户在浏览导航栏时有效,但在浏览其他人的项目帖子时无效。如果请求是通过导航栏和其他请求是通过个人资料页面时,有没有办法让它动态到我可以返回 get_object 的位置?
...
class ViewProfileView(generic.DetailView):
model = Profile
template_name = 'registration/view_profile.html'
def get_object(self):
return self.request.user.profile
# def get_context_data(self, *args, **kwargs):
# users = Profile.objects.all()
# ctx = super(ViewProfileView, self).get_context_data(*args, **kwargs)
# page_user = get_object_or_404(Profile, id=self.kwargs['username'])
# ctx['page_user'] = page_user
# return ctx
...
urls.py
...
app_name = 'accounts'
urlpatterns = [
path('signup/', SignUpView.as_view(), name='signup'),
path('<str:username>/edit_user/', EditUserView.as_view(), name='edit_user'),
path('password/', ChangePasswordView.as_view(), name='change-password'),
path('password_success/', password_success, name='password_success'),
path('<str:username>/view_profile/', ViewProfileView.as_view(), name='view_profile'),
path('<str:username>/edit_profile/', EditProfileView.as_view(), name='edit_profile')
]
base.html (导航栏,去自助)
...
<a class="dropdown-item" href="{% url 'accounts:view_profile' user.username %}">View Profile</a>
...
project_detail.html (转到另一个用户的个人资料但返回自我,不起作用)
...
<a href="{% url 'accounts:view_profile' project.owner.username %}">View Profile</a><br></small></i>
...
感谢您的宝贵时间!非常感谢任何帮助!干杯
【问题讨论】: