Я пытаюсь показать несколько форм, предварительно заполненных данными из экземпляров модели. Тогда я бы хотел использовать Django "prefix" kwarg для Forms. Однако, как только я использую этот аргумент «prefix» в форме и отправляю данные для отображения с ним, он возвращается пустым, без ошибок формы.
Ниже я написал очень простой пример с двумя формами: первый имеет нет префикса и работает правильно, 2-й имеет префикс и не работает.
Я хотел бы помочь! Большое спасибо!
models.py
class Production_Plan_Data(models.Model):
production_plan = models.ForeignKey(
Production_Plan,
on_delete=models.CASCADE,
related_name="production_plan_data",
verbose_name="production plan data"
)
week_number = models.PositiveSmallIntegerField(verbose_name="Week Number")
product = models.ForeignKey(
Product,
on_delete=models.PROTECT,
related_name="production_plan_product",
verbose_name="production plan product"
)
value = models.PositiveIntegerField(verbose_name="Week Value")
creation_date = models.DateTimeField(auto_now_add=True)
update_date = models.DateTimeField(auto_now=True)
class Meta:
verbose_name = "Production Plan Data"
ordering = ["production_plan", "product", "week_number"]
def __str__(self):
return self.production_plan
forms.py
class Production_Plan_Data_Form(forms.ModelForm):
class Meta:
model = Production_Plan_Data
fields = ["product", "week_number", "value"]
view.py
class Tests_View(TemplateView):
template_name = "load_mgmt/tests.html"
def get(self, request, **kwargs):
current_item = Production_Plan_Data.objects.get(pk=105)
current_item_data = {
'product': current_item.product,
'week_number': current_item.week_number,
'value': current_item.value
}
form_prefix = "form" + str(current_item.pk)
form1 = Production_Plan_Data_Form(instance=current_item)
# form1 = Production_Plan_Data_Form(current_item_data, prefix="tt")
current_item2 = Production_Plan_Data.objects.get(pk=106)
current_item_data2 = {
'product': current_item2.product,
'week_number': current_item2.week_number,
'value': current_item2.value
}
form2 = Production_Plan_Data_Form(current_item_data2, prefix="f2")
print(form2.errors)
forms = {
"form1": form1,
"form2": form2
}
return render(request, self.template_name, {'forms': forms})
тестовый файл шаблона. html
{% extends "base.html" %}
{% load static %}
{% block page_title %}<h2>Tests</h2>{% endblock %}
{% block content %}
<form action="" method="post">
{% csrf_token %}
{% for key, form in forms.items %}
{{ form.as_p }}
<br>
<br>
{% endfor %}
<input type="submit" value="Save" id="production_plan_data_submit_button" />
</form>
{% endblock %}
Результат в браузере:
<form action="" method="post">
<input type="hidden" name="csrfmiddlewaretoken" value="LdbVktYCHdWkNX6OkIPtVSMNgu1zEMf5wLYMnXpMXC6LX4wYsBpBl9Mp5MmOv5WH">
<p><label for="id_product">Production plan product :</label> <select name="product" required="" id="id_product">
<option value="">---------</option>
<option value="5" selected="">Truc</option>
<option value="6">Machin</option>
</select></p>
<p><label for="id_week_number">Week Number :</label> <input type="number" name="week_number" value="1" min="0" required="" id="id_week_number"></p>
<p><label for="id_value">Week Value :</label> <input type="number" name="value" value="6" min="0" required="" id="id_value"></p>
<br>
<br>
<ul class="errorlist"><li>Ce champ est obligatoire.</li></ul>
<p><label for="id_f2-product">Production plan product :</label> <select name="f2-product" required="" id="id_f2-product">
<option value="" selected="">---------</option>
<option value="5">Truc</option>
<option value="6">Machin</option>
</select></p>
<ul class="errorlist"><li>Ce champ est obligatoire.</li></ul>
<p><label for="id_f2-week_number">Week Number :</label> <input type="number" name="f2-week_number" min="0" required="" id="id_f2-week_number"></p>
<ul class="errorlist"><li>Ce champ est obligatoire.</li></ul>
<p><label for="id_f2-value">Week Value :</label> <input type="number" name="f2-value" min="0" required="" id="id_f2-value"></p>
<br>
<br>
<input type="submit" value="Save" id="production_plan_data_submit_button">
</form>