微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Django 表单,级联/依赖下拉列表未正确提交 posts.modelsposts.forms发布模板这是使用 Ajax 和 JQuery 的地方location.modelslocation.views - 在这里你可以看到我试图直接传递给表单中的选项,但不起作用location.templates.municipios_options.htmllocation.templates.colonias_options.html

如何解决Django 表单,级联/依赖下拉列表未正确提交 posts.modelsposts.forms发布模板这是使用 Ajax 和 JQuery 的地方location.modelslocation.views - 在这里你可以看到我试图直接传递给表单中的选项,但不起作用location.templates.municipios_options.htmllocation.templates.colonias_options.html

我使用 this tutorial一个依赖或级联下拉列表,它在提交表单时列出了州、县和社区。它显示正确,但是当我点击提交时,会列出以下错误:“选择一个有效的选项。该选项不可用”。 它有两个应用程序:posts 和 location,我会发布posts.models、posts.forms 和posts 的模板,但不发布视图,因为它是一个简单的CreateView。

关于位置应用程序,我将发布我将信息传递给帖子应用程序的模型、视图和模板。 我把定位应用分开了,因为我也想用它来搜索这些帖子。 非常感谢任何建议。

附带说明:Estado = State,Municipio = County and Colonia = Neighborhood

这是我的代码

posts.models

class PostRoom(models.Model):
  colonia = models.ForeignKey(Colonia,on_delete=models.SET_NULL,blank=True,null=True)
  municipio = models.ForeignKey(Municipio,null=True)
  estado = models.ForeignKey(Estado,null=True)

class PostPerson(models.Model):
  colonia = models.ForeignKey(Colonia,null=True)

posts.forms

class PostPersonForm(forms.ModelForm):
  class Meta:
    model = PostPerson
    fields = ('colonia','municipio','estado')
  def __init__(self,*args,**kwargs):
    super().__init__(*args,**kwargs)
    self.fields['municipio'].queryset = Municipio.objects.none()
    self.fields['colonia'].queryset = Colonia.objects.none()


class PostRoomForm(forms.ModelForm):
  class Meta:
    model = PostRoom
    fields = ('colonia',**kwargs)
    self.fields['municipio'].queryset = Municipio.objects.none()
    self.fields['colonia'].queryset = Colonia.objects.none()

发布模板(这是使用 Ajax 和 JQuery 的地方)

    <form method="POST" action="" enctype="multipart/form-data" id="personForm" load-municipios="{% url 'load_municipios' %}" load-colonias="{% url 'load_colonias' %}">
    {% csrf_token %}
            <div class="form-row">
        <div class="col-12 form-group">
            {% if form.estado.errors %} 
            <div class="card border-danger mb-3" style="max-width: 18rem;">
                <div class="card-body text-danger">
                    <h5 class="card-title">{{ form.estado.errors }}</h5>
                </div>  
            </div>
            {% endif %}
            <h6>Estado</h6>
            {{ form.estado }}
        </div> <!-- form-group end.// -->

        <div class="col-12 form-group">
            {% if form.municipio.errors %} 
            <div class="card border-danger mb-3" style="max-width: 18rem;">
                <div class="card-body text-danger">
                    <h5 class="card-title">{{ form.municipio.errors }}</h5>
                </div>  
            </div>
            {% endif %}
            <h6>Municipio</h6>
            {{ form.municipio }}
        </div> <!-- form-group end.// -->

        <div class="col-12 form-group">
            {% if form.colonia.errors %} 
            <div class="card border-danger mb-3" style="max-width: 18rem;">
                <div class="card-body text-danger">
                    <h5 class="card-title">{{ form.colonia.errors }}</h5>
                </div>  
            </div>
            {% endif %}
            <h6>Colonia</h6>
            {{ form.colonia }}
        </div> <!-- form-group end.// -->
        </div>
        <hr>
     </form>
    
    <script>
    $("#id_estado").change(function () {
      var url = $("#personForm").attr("load-municipios");  // get the url of the `load_cities` view
      var estadoId = $(this).val();  // get the selected country ID from the HTML input

      $.ajax({                       // initialize an AJAX request
        url: url,// set the url of the request (= localhost:8000/hr/ajax/load-cities/)
        data: {
          'estado': estadoId       // add the country id to the GET parameters
        },success: function (data) {   // `data` is the return of the `load_cities` view functionlog
        console.log(data);
          $("#id_municipio").html(data);  // replace the contents of the city input with the data that came from the server
        }
      });

    });
</script>

<script>
    $("#id_municipio").change(function () {
      var url = $("#personForm").attr("load-colonias");  // get the url of the `load_cities` view
      var municipioId = $(this).val();  // get the selected country ID from the HTML input

      $.ajax({                       // initialize an AJAX request
        url: url,// set the url of the request (= localhost:8000/hr/ajax/load-cities/)
        data: {
          'municipio': municipioId       // add the country id to the GET parameters
        },success: function (data) {   // `data` is the return of the `load_cities` view functionlog
        console.log(data);
          $("#id_colonia").html(data);  // replace the contents of the city input with the data that came from the server
        }
      });

    });
</script>

现在,它与位置应用通信:

location.models

class Estado(models.Model):
    estado = models.CharField(max_length=100)

    def __str__(self):
        return self.estado

class Municipio(models.Model):
    municipio = models.CharField(max_length=100)
    estado = models.ForeignKey(Estado,on_delete=models.CASCADE)

    def __str__(self):
        return self.municipio

class CP(models.Model):
    cp = models.CharField(max_length=100)
    municipio = models.ForeignKey(Municipio,on_delete=models.CASCADE)
    estado = models.ForeignKey(Estado,on_delete=models.CASCADE)

    def __str__(self):
        return self.cp

class Colonia(models.Model):
    colonia = models.CharField(max_length=100)
    cp = models.ForeignKey(CP,on_delete=models.CASCADE)
    municipio = models.ForeignKey(Municipio,on_delete=models.CASCADE)
      
    def __str__(self):
        return self.colonia

location.views - 在这里你可以看到我试图直接传递给表单中的选项,但不起作用。

def load_municipios(request):
    estado_id = request.GET.get('estado')
    municipios = Municipio.objects.filter(estado_id=estado_id).order_by('municipio')
    person_form = PostPersonForm(request.POST)
    room_form = PostRoomForm(request.POST)
    choice_list = []
    for municipio in municipios:
        choice = (municipio.pk,municipio.municipio)
        choice_list.append(choice)

    person_form.fields['municipio'].choices = choice_list
    print(person_form.fields['municipio'].choices)
    return render(request,'location/municipios_options.html',{'municipios' : municipios})
    #return JsonResponse(list(municipios.values('id','municipio')),safe=False)

def load_colonias(request):
    municipio_id = request.GET.get('municipio')
    colonias = Colonia.objects.filter(municipio_id=municipio_id).order_by('colonia')
    #print(list(colonias.values('id','municipio')))
    return render(request,'location/colonias_options.html',{'colonias' : colonias})
    #return JsonResponse(list(municipios.values('id',safe=False)

最后,我如何将选项信息传递到表单模板...

location.templates.municipios_options.html

<option value="">---------</option>
{% for municipio in municipios %}
<option value="{{ municipio.pk }}">{{ municipio.municipio }}</option>
{% endfor %}

location.templates.colonias_options.html

<option value="">---------</option>
{% for colonia in colonias %}
<option value="{{ colonia.pk }}">{{ colonia.colonia }}</option>
{% endfor %}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。