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

我正在尝试在 url 中使用用户的用户名创建 UserProfileView 。实际上,它以某种方式与实际设置配合使用。问题是,网址中的任何用户名扩展都会重定向到登录用户的个人资料。而且,当我尝试在不登录的情况下进入个人资料时,模板中没有任何信息。这是我的代码,感谢任何帮助。


models.py


class 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.py


class 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.py


urlpatterns = [

  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>


温温酱
浏览 100回答 1
1回答

饮歌长啸

您需要添加BaseDetailView、定义get_object方法并添加'user'到上下文:class UserProfileView(SelectRelatedMixin, BaseDetailView, TemplateView):&nbsp; model = Profile&nbsp; template_name = 'accounts/profile.html'&nbsp; select_related = ('user',)&nbsp; def get_object(self):&nbsp; &nbsp;return self.get_queryset().get(user__username=self.kwargs['username'])&nbsp; def get_context_data(self, **kwargs):&nbsp; &nbsp; context = super().get_context_data(**kwargs)&nbsp; &nbsp; content['user'] = self.object.user&nbsp; &nbsp; return context或者,您可以将您的观点基于User模型,而不是Pofile(我认为这种方式更简单):class UserProfileView(SelectRelatedMixin, BaseDetailView, TemplateView):&nbsp; model = User&nbsp; template_name = 'accounts/profile.html'&nbsp; select_related = ('profile',)&nbsp; def get_object(self):&nbsp; &nbsp;return self.get_queryset().get(username=self.kwargs['username'])&nbsp; def get_context_data(self, **kwargs):&nbsp; &nbsp; context = super().get_context_data(**kwargs)&nbsp; &nbsp; content['user'] = self.object&nbsp; &nbsp; return context或者您甚至可以不费心添加'user'到上下文中,只需通过以下方式访问模板中的用户object
打开App,查看更多内容
随时随地看视频慕课网APP