You need to see clearly that your post object is PostForm() not Post(). Your PostForm form processing object has an initial value of id, but does the request.POST value you pass have an id value? If not, it will naturally be None. Yes, if your post is a Post() object, then it must have an id value
There is one piece of information that is not given in detail, which is PostFormhow you define it.
If you define it like thisPostForm,通过调用PostForm(request.POST).save(), you can get the result you want by calling PostForm(request.POST).save().
class PostForm(forms.ModelForm):
class Meta:
model = Post
But your PostForm is definitely not defined this way, because post = form.save(request.user)是错误的使用方法,ModelForm的save方法只有一个参数,就是commit = False 或者 commit=True indicates whether to save the data to the database, and the default is True.
Django does not need to "explicitly define primary keys"
It will automatically add an id field (primary key, auto-increment) to the table
You can consider removing the primary key you defined manually
You need to see clearly that your post object is PostForm() not Post(). Your PostForm form processing object has an initial value of id, but does the request.POST value you pass have an id value? If not, it will naturally be None. Yes, if your post is a Post() object, then it must have an id value
There is one piece of information that is not given in detail, which is
PostForm
how you define it.If you define it like this
PostForm
,通过调用PostForm(request.POST).save()
, you can get the result you want by callingPostForm(request.POST).save()
.But your PostForm is definitely not defined this way, because
post = form.save(request.user)
是错误的使用方法,ModelForm
的save
方法只有一个参数,就是commit = False
或者commit=True
indicates whether to save the data to the database, and the default is True.See link for source code