Мне нужна помощь с набором встроенных форм в Django. Я использую фабрику встроенных форм для загрузки документов в модель документа, которая имеет ссылку внешнего ключа на таблицу отделов, следующим образом:
model.py:
class Department(models.Model):
DepId = models.AutoField(primary_key=True)
Name = models.CharField(max_length=100)
ShortName = models.CharField (max_length=25)
def __str__(self):
return (str(self.DepId) + " "+ self.ShortName+ " is created!")
class Meta:
db_table = 'Department' # Table Name
managed = True
verbose_name = 'Departments' # Verbose Name of Table.
class Document(models.Model):
CATEGORY = (('Type1', 'Report Type 1'),
('Type2', 'Report Type 2'),)
Id = models.AutoField(primary_key=True)
Name = models.CharField(max_length=300)
DocType = models.CharField(max_length=300, choices=CATEGORY)
DocContent = models.FileField(upload_to='reports/')
DepId = models.ForeignKey(Department, on_delete=models.CASCADE, db_column="DepId")
UploadedDate = models.DateField(default=timezone.now, null=True)
def __str__(self):
return (str(self.Name))
class Meta:
db_table = 'Document'
managed = True
verbose_name = 'Document'
def delete(self, *args, **kwargs):
self.DocContent.delete()
super().delete(*args, **kwargs)
view.py
def doc_loading_view(request, pk, *args, **kwargs):
DocumentFormSet = inlineformset_factory(Location,
Document,
fields=('Name', 'DocContent', 'DocType',),
extra=1)
department = Department.objects.get(DepId=pk)
formset = DocumentFormSet(queryset=Document.objects.none(), instance=department)
context = {
'department': department,
'form': formset,
}
if request.method == "POST":
formset = PaymentDocumentFormSet(request.POST, request.FILES, instance=location)
if formset.is_valid():
for form in formset:
fileform = form.save(commit=False)
print (fileform.Name)
return redirect('getdoc', pk=department.DepId)
else:
messages.info(request, "Errors in Formset: "+formset.errors)
return render(request, "getdoc", context)
Шаблон:
{% extends 'base.html' %}
{% block content %}
{% load static %}
<br>
<div class="container">
<div class="row">
<div class="col-md-12">
<table class="table table-sm">
<thead class="thead-dark">
<tr>
<th>Department Name</th>
</tr>
</thead>
<tbody>
<tr>
<td>{{ request.session.dep_name }}</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="row">
<div class="col-md-12">
<table class="table table-sm">
<thead class="thead-dark">
<tr>
<th><h5>Upload the Document</h5><h6>You must have atleast one Report 1 and one Report 2 types</h6></th>
</tr>
</thead>
<tbody>
<tr>
{% for message in messages %}
<td id="messages">{{message}}</td>
{% endfor %}
</tr>
<tr>
<td>
<form action = "" method="POST" enctype="multipart/form-data"> {% csrf_token %}
<table class="table table-sm">
{{ form.management_form }}
{% for f in form %}
{% if forloop.first %}
<thead>
<tr>
{%for field in f.visible_fields %}
<th>{{ field.label|capfirst }}</th>
{% endfor %}
</tr>
</thead>
{% endif %}
<tr class="formset_row">
{% for field in f.visible_fields %}
<td>
{# Include the hidden fields in the form #}
{% if forloop.first %}
{% for hidden in f.hidden_fields %}
{{ hidden }}
{% endfor %}
{% endif %}
{{ field.errors.as_ul }}
{{ field }}
</td>
{% endfor %}
</tr>
{% endfor %}
</table>
<button type="submit" name ="fl_upload" class="btn btn-outline-info btn-sm"><span class="fas fa-arrow-circle-up fa-2x">Upload File</span></button>
</form>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="{% static 'js/jquery.formset.js' %}"></script>
<script type="text/javascript">
$('.formset_row').formset({
addText: 'Add More Doc',
deleteText: 'Remove',
prefix: 'paydocumentform_set'
});
</script>
{% endblock content %}
Я использую Javascript из этого git репозитория .
Поэтому, когда я загружаю несколько документов, набор форм всегда возвращает только один документ. Есть ли проблема с моим кодом? Я не уверен, что это поведение из-за extra = 1, который я указал в определении набора форм.
Спасибо.