Django форма/формасет кнопка для добавления поля
models.py
class Car(models.Model):
FUEL = (
('', '---------'),
('1', 'Gasoline'),
('2', 'Diesel'),
('3', 'Electric'),
('4', 'Hybrid'),
)
client = models.ForeignKey(Client,on_delete=models.CASCADE, null=True, blank=True)
car_make = models.ForeignKey(CarMake, on_delete=models.CASCADE)
car_model = models.ForeignKey(CarModel, on_delete=CASCADE)
fuel_type = models.CharField(max_length=15, choices=FUEL, default=None)
engine = models.CharField(max_length=15)
service = models.ForeignKey(Service, on_delete=models.SET_NULL, null=True, blank=True)
extra_info = models.TextField(max_length=300, verbose_name='Info.', null=True, blank=True)
date_added = models.DateTimeField(auto_now_add=True)
date_updated = models.DateTimeField(auto_now=True)
forms.py
CarFormset = modelformset_factory(
models.Car,
fields=('service', ),
extra=1,
widgets={'name': forms.TextInput(attrs={
'class': 'form-control',
'placeholder': 'Whatever'
})
}
)
class CarForm(forms.ModelForm):
class Meta:
model = models.Car
fields = '__all__'
шаблон
{% load crispy_forms_tags %}
<form action='' method='post'>
{% csrf_token %}
{{ form|crispy }}
<input type='submit' value='Submit'>
{% if formset %}
{{formset.management_form}}
<div id='service-form-test'></div>
<div id='empty-form' class=''>{{formset.empty_form}}</div>
<button id='add-more' type='button'>Add</button>
{% endif %}
</form>
<script>
const addMoreBtn = document.getElementById('add-more')
const totalNewForms = document.getElementById('id_form-TOTAL_FORMS')
const currentServiceForms = document.getElementsByClassName('service-form')
addMoreBtn.addEventListener('click', add_new_form)
function add_new_form(event) {
if (event) {
event.preventDefault()
}
const currentFormCount = currentServiceForms.length // + 1
console.log(currentServiceForms.length)
const formCopyTarget = document.getElementById('service-form-test')
const copyEmptyFormEl = document.getElementById('empty-form').cloneNode(true)
copyEmptyFormEl.setAttribute('class', 'service-form')
copyEmptyFormEl.setAttribute('id', `form-${currentFormCount}`)
const regex = new RegExp('__prefix__', 'g')
copyEmptyFormEl.innerHTML = copyEmptyFormEl.innerHTML.replace(regex, currentFormCount)
totalNewForms.setAttribute('value', currentFormCount + 1)
formCopyTarget.append(copyEmptyFormEl)
}
</script>
Здравствуйте, я добавлю изображение того, что я пытаюсь сделать, я новичок и единственное место, где я могу спросить, это здесь. Итак, я пытаюсь добавить этот набор форм внутрь формы, картинка объяснит. Возможно, у меня есть несколько идей, но я не знаю, являются ли они оптимальными.
- Render form manually, skip the SERVICE field and add a formset in its place.
- Remove SERVICE field from form and just add a formset in its place, i guessi would have to render form manually as well?
- Ideal thing that i would like to do is just a button near SERVICE form.field to add a formset below it if i want to - this i do not know how to do.
Я пытался что-то искать, но не нашел решения. Вот скрин отрисованного шаблона и то, что я пытаюсь сделать.