N
N
NikClik2018-08-18 01:15:45
Django
NikClik, 2018-08-18 01:15:45

Doesn't save the second instance of the child model, what's the problem?

Models

class GroupTasks(models.Model):
    TASK_STATUS = {
        ('В процессе выполенения', 'В процессе выполенения'),
        ('В ожидании выполнения', 'В ожидании выполнения'),
        ('Выполнение закончено', 'Выполнение закончено'),
    }
    owner = models.CharField(blank=True, verbose_name="Владелец", max_length=1000000, editable=False)
    header = models.CharField(blank=False, verbose_name="Заголовок задачи", max_length=1000000)
    dateOfCreate = models.DateTimeField(blank=True, auto_now_add=True)
    dateOfStart = models.DateTimeField(blank=False, verbose_name="Дата, время начала задачи")
    dateOfEnd = models.DateTimeField(blank=True, verbose_name="Дата, время окончания задачи")
    progress = models.IntegerField(default=0, verbose_name="Прогресс")
    status = models.CharField(choices=TASK_STATUS, verbose_name="Статус", max_length=1000000, default="В ожидании выполнения")

    def __str__(self):
        return "Групповая задача %s" % (self.header, )

    class Meta:
        verbose_name = 'Групповые задачи'
        verbose_name_plural = 'Групповые задачи'

    def class_name(self):
        return self.__class__.__name__

class UnderTask(models.Model):
    TASK_STATUS = {
        ('В процессе выполенеия', 'В процессе выполенеия'),
        ('В ожидании выполнения', 'В ожидании выполнения'),
        ('Выполнение закончено', 'Выполнение закончено'),
    }
    headerTask = models.ForeignKey(GroupTasks, on_delete=models.CASCADE, editable=False)
    creator = models.CharField(max_length=1000000, verbose_name="Создатель", blank=True, editable=False)
    excerpt = models.CharField(max_length=1000000, verbose_name="Выполняющий")
    actions = models.TextField(blank=False, max_length=1000000, verbose_name="Выполняемые работы")
    dateOfCreate = models.DateTimeField(blank=True, auto_now_add=True)
    dateOfStart = models.DateTimeField(blank=False, verbose_name="Дата, время начала задачи")
    dateOfEnd = models.DateTimeField(blank=True, verbose_name="Дата, время окончания задачи")
    step = models.IntegerField(blank=False, default=0, verbose_name="Шаг")
    status = models.CharField(choices=TASK_STATUS, default="В ожидании выполнения", max_length=1000000, verbose_name="Статус выполнения")

    def __str__(self):
        return "Подзадача %s" % (self.excerpt,)

    class Meta:
        verbose_name = 'Подзадачи'
        verbose_name_plural = 'Подзадачи'

    def class_name(self):
        return self.__class__.__name__

forms.py
class UnderTasksForm(ModelForm):
    excerpt = forms.ModelChoiceField(queryset=User.objects.all(), required=True, label='Выполняющий', initial=UnderTask.excerpt)

    class Meta:
        model = UnderTask
        exclude = ()


UnderTaskFormSet = inlineformset_factory(GroupTasks, UnderTask, form=UnderTasksForm, extra=1)


class GroupTasksForm(forms.ModelForm):
    progress = forms.IntegerField(disabled=True)


    class Meta:
        model = GroupTasks
        exclude = ["id"]

views.py
class GroupTaskList(ListView):
    model = GroupTasks


class GroupTaskCreate(CreateView):
    model = GroupTasks
    fields = ['header',  'dateOfStart', 'dateOfEnd', 'progress', 'status']


class UnderTasksCreate(CreateView):
    model = GroupTasks
    fields = ['header',  'dateOfStart', 'dateOfEnd', 'progress', 'status']
    success_url = 'MainPage'

    def get_context_data(self, **kwargs):
        data = super(UnderTasksCreate, self).get_context_data(**kwargs)
        if self.request.POST:
            data['undertasks'] = UnderTaskFormSet(self.request.POST, instance=self.object)
            data['undertasks'].full_clean()
        else:
            data['undertasks'] = UnderTaskFormSet(instance=self.object)
        return data

    def form_valid(self, form):
        context = self.get_context_data()
        undertasks = context['undertasks']
        with transaction.atomic():
            self.object = form.save()
            if undertasks.is_valid():
                undertasks.instance = self.object
                undertasks.save()
        return super(UnderTasksCreate, self).form_valid(form)

template.html
<body>
    <div class="col-md-4">
    <form action="" method="post">{% csrf_token %}
        {{ form.as_p }}
        <table class="table">
            {{ undertasks.management_form }}

            {% for form in undertasks.forms %}
                {% if forloop.first %}
                    <thead>
                    <tr>
                        {% for field in form.visible_fields %}
                            <th>{{ field.label|capfirst }}</th>
                        {% endfor %}
                    </tr>
                    </thead>
                {% endif %}
                <tr class="{% cycle row1 row2 %} formset_row">
                    {% for field in form.visible_fields %}
                        <td>
                            {% if forloop.first %}
                                {% for hidden in form.hidden_fields %}
                                    {{ hidden }}
                                {% endfor %}
                            {% endif %}
                            {{ field.errors.as_ul }}
                            {{ field }}
                        </td>
                    {% endfor %}
                </tr>
            {% endfor %}
        </table>
        <input type="submit" value="Save"/> <a href="">back to the list</a>
    </form>
</div>
<script src="{% static 'jquery.min.js' %}"></script>
<script src="{% static 'jquery.formset.js' %}"></script>
<script type="text/javascript">
    $('.formset_row').formset({
        addText: 'Добавить подзадачу',
        deleteText: 'Удалить',
        prefix: 'undertasks_set'
    });
</script>
</body>

The problem is that only one instance of UnderTask is added, and the second one is not, I can't figure out where the error is

Answer the question

In order to leave comments, you need to log in

4 answer(s)
S
Sergey Tikhonov, 2018-08-20
@NikClik

inlineformset_factory is called with extra=1, so the formset thinks that exactly one record has been passed. When adding multiple rows, you need to increment the counter from the management form.

F
FanatPHP, 2015-02-05
@skver91

Nothing works! What to do??? - here are the answers to all your questions

A
Alexey, 2015-02-06
@gentee

And why do you have the Content -Type output after the image output?
Should be like this

header(  'Content-Type: image/jpeg' );
imagejpeg( $image_p, NULL, 100 );

I
Ilya Korablev, 2015-02-05
@swipeshot

I did not quite understand the essence of the question. Where should it be taken out?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question