【发布时间】:2021-08-25 03:42:35
【问题描述】:
我有一个非常复杂的方法,我通过 Ajax 在我自己的项目中询问州、县和社区的数据库,在 forms.py 的帮助下,现在,我有它来注册一个房间(这是与这些位置有关),它通过一个 CreateView,我没有问题,但是,当想要创建一个查询集来搜索我的房间及其各自的位置时,它似乎没有选择在该字段上选择了什么,我知道这是因为我要求它打印请求并且它打印“无”,这是我的代码:
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)
我通过它发送选定字段到我的 location.views.py 的 ajax 代码:
<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
顺便说一句,我从 https://simpleisbetterthancomplex.com/tutorial/2018/01/29/how-to-implement-dependent-or-chained-dropdown-list-with-django.html 获得了奇怪的依赖下拉列表的诀窍
【问题讨论】:
标签: django search django-views django-forms django-queryset