Hello Everyone,
I have been using class-based views for sometime now, and I am running
into an issue while subclassing CreateView, and think that this type of
thing could be placed into Django somehow to make it easier to implement.
Most multi-user websites connect models to a user by some means, so the
posts they make or articles they add list them as the owner/poster of it.
Assigning the object to the user when using class-based views at the moment
is annoying to say the least:
def form_valid(self, form):
self.object = form.save(commit=False)
self.object.user = self.request.user
self.object.save()
return super(ModelFormMixin, self).form_valid(form)
This is what I currently do, and it looks messy and unorganized. I would
like a way to easily assign additional data to the self.object without
going through all this. You may notice that I am calling super() on
ModelFormMixin, when this is a CreateView, well the super() of CreateView
will attempt to re-create the self.object from a form.save(), and since I
already created the object here, with no easy way to just pass
self.object... Anyways, you get the idea.
Perhaps a new overridable method that allows us to do something with an
uncommitted object before it is saved. Here is a new form_valid I propose:
class ModelFormMixin(...):
def not_sure_of_naming(self):
pass
def form_valid(self, form):
self.object = form.save(commit=False)
self.not_sure_of_naming()
self.object.save()
return super(ModelFormMixin, self).form_valid(form)
This will allow us developers using class-based views to easily perform
tasks on a self.object before it is finally saved back into the database.
The above implementation is just an example of what I would love to see in
a future version of class-based views.
Best Regards,
Kevin Veroneau
Python Diary
http://www.pythondiary.com/
--
You received this message because you are subscribed to the Google Groups
"Django developers" group.
To view this discussion on the web visit
https://groups.google.com/d/msg/django-developers/-/qRIihOsXQDoJ.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/django-developers?hl=en.