【发布时间】:2021-01-30 09:26:47
【问题描述】:
我正在尝试使用 url 中的用户名创建 UserProfileView。实际上,它以某种方式与实际设置一起工作。问题是,url 中的任何用户名扩展都会重定向到登录用户的个人资料。而且,当我尝试在不登录的情况下进入个人资料时,模板中没有任何信息。这是我的代码,感谢任何帮助。
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>
*为更清晰的解释更新:
【问题讨论】:
-
不是很清楚你的问题是什么
-
尝试添加问题的示例图片。希望现在更容易理解。
-
User或Profile模型上是否有username字段?试图弄清楚为什么您将视图用于配置文件而不是仅用于用户... -
没错,User模型的用户名是attr。此外,Profile 模型通过 OneToOneField 与 User 模型连接。
-
那么您能否只创建
UserView而不是使用User模型而不是Profile的UserProfileView?不是更简单吗?我在模板中看到,无论如何您都可以通过user.profile访问profile...
标签: python django django-models django-views django-templates