How to create instance of a django model

51 Views Asked by At

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!

2

There are 2 best solutions below

9
Pycm On BEST ANSWER
  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 }} .

1
Yassou Sk On

It is not accepting profile_inst because you're not passing the instance to the form when the request is POST request, instead you're passing object of request.POST which contains a key 'username | admin' hence django ORM cannot match the above key to your post model field 'author'

Try creating object to pass to your form like this :

form_obj = {
   author : profile_inst, 
   ... other necessary form fields
}

form = CreatePost(form_obj, request.FILES)

... other code 

Or change the name of input field from 'username | admin' to 'author' but you will need to check if the author exists and get its instance in createpost form.