为了账号安全,请及时绑定邮箱和手机立即绑定

使用户个人资料对所有用户可见包括 Django 上的 AnonyMouseUser()

使用户个人资料对所有用户可见包括 Django 上的 AnonyMouseUser()

PHP
温温酱 2023-11-09 21:18:21
我正在尝试在 url 中使用用户的用户名创建 UserProfileView 。实际上,它以某种方式与实际设置配合使用。问题是,网址中的任何用户名扩展都会重定向到登录用户的个人资料。而且,当我尝试在不登录的情况下进入个人资料时,模板中没有任何信息。这是我的代码,感谢任何帮助。models.pyclass Profile(models.Model):  user = models.OneToOneField(User, related_name='profile', on_delete=models.CASCADE)  email = models.EmailField(max_length=150)  bio = models.TextField(max_length=280, blank=True)  avatar = models.ImageField(default='default.jpg', upload_to='avatars/')  def __str__(self):    return '@{}'.format(self.user.username)  def save(self):    super().save()    img = Image.open(self.avatar.path)    if img.height > 300 or img.width > 300:      output_size = (300, 300)      img.thumbnail(output_size, Image.BICUBIC)      img.save(self.avatar.path)views.pyclass UserProfileView(SelectRelatedMixin, TemplateView):  model = Profile  template_name = 'accounts/profile.html'  select_related = ('user',)  def get_context_data(self, **kwargs):    context = super().get_context_data(**kwargs)    return context  def get_success_url(self):    return reverse('accounts:profile', kwargs={'user': self.object.user})urls.pyurlpatterns = [  path('<str:username>/', views.UserProfileView.as_view(), name='profile')]profile.html(我如何调用模板中的相关数据)<h3>{{ user.profile }}</h3>      <p>{{ user.profile.email }}</p>      <p>{{ user.profile.bio }}</p>        <h3>{{ profile }}</h3>
查看完整描述

1 回答

?
饮歌长啸

TA贡献1951条经验 获得超3个赞

您需要添加BaseDetailView、定义get_object方法并添加'user'到上下文:


class UserProfileView(SelectRelatedMixin, BaseDetailView, TemplateView):

  model = Profile

  template_name = 'accounts/profile.html'

  select_related = ('user',)


  def get_object(self):

   return self.get_queryset().get(user__username=self.kwargs['username'])


  def get_context_data(self, **kwargs):

    context = super().get_context_data(**kwargs)

    content['user'] = self.object.user

    return context

或者,您可以将您的观点基于User模型,而不是Pofile(我认为这种方式更简单):


class UserProfileView(SelectRelatedMixin, BaseDetailView, TemplateView):

  model = User

  template_name = 'accounts/profile.html'

  select_related = ('profile',)


  def get_object(self):

   return self.get_queryset().get(username=self.kwargs['username'])


  def get_context_data(self, **kwargs):

    context = super().get_context_data(**kwargs)

    content['user'] = self.object

    return context

或者您甚至可以不费心添加'user'到上下文中,只需通过以下方式访问模板中的用户object


查看完整回答
反对 回复 2023-11-09
  • 1 回答
  • 0 关注
  • 62 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信