使用 Ajax 动态更新 Django 表单字段选项以获取新的查询集 [英] Dynamically update Django form field options using Ajax to GET new queryset

查看:19
本文介绍了使用 Ajax 动态更新 Django 表单字段选项以获取新的查询集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是编码和 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 %}

更新:sub_category 选项显示为 [object Object],直到我将 value 更改为 value.name 并且看起来它正在工作.除非有任何意见,否则我将对其进行测试并关闭.

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 视图端(即后端)执行此操作.您可以尝试使用 ajax 请求来实现此类请求,方法是向服务器发送 GET 请求以填充下拉列表或您想要的任何内容.

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

如何在 Django 中使用 jQuery/Ajax 进行 POST?

编辑

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆