早上好,我是Django的新手,我想包括一个模板表单,但是它不显示字段,仅显示保存按钮。 使用Django 2.1。我总结了代码,所以请您帮我一下。因为您需要在其他模板中重复使用该表单。
models.py
from django.db import models
class Area(models.Model):
nombre = models.CharField(max_length=45)
descripcion = models.CharField(max_length=100, null=True, blank=True)
def __str__(self):
return self.nombre
views.py
class AreaCreate(CreateView):
model = Area
form_class = AreaForm
template_name = 'area/area_form.html'
class AreaList(ListView):
model = Area
template_name = 'area/area_list.html'
forms.py
class AreaForm(forms.ModelForm):
class Meta:
model = Area
fields = (
'nombre',
'descripcion',
)
widgets = {
'nombre': forms.TextInput(attrs={'class': 'form-control', 'placeholder':'Area'}),
'descripcion': forms.TextInput(attrs={'class': 'form-control', 'placeholder':'Descripción'}),
}
area_form.html
<form action="" method="POST"> {% csrf_token %}
<div class="form-row">
<div class="col-sm-4 campoform">
{{ form.nombre }}
</div>
<div class="col-sm-6 campoform">
{{ form.descripcion }}
</div>
<div class="col-sm-2 campoform">
<button class="btn btn-primary" type="submit" style="width:100%">Guardar</button>
</div>
</div>
</form>
area_list.html ---为了更好的理解,我没有添加完整的list.html代码。
<div>{% include "area/area_form.html" %}</div>
area_list.html中的结果是仅显示按钮。
答案 0 :(得分:1)
抱歉,回复延迟。我通过使用模式调用表单解决了该问题。使用库“ bootstrap_modal_forms”。
#View
class GestionarAreas(generic.ListView):
model = Area
context_object_name = 'areas'
template_name = 'areas/gestionar_areas.html'
paginate_by = 10
class CrearArea(generic.CreateView):
template_name = 'areas/crear_area.html'
form_class = AreaForm
success_url = reverse_lazy('gestionar_areas')
#urls
path('', login_required(views.GestionarAreas.as_view()),name='gestionar_areas'),
path('crear/', login_required(views.CrearArea.as_view()), name='crear_area'),
#HTML
<div class="col-sm-auto">
<button class="crear-area btn btn-primary" type="button"name="button">
<span class="fa fa-plus mr-2"></span>Crear Area</button>
</div>
#Script
// Boton Crear Area
$(".crear-area").modalForm({formURL: "{% url 'crear_area' %}", successURL: ""});
// Boton Actualizar Area
$(".editar-area").each(function () {
$(this).modalForm({formURL: $(this).data('id'), successURL: ""});
});