I know the following function can be used to do some pre-save processing. But, how can I access the request data, for example a text field value from the request for doing validation?
def save_model(self, request, obj, form, change):
# do something for validation
obj.save()
The raw request data is stored in
request.POST, as it usually is. It’s probably better to accessform.cleaned_data, as Django has already validated it.However, the
save_modelmethod probably isn’t the correct place to do validation. If you raise aValidationError, then the exception will not be caught and the user will get a 500 server error page. Thesave_modelmethod is more appropriate when you know the data is already valid, for example to set the object’s author based onrequest.userbefore saving.If you want to do custom validation, a better approach would be to define a model form, and use it in your model admin with the
ModelAdmin.formsetting.