search

Home  >  Q&A  >  body text

python - 为什么无法获取Django模型主键的值?

PHPzPHPz2911 days ago474

reply all(3)I'll reply

  • PHPz

    PHPz2017-04-18 10:10:40

    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

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-04-18 10:10:40

    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

    reply
    0
  • PHPz

    PHPz2017-04-18 10:10:40

    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)是错误的使用方法,ModelFormsave方法只有一个参数,就是commit = False 或者 commit=True indicates whether to save the data to the database, and the default is True.

    See link for source code

    reply
    0
  • Cancelreply