Django.fun

Django set formset with current user

Django 3.2.7

I have a form that contains multiple inlineformset_factory formset.

For all my models, they all have a meta field call created_by.

Only the main form Person's created_by is filled by current user. For all the formsets (emailfs, imagefs), it did not set their created_by with current user. How can I do that?

Here is my views and my 7 different failed approaches.

# views.py
class PersonCreateView(LoginRequiredMixin, SuccessMessageMixin, CreateView):
    ...
    model = Person
    form_class = PersonForm

    def get_context_data(self, **kwargs):
        context = super(PersonCreateView, self).get_context_data(**kwargs)
        if self.request.POST:
            context["emailfs"] = PersonEmailFormSet(
                self.request.POST, self.request.FILES
            )
            context["imagefs"] = PersonImageFormSet(
                self.request.POST, self.request.FILES
            )
            # Method 6
            # context["imagefs"] = PersonImageFormSet(
            #     self.request.POST, self.request.FILES, user=self.request.user
            # )
            # Method 7
            # context["imagefs"] = PersonImageFormSet(
            #     self.request.POST, self.request.FILES, form_kwarg={'created_by': self.request.user}
            # )
        else:
            context["emailfs"] = PersonEmailFormSet()
            context["imagefs"] = PersonImageFormSet()
        return context


    def form_valid(self, form):
        form.instance.created_by = self.request.user
        context = self.get_context_data()
        emailfs = context["emailfs"]
        imagefs = context["imagefs"]
        personfs = [emailfs, imagefs]
        if (
            form.is_valid()
            and all(fs.is_valid() for fs in personfs)
        ):
            self.object = form.save()
            for fs in personfs:
                # Method 1
                # fs.created_by = self.request.user
                # Method 2
                # self.created_by = self.request.user
                fs.instance = self.object
                # Method 3
                # fs.created_by = self.request.user
                # Method 4
                # fs.instance.created_by = self.request.user
                # Method 5
                # for f in fs.forms:
                #     f.user = self.request.user
                #     f.save()
                fs.save()
        else:
            return self.form_invalid(form)
        return super(PersonCreateView, self).form_valid(form)
# forms.py for imagefs
# for method 6,7 in views.py
class PersonImageForm(forms.ModelForm):
    ...

    def __init__(self, *args, created_by **kwargs):
        self.created_by = created_by
        super().__init__(*args, **kwargs)

Answers: 0