im使用 Django 2.0, Django_select2 6.0.3和 Select2 4.0.6在我的项目中创建两个依赖列表。我遵循this documentation设置代码。我们没有收到任何错误,但数据未显示在自动完成字段中。我试图将列表“ Provincias”与列表“ Regiones”链接在一起,因此当您从区域中选择一个选项时,将显示该区域中的所有省。这是我的代码。
Models.py
class region(models.Model):
region = models.CharField(max_length=200)
class provincia(models.Model):
region = models.ForeignKey(region, related_name="provincias",on_delete=models.CASCADE)
provincia = models.CharField(max_length=200)
Forms.py
class Direccion(forms.ModelForm):
region = forms.ModelChoiceField(
queryset=region.objects.all(),
label="Region",
widget=ModelSelect2Widget(
model=region,
search_fields=['region'],
dependent_fields={'provincia': 'provincias'},
)
)
provincia = forms.ModelChoiceField(
queryset=provincia.objects.all(),
label="Provincia",
widget=ModelSelect2Widget(
model=provincia,
search_fields=['region__icontains'],
dependent_fields={'region': 'region'},
max_results=500,
)
)
comuna = forms.CharField(required=True, label='Comuna')
calle = forms.CharField(required=True, label='Calle')
numero = forms.CharField(required=True, label='Número')
departamento = forms.IntegerField(label='Departamento')
class Meta:
model = direcciones
fields = ('region', 'provincia', 'comuna', 'calle', 'numero', 'departamento')
views.py
def nuevadir(request):
if request.method == 'POST':
dire = Direccion(request.POST)
if dire.is_valid():
dire2 = dire.save(commit=False)
dire2.user = request.user
dire2.region = dire.cleaned_data['region']
dire2.provincia = dire.cleaned_data['provincia']
dire2.comuna = dire.cleaned_data['comuna']
dire2.numero = dire.cleaned_data['numero']
dire2.calle = dire.cleaned_data['calle']
dire2.departamento = dire.cleaned_data['departamento']
dire2.save()
return render(request, 'perfil-direccion.html')
else:
dir = Direccion()
return render(request, 'perfil-nuevadir.html', {'dir': dir})
HTML
{% load widget_tweaks %}
<form method="post" action="{% url 'nuevadir' %}">
{% csrf_token %}
{% if dir.errors %}
{{ errors }}
{% endif %}
<div class="form -row">
<div class="col-md-6">
<div class="form-row">
{% for item in dir.visible_fields %}
<div class="col-md-12 mb-3">
<label class="control-label" for="{{item.id_for_label}}">{{item.label}}</label>
{% render_field item class="form-control" %}
</div>
{% endfor %}
</div>
</div>
</div>
<hr>
<div class="form-actions">
<button type="submit" class="btn btn-primary ml-auto">Agregar Dirección</button>
</div>
</form>
我不知道从数据库获取数据是否有问题(我们有两个表。一个具有列ID和列的Regiones,另一个是具有列ID,Provincias和region_id的Provicionas),也许不是在HTML中正确呈现。
感谢您的帮助,我们对此深感困惑