Django 表单未获得 select 字段 selection。下拉依赖
Django form not getting the select field selection. Dropdown dependant
我有一个非常复杂的方法,在 forms.py 的帮助下,我通过 Ajax 在我自己的项目中查询州、县和社区的数据库,现在,我有它用于注册一个房间(与这些位置相关),它通过一个 CreateView,对于这个我没有问题,但是,当想要创建一个查询集来搜索我的房间及其各自位置时,它似乎它没有拾取在该字段上选择的内容,我知道这一点,因为我要求它打印请求并打印 'None',这是我的代码:
models.py
class PostRoom(models.Model):
author = models.ForeignKey(User,on_delete=models.CASCADE,default=1,related_name='room_author')
colonia = models.ForeignKey(Colonia, on_delete=models.SET_NULL, blank=True, null=True)
cp = models.ForeignKey(CP, on_delete=models.SET_NULL, blank=True, null=True)
municipio = models.ForeignKey(Municipio, on_delete=models.SET_NULL, blank=True, null=True)
estado = models.ForeignKey(Estado, on_delete=models.SET_NULL, blank=True, null=True)
完美运行的 CreateView:
class RoomSubmitCreateView(LoginRequiredMixin, CreateView):
model = PostRoom
form_class = PostRoomForm
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
ajax 代码,通过它我将选定的字段发送到我的 location.views.py:
<script>
$("#id_estado").change(function () {
var url = $("#roomForm").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>
$("#id_municipio").change(function () {
var url = $("#roomForm").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
}
});
});
现在,事情行不通了。
我的 forms.py 搜索:
class RoomSearch(forms.ModelForm):
class Meta:
model = PostRoom
fields = ('estado',
'municipio',
'colonia')
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['municipio'].queryset = Municipio.objects.none()
self.fields['colonia'].queryset = Colonia.objects.none()
if 'estado' in self.data:
try:
estado_id = int(self.data.get('estado'))
self.fields['municipio'].queryset = Municipio.objects.filter(estado_id=estado_id).order_by('municipio')
except (ValueError, TypeError):
pass # invalid input from the client; ignore and fallback to empty City queryset
elif self.instance.pk:
self.fields['municipio'].queryset = self.instance.estado.municipio_set.order_by('municipio')
if 'municipio' in self.data:
try:
municipio_id = int(self.data.get('municipio'))
self.fields['colonia'].queryset = Colonia.objects.filter(municipio_id=municipio_id).order_by('colonia')
except (ValueError, TypeError):
pass # invalid input from the client; ignore and fallback to empty City queryset
elif self.instance.pk:
self.fields['colonia'].queryset = self.instance.municipio.colonia_set.order_by('colonia')
和我的 search.views.py:
def room_results(request):
form = RoomSearch(request.GET or None)
context = {
"form": form,
}
print ("ESTADO:",form['estado'].value())
print ("MUNICIPIO:",form['municipio'].value())
print ("COLONIA:",form['colonia'].value())
if request.method == 'GET':
print ("SI QUERY")
queryset = PostRoom.objects.all().filter(
estado__id__exact=form['estado'].value(),
municipio__id__exact=form['municipio'].value(),
colonia__id__exact=form['colonia'].value()
)
context = {
"rooms": queryset,
"form": form,
}
return render(request, "search/search_room.html",context)
无论我做什么,它每次都会在日志中打印:
ESTADO: None
MUNICIPIO: None
COLONIA: None
SI QUERY
那里获得了制作奇怪的依赖下拉列表的诀窍
好吧,朋友们,没人回答(哇,太惊喜了,从来没有在这里得到任何直接帮助),一如既往,它有一个笨拙的错误,在我的 HTML 文件中:
<a type="submit" class="btn btn-primary">
<i class="fa fa-search"></i>
</a>
它应该是:
<button type="submit" class="btn btn-primary">
<i class="fa fa-search"></i>
</button>
我有一个非常复杂的方法,在 forms.py 的帮助下,我通过 Ajax 在我自己的项目中查询州、县和社区的数据库,现在,我有它用于注册一个房间(与这些位置相关),它通过一个 CreateView,对于这个我没有问题,但是,当想要创建一个查询集来搜索我的房间及其各自位置时,它似乎它没有拾取在该字段上选择的内容,我知道这一点,因为我要求它打印请求并打印 'None',这是我的代码:
models.py
class PostRoom(models.Model):
author = models.ForeignKey(User,on_delete=models.CASCADE,default=1,related_name='room_author')
colonia = models.ForeignKey(Colonia, on_delete=models.SET_NULL, blank=True, null=True)
cp = models.ForeignKey(CP, on_delete=models.SET_NULL, blank=True, null=True)
municipio = models.ForeignKey(Municipio, on_delete=models.SET_NULL, blank=True, null=True)
estado = models.ForeignKey(Estado, on_delete=models.SET_NULL, blank=True, null=True)
完美运行的 CreateView:
class RoomSubmitCreateView(LoginRequiredMixin, CreateView):
model = PostRoom
form_class = PostRoomForm
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
ajax 代码,通过它我将选定的字段发送到我的 location.views.py:
<script>
$("#id_estado").change(function () {
var url = $("#roomForm").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>
$("#id_municipio").change(function () {
var url = $("#roomForm").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
}
});
});
现在,事情行不通了。 我的 forms.py 搜索:
class RoomSearch(forms.ModelForm):
class Meta:
model = PostRoom
fields = ('estado',
'municipio',
'colonia')
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['municipio'].queryset = Municipio.objects.none()
self.fields['colonia'].queryset = Colonia.objects.none()
if 'estado' in self.data:
try:
estado_id = int(self.data.get('estado'))
self.fields['municipio'].queryset = Municipio.objects.filter(estado_id=estado_id).order_by('municipio')
except (ValueError, TypeError):
pass # invalid input from the client; ignore and fallback to empty City queryset
elif self.instance.pk:
self.fields['municipio'].queryset = self.instance.estado.municipio_set.order_by('municipio')
if 'municipio' in self.data:
try:
municipio_id = int(self.data.get('municipio'))
self.fields['colonia'].queryset = Colonia.objects.filter(municipio_id=municipio_id).order_by('colonia')
except (ValueError, TypeError):
pass # invalid input from the client; ignore and fallback to empty City queryset
elif self.instance.pk:
self.fields['colonia'].queryset = self.instance.municipio.colonia_set.order_by('colonia')
和我的 search.views.py:
def room_results(request):
form = RoomSearch(request.GET or None)
context = {
"form": form,
}
print ("ESTADO:",form['estado'].value())
print ("MUNICIPIO:",form['municipio'].value())
print ("COLONIA:",form['colonia'].value())
if request.method == 'GET':
print ("SI QUERY")
queryset = PostRoom.objects.all().filter(
estado__id__exact=form['estado'].value(),
municipio__id__exact=form['municipio'].value(),
colonia__id__exact=form['colonia'].value()
)
context = {
"rooms": queryset,
"form": form,
}
return render(request, "search/search_room.html",context)
无论我做什么,它每次都会在日志中打印:
ESTADO: None
MUNICIPIO: None
COLONIA: None
SI QUERY
那里获得了制作奇怪的依赖下拉列表的诀窍
好吧,朋友们,没人回答(哇,太惊喜了,从来没有在这里得到任何直接帮助),一如既往,它有一个笨拙的错误,在我的 HTML 文件中:
<a type="submit" class="btn btn-primary">
<i class="fa fa-search"></i>
</a>
它应该是:
<button type="submit" class="btn btn-primary">
<i class="fa fa-search"></i>
</button>