Django, adding excluded properties to the submitted modelform

前端 未结 4 2030
离开以前
离开以前 2021-02-05 22:50

I\'ve a modelform and I excluded two fields, the create_date and the created_by fields. Now I get the \"Not Null\" error when using the save()

4条回答
  •  北荒
    北荒 (楼主)
    2021-02-05 23:29

    One way to do this is by using form.save(commit=False) (doc)

    That will return an object instance of the model class without committing it to the database.

    So, your processing might look something like this:

    form = some_form(request.POST)
    location = form.save(commit=False)
    user = User(pk=1)
    location.created_by = user
    location.create_date = datetime.now()
    location.save()
    

提交回复
热议问题