在Django中如何设置相关下拉列表

在Django中如何设置相关下拉列表,django,Django,我正在尝试在Django3.1站点中设置相关下拉列表。这些列表通过另一个应用程序(Django Machina)DB表填充。我试图改编这个例子。然而,我对Django和Python还不熟悉,到目前为止,我还不能让它工作 我的档案如下: models.py from django.contrib.auth.models import AbstractUser from django.db import models from machina.core.db.models import get_mo

我正在尝试在Django3.1站点中设置相关下拉列表。这些列表通过另一个应用程序(Django Machina)DB表填充。我试图改编这个例子。然而,我对Django和Python还不熟悉,到目前为止,我还不能让它工作

我的档案如下:

models.py

from django.contrib.auth.models import AbstractUser
from django.db import models
from machina.core.db.models import get_model
from django.db.models import Q

Forum = get_model("forum", "Forum")

class CustomUser(AbstractUser):
    age = models.PositiveIntegerField(null=True, blank=True)
    business_location_state = models.ForeignKey(Forum, null=True,  on_delete=models.SET_NULL, limit_choices_to={"lft":1})
    business_location_county = models.ForeignKey(Forum, null=True, on_delete=models.SET_NULL, related_name='county', limit_choices_to=(~Q(lft__in = (1,2))))
views.py

from django.urls import reverse_lazy
from django.views.generic import CreateView
from .forms import CustomUserCreationForm
from .models import CustomUser
from django.shortcuts import render
from machina.core.db.models import get_model
from django.db.models import Q

Forum = get_model("forum", "Forum")


class SignUpView(CreateView):
    form_class = CustomUserCreationForm
    success_url = reverse_lazy('login')
    template_name = 'registration/signup.html'

def load_counties(request):
    parent_id = request.GET.get('business_location_state')
    counties = Forum.objects.filter(parent_id=parent_id).order_by('name')
    return render(request, 'hr/county_dropdown_list_options.html', {'counties': counties})
accounts/url.py

# accounts/urls.py
from django.urls import path
from .views import SignUpView
from . import views

urlpatterns = [
    path('signup/', SignUpView.as_view(), name='signup'),
    path('ajax/load-counties/', views.load_counties, name='ajax_load_counties'),  # ajax to load counties

]
forms.py

from django import forms
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from .models import CustomUser

class CustomUserCreationForm(UserCreationForm):
    class Meta(UserCreationForm):
        model = CustomUser
        fields = UserCreationForm.Meta.fields + ('username', 'email', 'age', 'business_location_state', 'business_location_county')

        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
            self.fields['business_location_county'].queryset = CustomUser.objects.none()




class CustomUserChangeForm(UserChangeForm):
    class Meta:
        model = CustomUser
        fields = ('username', 'email', 'age','business_location_state', 'business_location_county')
计数\下拉列表\选项.html

<!-- templates/hr/county_dropdown_list_options.html -->
<option value="">---------</option>
{% for county in counties %}
<option value="{{ business_location_county.pk }}">{{ business_location_county.name }}</option>
{% endfor %}

---------
{县中县的百分比%}
{{business_location_county.name}
{%endfor%}
signup.html

<!-- templates/registration/signup.html -->
{% extends 'base.html' %}

{% block title %}
  Sign Up
{% endblock title %}

{% block content %}
<h2>Sign up</h2>
<form method="post" id=signupForm data-counties-url="{% url 'ajax_load_counties' %}" novalidate>
  {% csrf_token %}
  {{ form.as_p }}
  <button type="submit">Sign Up</button>
</form>

<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
  <script>
    $("#id_business_location_state").change(function () {
      var url = $("#signupForm").attr("data-counties-url");  // get the url of the `load_cities` view
      var stateId = $(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: {
          'business_location_state': stateId       // add the state id to the GET parameters
        },
        success: function (data) {   // `data` is the return of the `load_cities` view function
          $("#id_county").html(data);  // replace the contents of the city input with the data that came from the server
        }
      });

    });
  </script>
{% endblock content %}

{%extends'base.html%}
{%block title%}
注册
{%endblock title%}
{%block content%}
注册
{%csrf_令牌%}
{{form.as_p}}
注册
$(“#id#business#location#state”).change(函数(){
var url=$(“#signupForm”).attr(“数据县url”);//获取“加载城市”视图的url
var stateId=$(this).val();//从HTML输入中获取所选国家/地区ID
$.ajax({//初始化ajax请求
url:url,//设置请求的url(=localhost:8000/hr/ajax/load cities/)
数据:{
'business\u location\u state':stateId//将状态id添加到GET参数
},
成功:函数(data){/`data`是`load_cities`视图函数的返回
$(“#id_county”).html(data);//将城市输入的内容替换为来自服务器的数据
}
});
});
{%endblock内容%}

我目前没有看到任何错误,但县列表没有根据“业务位置状态”选择进行更改。你知道哪里出了问题吗?

是你所在领域的id
id\u county
?我假设它的id是
id\u business\u location\u county
,给定字段名。您可以使用浏览器开发工具检查呈现的HTML,检查字段的id是什么。据我所知,您需要更改
$(“#id_county”).html(数据)
$(“#id_business_location_county”).html(数据)。同样在ajax模板中,您编写了
{{business\u location\u county.pk}
{{business\u location\u county.name}
,但是您的循环变量名为
country
谢谢您,Abdul。这就成功了。我更改了$(“#id_county”).html(数据);至$(“#id#u business_location_county”).html(数据);然后在ajax中循环通过{country.pk}和{{country.name}}。