@Lepilov

В чем ошибка валидации формы CreateView?

Сделал форму с формсетами , которая всегда отдает invalid. Форма содержит два формсета и сабмитится одной кнопкой.

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

    def get_context_data(self, **kwargs):
        context = super(SkillTestCreateView, self).get_context_data(**kwargs)
        context['formset_framework'] = SkillFrameworkFormSet()
        context['formset_planguage'] = SkillPLanguageFormSet()

        return context

    def post(self, request, *args, **kwargs):

        self.object = None
        formset_framework = SkillFrameworkFormSet(self.request.POST)
        formset_planguage = SkillPLanguageFormSet(self.request.POST)
        if formset_framework.is_valid() and formset_planguage.is_valid():
            return self.form_valid(formset_framework, formset_planguage)
        else:
            return self.form_invalid(formset_framework, formset_planguage)

    def form_valid(self, formset_framework, formset_planguage):
        formset_framework.save()
        formset_planguage.save()
        return HttpResponseRedirect('/')

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


template.html

<div class="container">
     <form method="post" action="">
          {% csrf_token %}
    <h3>Programming language</h3>
        <table class="table-responsive">
            <tr>
                {{ formset_planguage.management_form }}
            {% for form in formset_planguage %}
                <td>
                    <table>
                    {% for field in form.visible_fields %}
                        <tr><td >{{ field.label_tag }}</td></tr>
                    {% endfor %}
                    </table>
                </td>

                <td>
                    <table>
                    {% for field in form.visible_fields %}
                        <tr style="background: cyan; line-height:1; white-space:nowrap;" ><td  >{{ field }}</td></tr>
                    {% endfor %}
                    </table>
                </td>
            {% endfor %}
            </tr>
        </table>

    <h3>Frameworks</h3>
        <table class="table-responsive">
          <tr>
                {{ formset_framework.management_form }}
            {% for form in formset_framework %}
                <td>
                    <table>
                    {% for field in form.visible_fields %}
                        <tr><td>{{ field.label_tag }}</td></tr>
                    {% endfor %}
                    </table>
                </td>
                <td>
                    <table>
                    {% for field in form.visible_fields %}
                        <tr><td style="background: cyan; line-height:1; white-space:nowrap;"  >{{ field }}</td></tr>
                    {% endfor %}
                    </table>
                </td>
            {% endfor %}
          </tr>

        </table>
          <input type="submit" value="Submit"/>
          </form>
</div>


forms.py
class SkillBaseCreateForm(forms.ModelForm):
    YEAR_CHOICES = [(r, r) for r in range(1, 11)]
    LAST_YEAR_CHOICES = [(r, r) for r in range(1980, datetime.datetime.now().year + 1)]
    year = forms.CharField(
        widget=forms.Select(choices=YEAR_CHOICES),
    )
    last_year = forms.CharField(widget=forms.Select(choices=LAST_YEAR_CHOICES))

    class Meta:

        model = Skill
        fields = ['technology', 'level', 'last_year', 'year']


class SkillCreatePLanguageForm(SkillBaseCreateForm):
    def __init__(self, *args, **kwargs):
        super(SkillCreatePLanguageForm, self).__init__(*args,**kwargs)
        self.fields['technology'].queryset = Technology.objects.filter(group_id='3')


class SkillCreateFrameworkForm(SkillBaseCreateForm):
    def __init__(self, *args, **kwargs):
        super(SkillCreateFrameworkForm, self).__init__(*args,**kwargs)
        self.fields['technology'].queryset = Technology.objects.filter(group_id='2')


После отправки никаких ошибок, редирект обратно к форме. В чем может быть причина?
  • Вопрос задан
  • 39 просмотров
Пригласить эксперта
Ответы на вопрос 1
alternativshik
@alternativshik
Достаточно в form_invalid сделать print формы и все встанет на свои места...
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы