Search code examples
pythonhtmldjangoweb-development-serverweb-developer-toolbar

How to create instance of a django model


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']

above is my view to create post on the blog i'm making, but for some reason django is not accepting profile_inst as a Profile instance and givin' the error shown above.

Please ignore the post_id field, that i just created for some purpose but is not yet being used yet as of my knowledge.

appreciating any efforts!


Solution

    1. Use the below code with 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()
    

    Since it is the logged-in use who creat posts, you don't need to let the user type their name. So remove author = forms.CharField(widget=forms.HiddenInput()) line. We can set post author automatically using 1) code.

    class CreatePost(ModelForm):
        thumbnail = forms.ImageField()
        title = forms.TextInput()
    # Remove the below lines
        #author = forms.CharField(widget=forms.HiddenInput())
        # author = forms.TextInput(widget=forms.HiddenInput())
    
        class Meta:
            model=Post
            exclude=['views','posted_on','post_id']
    

    If you want to show the user name/info in post creation form, use

    {{ request.user.profile }} .