Django bulk_create CreateView

时间:2018-05-30 01:57:49

标签: python django django-models create-view

我有models.py

class Schedule(models.Model):
    name = models.CharField(max_length=255)
    date_from = models.DateField('')
    date_to = models.DateField('', null=True)
    desc = models.TextField(blank=True, null=True)

这是我的views.py

class Schedule(CreateView):
    fields = ()
    model = models.Schedule

    def form_valid(self, form):
        self.object = form.save(commit=False)
        self.object.save()
        return super(ModelFormMixin, self).form_valid(form)

和我的template.html

{{form.as_p}}

这种形式只能做一次输入。但是我需要以单一形式执行3次输入,其名称和名称不同。约会(在我的情况下)。

和形式可能看起来像

{{form.as_p}}    
{{form.as_p}}
{{form.as_p}}

我查看文档theres bulk_create可以在单次运行中做多个输入,但我不知道如何处理我的template.html

1 个答案:

答案 0 :(得分:1)

为您演示:

views.py

from datetime import date
from django.db import models


class Schedule(models.Model):
    name = models.CharField(max_length=255)
    date_from = models.DateField("date from", default=date.today)
    date_to = models.DateField("date to", default=date.today)
    desc = models.TextField(blank=True, null=True)

    def __str__(self):
        return self.name or self.__class__.__name__

models.py

<form method='post'>{% csrf_token %}
        {% for form in forms %}
                {{ form.Meta.model }} {{ forloop.counter }}<br>
                {{ form.as_p }}
                -------------------------------------------<br>
        {% endfor %}
<input type='submit', value='OK'>
</form>

模板

reshape