1👍
Your template does not include the profile
field, which is mandatory, so your form is never valid. Because you’re creating a new form every time, you’re not seeing the error message – not that your template would display it anyway.
Specify in your form definition that you only want the body:
class PostForm(ModelForm):
class Meta:
model = Post
fields = ['body']
That will let the form validate. You will also have to set the profile
field explicitly:
if newpostform.is_valid():
newpost = newpostform.save(commit=False)
newpost.profile = request.user.get_profile()
newpost.save()
And your instance
argument to the form constructor is not doing what you think it is – that’s for passing in an existing instance of the model the form represents for editing.
I would rewrite the view thus:
@login_required
def post(request, username):
newpostform = PostForm(data=request.POST)
if newpostform.is_valid():
newpost = newpostform.save(commit=False)
newpost.profile = request.user.get_profile()
newpost.save()
newpostform = PostForm()
context = {'newpostform': newpostform,}
return render(request, 'twitterclone/newpost.html', context)
Here, I’m not reassigning the form to a new empty one unless the one that was just submitted was valid. That will allow the template to show error messages.
Source:stackexchange.com