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
Answers
commit=False
.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.
If you want to show the user name/info in post creation form, use
{{ request.user.profile }}
.
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 :
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.