使用户配置文件对所有用户可见包括Django上的AnonyMouseUser()



我正试图在url中使用用户的用户名创建UserProfileView。事实上,它在某种程度上与实际设置相匹配。问题是,url中的任何用户名扩展都会重定向到登录用户的配置文件。而且,当我尝试在没有登录的情况下进入个人资料时,模板中没有任何信息。这是我的代码,如果有任何帮助,我们将不胜感激。

型号.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>

*更新以获得更清晰的解释:

这是在没有登录的情况下尝试的用户配置文件

和登录时相同的用户配置文件。实际上,它应该显示url中用户名的用户的配置文件。但是,它总是在任何url上显示当前用户的配置文件。

您需要添加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访问模板中的用户

最新更新