Django:通过ModelForm创建帖子时,如何将用户与创建的帖子相关联 [英] Django : How to associate a user to a created post when post is created through a ModelForm

查看:96
本文介绍了Django:通过ModelForm创建帖子时,如何将用户与创建的帖子相关联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个普通的Django posts app,基本上可以创建一个post及其内容。
现在的事情是,我在form.py中将create post表单实现为modelform。现在,如果它不是modelform而是html-form,我将拥有用户 request.POST。 get('data')
但是现在当我使用

I created a normal Django posts app , which basically create a post and its content. Now the thing is that I implemented the create post form as a modelform in forms.py .Now if it wasnt a modelform and just a html-form , I would have user request.POST.get('data') But now when I used

class PostForm(forms.ModelForm):
class Meta:
    model = Post
    fields = (
        'title',
        'content',
        'image',
    )

Model.py

class Post(models.Model):
    title = models.CharField(max_length=100)
    image = models.ImageField(null=True,blank=True)
    content = models.TextField()
    user = models.ForeignKey(User,on_delete=models.CASCADE,null=True)

Views.py

def create(request):
    form = PostForm(request.POST or None)
    if form.is_valid():
        instance = form.save(commit=False)
        instance.save()
        return HttpResponseRedirect('/home')
    return render(request,'create.html',{'form':form})

如何将用户加入到创建的帖子中

How can I join a user to a created post

推荐答案

您只需分配用户到两个保存功能之间的实例:

You can simply assign the user to the instance in between the two save functions:

instance = form.save(commit=False)
instance.user = request.user
instance.save()

这篇关于Django:通过ModelForm创建帖子时,如何将用户与创建的帖子相关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆