Django创建含用户帖子的UserProfileView(DetailView)报错求助
解决Django UserProfileView帖子过滤错误
错误原因
你在get_context_data里用Profile.user过滤帖子,这是Profile模型类的字段描述符,不是当前视图对应的具体Profile实例的用户对象。Django无法将这个描述符转化为用户ID,所以抛出类型错误。
修正后的视图代码
class UserProfileView(DetailView): model = Profile context_object_name = 'profile' template_name = 'users/profile.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) # 获取当前页面对应的Profile实例 current_profile = self.get_object() # 过滤该用户发布的所有帖子 context['user_posts'] = Post.objects.filter(author=current_profile.user) # 或者用反向关联更简洁:current_profile.user.post_set.all() return context
额外优化建议
- 给Post模型的author字段添加
related_name,让反向关联更直观:
class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='posts') # 其他字段保持不变...
之后在视图里可以用current_profile.user.posts.all()替代过滤语句,代码更清晰。
- Profile模型的slug字段
default=user存在逻辑问题,因为user是模型字段而非可调用的默认值。可以改为自动生成slug:
from django.utils.text import slugify class Profile(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, primary_key=True) display_name = models.CharField(max_length=32) profile_picture = models.ImageField( default='assets/default.jpg', upload_to='profile_pictures') slug = models.SlugField(max_length=150, blank=True) def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.user.username) super().save(*args, **kwargs) def get_absolute_url(self): return reverse("profile", kwargs={"pk": self.pk})
内容的提问来源于stack exchange,提问作者wisie
相关产品推荐
相关产品推荐

