亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用戶個人資料對所有用戶可見包括 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 關注
  • 141 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號