Thursday, May 30, 2019

Accessing request from form

Does anyone know a philosophical reason (or I suppose a technical one, although I don't think that's the case) why the request is not made available by default in ModelForms when using CBV's? 

Almost all of the models I use have "audit" fields (created_by, updated_by, etc.) that reference the current logged in user. A ModelForm has no access to the current request, and as such can't update these fields without a User object. I have other use cases as well, but this one is probably the most prevalent among other developers.

At any rate, I'm currently stuck having to create relatively empty ModelForm shell classes for the simple reason of including a form mixin that grabs the request before __init__() (because the ModelForm complains if I don't), and overrides save() to save the fields with the user object, in addition to specifying the form_class in the CBV along with a view mixin for sending the request over via get_form_kwargs(). It's quite a process, especially when dealing with multiple models. I could drop a significant amount of code if I could flag the CBV to include the request with the form initialization. Heck, there could even be some magic to have the form associate the user with specific fields on save from the view as form_kwargs.

Or am I making things hard on myself? Thanks.

-James

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CA%2Be%2BciVd5nZtMXNU2UUgvxCUXmmzKU4UAnkSRXzFffS3QBGbHg%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment