Thursday, May 30, 2019

Re: Accessing request from form

I always dread being the guy that responds to his own thread with "Hey guys, I fixed it."

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.

For the use case above, I had an epiphany did some more experimenting and figured out how to update the audit fields without needing to mangle a Form/ModelForm, entirely from the CBV:

     def form_valid(self, form):
        form.instance.updated_by = self.request.user
        return super().form_valid(form)

Fully compatible with an implicit ModelForm, and only 3 lines of code!

This is an easy drop in a view mixin, which I already have for other overrides anyway. However, this feels really gross, and I feel like I'm violating some prime directive by attaching data to an instance that was not validated by the form. I think I can forgive myself since the data I'm attaching is coming from Django and not some other source, and I have to assume Django handles these things properly.

Of course while writing this message, I then stumbled on this exact solution buried in the Django docs:


So, feel free to ignore me. I will grant myself a point for coming up with the same solution already blessed by the Django devs. I'm also deducting a point from myself for not RTFM properly, so I break even.

-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%2BciVKk6V6gpwF5FW8%3D-1ib%3D-xj6UX4-cceL3Fco12BpkfUg%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment