[英]Comment model for User only Django
I hope you're well.我希望你很好。 I'm beginning with Django. I'd like to create a comment for users only.
我从 Django 开始。我只想为用户创建评论。 I've created a UserProfile page before (with image for each member).
我之前创建了一个 UserProfile 页面(每个成员都有图像)。
For my comment models.对于我的评论模型。 Do I need to add field for the image related to UserProfile?
我是否需要为与 UserProfile 相关的图像添加字段? Or User is enough, like that?
还是 User 就足够了? if a user comment something I want to display his username and his image.
如果用户评论我想显示他的用户名和他的图像。
class Comment(models.Model):
post = models.ForeignKey(Post,on_delete=models.CASCADE,related_name="comments")
user = models.ForeignKey(User)
content = models.TextField(max_length=160)
publishing_date = models.DateField(auto_now_add=True)
def __str__(self):
return self.post.title
models.py (UserProfile) models.py(用户配置文件)
class UserProfile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE)
image = models.ImageField(null=True,blank=True,default='user/user-128.png', upload_to='user/')
slug = models.SlugField(editable=False)
def save(self, *args,**kwargs):
self.slug = slugify(self.user.username)
super(UserProfile, self).save(*args, **kwargs)
img = Image.open(self.image.path)
if img.height > 200 or img.width > 200:
new_size = (200, 200)
img.thumbnail(new_size)
img.save(self.image.path)
def __str__(self):
return self.user.username
No need to add image field or user name field in comment model as User model is its foreign key.评论model不需要添加图片字段和用户名字段,因为用户model是它的外键。
You can use like this Comments = Comment.objects.values('post', 'user__name', 'user__image')你可以像这样使用 Comments = Comment.objects.values('post', 'user__name', 'user__image')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.