为什么不批量创建模型?

问题描述 投票:0回答:1

我正在尝试批量创建对象空白,但是仅在填写表格后才创建一个对象,有人可以帮我解决我做错的事情吗?

html

{% block content %}
    <form class="box" method = "post">
        {% csrf_token %}
        <h1>Air Ticket Sales</h1>
        {{ form }}
        batch size:
        <input type="number" name="batch" value="{{ batch }}">
      <input type="submit" name="" value="Create Blank">

    </form>
{% endblock %}

型号

class blank(models.Model):
    #an integer field that automatically increments by itself as the object are created
    number = models.AutoField(primary_key=True)
    type = models.CharField(max_length=50, choices=type_choices, default='green')
    is_sold = models.BooleanField(default=False)
    is_refunded = models.BooleanField(default=False)
    date = models.DateField(auto_now_add=True)
    date.editable = True
    advisor = models.ForeignKey(
        User,
        models.SET_NULL,
        blank=True,
        null=True,
    )

视图

def create_blanks(request):
    if request.method == 'POST':
        #initializes the data from the form to the value form
        form = blank_form(data=request.POST)
        batch = request.POST.get("batch", "")
        if form.is_valid():
            for b in batch:
                form.save()
            return render(request, "create_blanks.html")
        else:
            return render(request, "create_blanks.html")
    else:
        form = blank_form
        return render(request, "create_blanks.html", {'form':form})
django forms post django-models size
1个回答
0
投票

是,您只是在您的帮助下找到了解决方案,我认为这不是最有效或最干净的解决方案,但是您可以使用

for b in range(int(batch)):
            form.save()
            form.instance = None
            form = blank_form(data=request.POST)
© www.soinside.com 2019 - 2024. All rights reserved.