Django, adding excluded properties to the submitted modelform

前端 未结 4 2076
离开以前
离开以前 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:08

    The correct solution is to pass an instance of the object with pre-filled fields to the model form's constructor. That way the fields will be populated at validation time. Assigning values after form.save() may result in validation errors if fields are required.

    LocationForm(request.POST or None, instance=Location(
        created_by=request.user,
        create_date=datetime.now(),
    ))
    

    Notice that instance is an unsaved object, so the id will not be assigned until form saves it.

提交回复
热议问题