微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何将用户连接到他在 Django 中创建的帖子

如何解决如何将用户连接到他在 Django 中创建的帖子

我从 Django 开始,我有一个关于帖子和创建它的用户间的联系的问题。现在,我设法创建了链接,但是,每当我创建一个新帖子时,用户 ID 始终是认的,因此是一个。我想让用户 id 是创建帖子的人的 id,并且出于某种原因,它永远不会起作用。我尝试的另一个选项是将“用户”放入表单中,但问题是用户可以选择他是哪个用户,这是有风险的。那么有没有办法让它自动呢?创建帖子时,正确的用户ID直接连接到它?感谢您的帮助!!

模型.py

"""

class Post(models.Model):      
    user = models.ForeignKey(User,on_delete=models.CASCADE,default=1)      
    image = models.ImageField(default="man.jpg")      
    titre = models.CharField(max_length=50)      
    slug = models.SlugField(max_length=100)      
    date_publication = models.DateTimeField(auto_Now_add=True)

"""

view.py

"""

@login_required  
    def post_create(request):      
    if request.method == "POST":          
        post_form = PostForm(request.POST)          
        if post_form.is_valid():              
            post_form.save()              
            messages.success(request,'Your post was successfully created!')              
            return redirect('seed:view_seed')          

        else:              
            messages.error(request,'Please correct the error below.') 
           
    else:          
        post_form = PostForm(request.POST)    

    return render(request,"post/create.html",context={"post_form": post_form})  

"""

forms.py

"""

class PostForm(ModelForm):
     class Meta:          
         model = Post          
         fields = ["user","image","titre","slug"]

"""

解决方法

您从表单中的字段中删除 user 字段:

class PostForm(ModelForm):
    class Meta:
        model = Post
        # no user ↓
        fields = ['image','titre','slug']

并在视图中将登录用户添加到包装在表单中的实例中:

@login_required
def post_create(request):
    if request.method == 'POST':
        post_form = PostForm(request.POST)
        if post_form.is_valid():
            # add user to the instance ↓
            post_form.instance.user = request.user
            post_form.save()
            messages.success(request,'Your post was successfully created!')
            return redirect('seed:view_seed')
        else:
            messages.error(request,'Please correct the error below.')
    else:
        post_form = PostForm()
    return render(request,"post/create.html",context={"post_form": post_form})

注意:通常使用 settings.AUTH_USER_MODEL [Django-doc] 来引用用户模型比直接使用 User model [Django-doc] 更好。有关详细信息,您可以查看 referencing the User model section of the documentation

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。