I am trying to use Django Extra Views pack to create new entry based on model + inline formset + extra information from the USER model. I know how to do it via function based views but now trying to decrease amount of the code:
I have 2 models + user model:
Model1: # primary model
author = models.ForeignKey("ExtraUser", )
+some fileds
Model2 # secondary model
photo = models.ForeignKey("Model1", )
+ some fields
# user model
Model ExtraUser(AbstractBaseUser)
+ some fileds
I use following VIEW to render and save it all together:
class ItemInline(InlineFormSetFactory):
model = Model2
fields = ["somefiled"]
class CreateBoatView(SuccessMessageMixin, LoginRequiredMixin, CreateWithInlinesView):
model = Model1
inlines = [ItemInline]
fields = ["list of the fields here"]
template_name = 'create.html'
def get_success_url(self):
return reverse('app:url', args=(self.object.pk, ))
It all work except 1 thing: I cant appoint current user as an entry author, that is author = models.ForeignKey("ExtraUser", ) is always NULL
in ancestor function based view I used to do following:
if form1.is_valid():
prim = form1.save(commit=False)
prim.author = request.user # that is I connect this entry to the current user.
# + do something + save(commit=True) finally.
How to do same stuff in CreateWithInlinesView?
tried following. Doenst work
def dispatch(self, request, *args, **kwargs):
self.user = request.user
return CreateWithInlinesView.dispatch(self, request, *args, **kwargs)
def form_valid(self, form): #(self, form, inlines)??
self.object = form.save(commit=False)
self.object.author = self.request.user
self.object.save()
return HttpResponseRedirect(self.get_success_url())
# super-class form_valid method (for reference)
def forms_valid(self, form, inlines):
"""
If the form and formsets are valid, save the associated models.
"""
self.object = form.save()
for formset in inlines:
formset.save()
return HttpResponseRedirect(self.get_success_url())