Please, this is a matter of consideration. Maybe someone will use one of the below.
I have a couple of models that contain a box ForeignKey(User). My class-based views are based on common ones CreateView.
There are two options for saving the associated user when adding a new object:
Saving a form in views by overriding a method form_valid; this does not disclose user_id(and other data not mentioned here that should not be displayed)
class CreateOfferView(CreateView):
model = Offer
form_class = SomeModelFormWithUserFieldExcluded
def form_valid(self, form):
instance = form.save(commit=False)
instance.user = self.request.user
instance.save()
, ( ) .
. ...
( ) , . OwnFormMixin
class OwnFormMixin(object):
def get_form(self, form_class):
form = super(OwnFormMixin, self).get_form(form_class)
form.fields['user'].widget = forms.HiddenInput()
def get_initial(self):
initial = super(OwnFormMixin, self).get_initial()
initial['user'] = self.request.user.pk
class CreateOfferView(OwnFormMixin, CreateView):
model = Offer
form_class = SomeModelFormWithAllFields
CreateXXXView OwnFormMixin..
?
? ?