使用Ajax动态更新Django表单字段选项以获取新的查询集 [英] Dynamically update Django form field options using Ajax to GET new queryset
问题描述
我是编码和django的新手,并且在审查了我找到的答案后,正在努力寻找以下问题的解决方案.
I'm new to coding and django and I'm struggling to find the solution to the following problem having reviewed the answers I've found.
我正在创建一个包含多个字段的搜索表单.当用户选择第一个字段category
时(在单击搜索之前),我想动态更改第二个字段sub_category
的查询集,以便仅显示相关值.
Im creating a search form with multiple fields. When the user selects the first field category
(and before hitting search) I would like to dynamically change the queryset for the second field sub_category
such that only related values are shown.
我有models.py
如下:
class Product(models.Model):
category = models.ForeignKey("Category")
sub_category = models.ForeignKey("SubCategory")
class Category(models.Model):
name = models.CharField(max_length=256)
class SubCategory(models.Model):
category = models.ForeignKey("Category")
name = models.CharField(max_length=256)
我的forms.py
包括:
class BasicSearchForm(forms.Form):
category = forms.ModelChoiceField(
label='Category',
queryset=Category.objects.all(),
to_field_name="name",
empty_label=None,
initial="Red")
sub_category = forms.ModelMultipleChoiceField(
required=False,
label='Type',
queryset= SubCategory.objects.all(),
to_field_name="name",
widget=forms.Select)
我的views.py
包括:
def search(request):
if request.method == 'POST':
form = BasicSearchForm(request.POST)
if form.is_valid():
category = form.cleaned_data['category']
sub_category = form.cleaned_data['sub_category']
return render(request, 'myapp/search.html', {'form': form})
else:
form = BasicSearchForm()
return render(request, 'myapp/search.html', {'form': form})
最后,search.html包括:
And finally the search.html includes:
<form class="search-form" role="search" action="/search/" method="get">
{{ form }}
<input type="submit" value="Search" />
</form>
我一直在回答一些问题,但似乎没有任何效果.我真的很感谢您的帮助.预先感谢!
I've played around with a few answers but nothing seems to work. I'd really appreciate some help. Thanks in advance!
更新: 感谢您的反馈.结果,我更新了以下内容:
Update: Thanks for the feedback. As a result I updated the following:
在我的urls.py
中:
urlpatterns = [
url(r'^ajax/update_subcategories/$', views.update_subcategories, name='update_subcategories'),
在我的views.py
中:
def update_subcategories(request):
category = request.GET.get('category', None)
sub_category = list(SubCategory.objects.filter(category__name__exact=category).values('name'))
return JsonResponse(sub_category, safe=False)
而我的myapp/search.html
中有这个:
{% block javascript %}
<script>
$("#id_category").change(function () {
var category = $(this).val();
$.ajax({
url: '{% url "myapp:update_subcategories" %}',
data: {
'category': category,
},
success: function (response) {
var new_options = response;
alert(new_options[0].name); // works
$('#id_sub_category').empty();
$.each(new_options, function(key, value) {
$('#id_sub_category')
.append($('<option>', { value : key })
.text(value.name));
});
}
});
</script>
{% endblock %}
更新:直到我将value更改为value.name且看起来正常为止,sub_category选项一直显示为[object Object].除非有任何评论,否则我将对其进行测试并关闭.
Update: The sub_category options were showing as [object Object] until I changed value to value.name and it looks like it's working. I'll test it out and close unless there are any comments.
更新:我的浏览器后退按钮仍然存在问题.当用户单击返回时,下拉值已更改回原始查询集,而不是更新的版本.
Update: Im still having an issue with the browser back button. When a user clicks back the dropdown values have changed back to the original queryset rather than the updated version.
推荐答案
您不能从Django视图端(即后端)执行此操作.您可以通过将GET请求发送到服务器以填充下拉列表或您要使用的任何内容,来尝试实现此类请求的ajax请求.
You can't do this from Django views side, ie, backend. You could try an ajax request for implementing this kind of requests, by sending a GET request to the server for populating the drop-down or whatever you are into.
举一个简单的例子,您可以参考 这里
For a simple example, you could refer here
编辑
def update_subcategories(request):
category = request.GET.get('category', None)
sub_category = list(SubCategory.objects.filter(category__name__exact=category).values('name'))
return JsonResponse(dict(sub_category=sub_category))
然后在ajax响应中,您可以像response.data.sub_category
Then in ajax response you could grab it like response.data.sub_category
这篇关于使用Ajax动态更新Django表单字段选项以获取新的查询集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!