Данные ManagementForm отсутствуют или были подделаны при использовании вложенных Django Formsets - PullRequest
0 голосов
/ 06 марта 2020

Я пытался использовать django форм вложенным способом. Я успешно создал формы .py и models.py для этой цели, но я изо всех сил пытался реализовать его сценарий html java. Теперь при сохранении формы я получаю сообщение об ошибке

Данные ManagementForm отсутствуют или были изменены с помощью

Я не могу определить, является ли это ошибкой views.py или Мой HTML / java скрипт. Я начинающий в django.

models.py

from django.db import models

# Create your models here.
from django.contrib.contenttypes.models import ContentType
# Create your models here.

class courses(models.Model):
    name  = models.CharField(max_length = 50)

    enter code here

class topics(models.Model):
    name  = models.CharField(max_length = 50)
    course = models.ForeignKey(courses,on_delete = models.CASCADE,null = True)

class sub_topics(models.Model):
    name  = models.CharField(max_length = 50)
    topic = models.ForeignKey(topics,on_delete = models.CASCADE,null = True)

class course_to_topics(models.Model):
    serial_no = models.IntegerField()
    course =  models.ForeignKey(courses ,related_name="course",
                                        on_delete = models.CASCADE,null = True)
    topic =  models.ForeignKey(topics ,related_name="topics",
                                        on_delete = models.CASCADE,null = True)

class topics_to_subtopics(models.Model):
        serial_no = models.IntegerField()
        topic =  models.ForeignKey(topics ,related_name="topic",
                                            on_delete = models.CASCADE,null = True)
        subtopic =  models.ForeignKey(sub_topics ,related_name="subtopics",
                                            on_delete = models.CASCADE,null = True)

forms.py

from django.forms import ModelForm
from django.forms import formset_factory, inlineformset_factory,modelformset_factory
from .models import courses, topics, sub_topics, course_to_topics, topics_to_subtopics

class CourseForm(ModelForm):
    class Meta:
        model = courses
        fields = ['name',]
        exclude = ()
    # name = forms.CharField(
    #     label='Course Name',
    #     widget=forms.TextInput(attrs={

    #         'class': 'form-control',
    #         'placeholder': 'Enter Course here'
    #     })
    # )


class TopicForm(ModelForm):
    class Meta:
        model = topics
        fields = ['name',]
        exclude = ('course',)


class Sub_TopicForm(ModelForm):
    class Meta:
        model = sub_topics
        fields = ['name',]
        exclude = ('topic',)

# courseform = modelformset_factory(courses,form = CourseForm,min_num = 1)
# topicform = modelformset_factory(topics,form = TopicForm,min_num = 1)
# sub_topicsform = modelformset_factory(sub_topics,form = Sub_TopicForm,min_num = 1)

TopicFormset = inlineformset_factory(courses, topics, fields=('name',),extra =1)
Sub_TopicFormset = inlineformset_factory(topics, sub_topics, fields=('name',),extra = 1)

views.py

from .forms import CourseForm,TopicFormset,Sub_TopicFormset
from .models import courses,topics,sub_topics
from django.shortcuts import render
from django.views.generic import CreateView
from django.http import HttpResponse

class Create_Course_View(CreateView):
    model = courses
    form_class = CourseForm
    template_name = 'create/add.html'
    success_url = 'create/save.html'

    def form_valid(self, form):
        result = super(Create_Course_View, self).form_valid(form)

        #authors_formset = AuthorInlineFormSet(form.data, instance=self.object, prefix='authors_formset')
        topic_formset = TopicFormset(form.data, instance=self.object, prefix='topic_formset')

        # if authors_formset.is_valid():
        #     authors = authors_formset.save()
        if topic_formset.is_valid():
            topics = topic_formset.save()

        #authors_count = 0
        topics_count = 0

        # for author in authors:
        #     books_formset = BookInlineFormSet(form.data, instance=author, prefix='books_formset_%s' % authors_count)
        #     if books_formset.is_valid():
        #         books_formset.save()
        #     authors_count += 1
        print(topics)
        for topic in topics:
            sub_topic_formset = Sub_TopicFormset(form.data, instance = topic, prefix='sub_topic_formset_%s topics_count')
            if sub_topic_formset.is_valid():
                sub_topic_formset.save()
            topics_count += 1

        return result

    def get_context_data(self, **kwargs):
        context = super(Create_Course_View, self).get_context_data(**kwargs)
        context['topic_formset'] = TopicFormset(prefix='topic_formset')
        context['sub_topic_formset'] = Sub_TopicFormset(prefix='sub_topic_formset_')
        return context

Html файл

{% load static %}

<script src="{% static 'jquery.js' %}"></script>
<script type="text/javascript">
    $(function () {
        $('form').delegate('.btn_add_sub_topic', 'click', function () {
            var $this = $(this)
            var author_ptr = $this.attr('id').split('-')[1]
            var $total_topic_sub_topics = $(':input[name=sub_topic_formset_' + author_ptr + '-TOTAL_FORMS]');
            var topic_sub_topic_form_count = parseInt($total_topic_sub_topics.val())
            $total_topic_sub_topics.val(topic_sub_topic_form_count + 1)

            var $new_book_form = $('<fieldset class="topic_sub_topic_form">' +
                '<legend>Sub Topic</legend>' +
                '<p>' +
                '<label for="id_sub_topic_formset_' + author_ptr + '-' + topic_sub_topic_form_count + '-name">Name:</label>' +
                '<input id="id_sub_topic_formset_' + author_ptr + '-' + topic_sub_topic_form_count + '-name" maxlength="256" name="sub_topic_formset_' + author_ptr + '-' + topic_sub_topic_form_count + '-name" type="text" />' +
                '<input id="id_sub_topic_formset_' + author_ptr + '-' + topic_sub_topic_form_count + '-author" name="sub_topic_formset_' + author_ptr + '-' + topic_sub_topic_form_count + '-author" type="hidden" />' +
                '<input id="id_sub_topic_formset_' + author_ptr + '-' + topic_sub_topic_form_count + '-id" name="sub_topic_formset_' + author_ptr + '-' + topic_sub_topic_form_count + '-id" type="hidden" />' +
                '</p>' +
                '</fieldset>'
            )

            $this.parents('.author_form').find('.topic_sub_topics').prepend($new_book_form)
        })

        $('form').delegate('#btn_add_topic', 'click', function () {
            var $total_authors = $(':input[name=topic_formset-TOTAL_FORMS]');
            author_form_count = parseInt($total_authors.val())
            $total_authors.val(author_form_count + 1)

            book_form = '<fieldset class="topic_sub_topic_form">' +
                '<legend>Sub Topic</legend>' +
                '<p>' +
                '<label for="id_sub_topic_formset_' + author_form_count + '-0-name">Name:</label>' +
                '<input id="id_sub_topic_formset_' + author_form_count + '-0-name" maxlength="256" name="sub_topic_formset_' + author_form_count + '-0-name" type="text" />' +
                '<input id="id_sub_topic_formset_' + author_form_count + '-0-author" name="sub_topic_formset_' + author_form_count + '-0-author" type="hidden" />' +
                '<input id="id_sub_topic_formset_' + author_form_count + '-0-id" name="sub_topic_formset_' + author_form_count + '-0-id" type="hidden" />' +
                '</p>' +
                '</fieldset>';

            $new_author_form = $(
                '<fieldset class="author_form">' +
                '<legend>Topic</legend>' +
                '<legend>Topic</legend>' +
                '<p>' +
                '<label for="id_topic_formset-' + author_form_count + '-name">Name:</label>' +
                '<input id="id_topic_formset-' + author_form_count + '-name" maxlength="256" name="topic_formset-' + author_form_count + '-name" type="text" />' +
                '<input id="id_topic_formset-' + author_form_count + '-publisher" name="topic_formset-' + author_form_count + '-publisher" type="hidden" />' +
                '<input id="id_topic_formset-' + author_form_count + '-id" name="topic_formset-' + author_form_count + '-id" type="hidden" />' +
                '</p>' +
                '<p><input type="button" value="Add Sub Topic" class="btn_add_sub_topic" id="author-' + author_form_count + '"/></p>' +
                '<div class="topic_sub_topics">' +
                '<input id="id_sub_topic_formset_' + author_form_count + '-TOTAL_FORMS" name="sub_topic_formset_' + author_form_count + '-TOTAL_FORMS" type="hidden" value="1" />' +
                '<input id="id_sub_topic_formset_' + author_form_count + '-INITIAL_FORMS" name="sub_topic_formset_' + author_form_count + '-INITIAL_FORMS" type="hidden" value="0" />' +
                '<input id="id_sub_topic_formset_' + author_form_count + '-MAX_NUM_FORMS" name="sub_topic_formset_' + author_form_count + '-MAX_NUM_FORMS" type="hidden" value="1000" />' +
                book_form +
                '</div >' +
                '</fieldset >'
            )

            $('#authors').prepend($new_author_form)
        })
    })
</script>

<h1>Add Course</h1>
<form action="" method="post">
    {% csrf_token %}
    {{ form.as_p }}

    <p><input type="button" id="btn_add_topic" value="Add another topic"/></p>

    <div id="authors">
        {{ topic_formset.management_form }}
        {% for form in topic_formset %}
            <fieldset class="author_form">
                <legend>Topic</legend>
                {{ form.as_p }}
                <p><input type="button" value="Add Sub Topic" class="btn_add_sub_topic" id="author-{{ forloop.counter0 }}"/></p>

                <div class="topic_sub_topics">
                    {{ sub_topic_formset.management_form }}

                    {% for form in sub_topic_formset %}
                        <fieldset class="topic_sub_topic_form">
                            <legend>Sub Topic</legend>
                            {{ form.as_p }}
                        </fieldset>
                    {% endfor %}
                </div>
            </fieldset>
        {% endfor %}
    </div>
    <p><input type="submit" value="Save"></p>
</form>
...