如何创建 django 模型的实例

问题描述 投票:0回答:1

views.py

def create_post(request):
    profile_inst = Profile.objects.filter(author_real=request.user).first()

    print(profile_inst)

    if request.method == 'POST':
        print('POST request')
        form = CreatePost(request.POST,request.FILES)
        if form.is_valid():
            print(request.FILES)
            form.save()
        
    else:
        print('JUST a VISIT!')
        form=CreatePost(initial={'author':profile_inst})
    
    return render(request,'create_post.html',{'form':form})
ValueError at /create_post/
Cannot assign "'username | admin'": "Post.author" must be a "Profile" instance.

Post Model

class Post(models.Model):
    post_id = models.IntegerField(default=0)
    author = models.ForeignKey(Profile,on_delete=models.CASCADE,null=True,blank=True,default='')
    title = models.CharField(max_length=255,default="No Title")
    views = models.IntegerField(default=0)
    posted_on = models.DateTimeField(auto_now_add=True)
    thumbnail = models.ImageField(upload_to='images/',default='')
    content = RichTextField(default='',blank=True,null=True)


     def __str__(self):
        return f'{self.title}'

CreatePost Model

class CreatePost(ModelForm):
    thumbnail = forms.ImageField()
    title = forms.TextInput()
    author = forms.CharField(widget=forms.HiddenInput())
    # author = forms.TextInput(widget=forms.HiddenInput())

    class Meta:
        model=Post
        exclude=['views','posted_on','post_id']

上面是我在我正在制作的博客上创建帖子的观点,但由于某种原因 django 不接受 profile_inst 作为 Profile 实例并给出上面显示的错误。

请忽略 post_id 字段,该字段是我出于某种目的而创建的,但据我所知尚未使用。

感谢任何努力!

python html django web-development-server web-developer-toolbar
1个回答
0
投票

将以下代码与

commit=False
一起使用。

form = CreatePost(request.POST,request.FILES)
if form.is_valid():
    print(request.FILES)
    post=form.save(commit=False)
    post.author = profile_inst
    post.save()
© www.soinside.com 2019 - 2024. All rights reserved.