J
J
Jekson2019-07-29 10:52:55
Django
Jekson, 2019-07-29 10:52:55

Why does Modelformset return None if not all forms are filled out?

There is a view using modelformset. If all visible forms are filled, then everything works as it should. If at least one of the forms is empty, then I get an error

The view base.views.SkillTestCreateView didn't return an HttpResponse object. It returned None instead.

views.py
class SkillTestCreateView(AuthorizedMixin, CreateView):
    model = Skill
    form_class = SkillCreateForm
    template_name = 'skill_create.html'

    def get_context_data(self, **kwargs):
        context = super(SkillTestCreateView, self).get_context_data(**kwargs)
        employee_current_technology = Technology.objects.filter(skill__employee__id=self.kwargs['pk'])
        context['formset_framework'] = SkillFrameworkFormSet()
        context['formset_planguage'] = SkillPLanguageFormSet()
        context['tech_group'] = Techgroup.objects.all()
        return context

    def post(self, request, *args, **kwargs):
        if 'framework' in request.POST:
            form = SkillFrameworkFormSet(self.request.POST)
            if form.is_valid():
                return self.form_valid(form)
        elif 'language' in request.POST:
            form = SkillPLanguageFormSet(self.request.POST)
            if form.is_valid():
                return self.form_valid(form)
        else:
            return self.form_invalid(self.form)

    def form_valid(self, form):
        """If the form is valid, redirect to the supplied URL."""
        for form in form:
            self.object = form.save(commit=False)
            self.object.employee =Employee.objects.get(pk=self.kwargs['pk'])
            self.object.save()

        return redirect("profile", pk=self.kwargs['pk'])

    def form_invalid(self, formset_framework, formset_planguage):
        return self.render_to_response(self.get_context_data(formset_framework=self.formset_framework,
                                                             formset_planguage=self.formset_planguage))

How can I change the code to be able to submit empty forms?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Y
Yura Khlyan, 2019-07-29
@Lepilov

Your POST conditions do not cover all options. For example:
framework in request.POST, but the form is not valid. Another example: language in request.POST, but the form is not valid. In these cases, the post will return nothing.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question