首页 > 解决方案 > 用户使用邮政编码数据库输入邮政编码时自动填充状态|Django|JQuery|UI

问题描述

如何通过输入邮政编码自动填充状态。我有邮政编码数据库。如何在表单中进行验证。如果用户使用该邮政编码输入此数据库中可用的邮政编码,则该州应自动填充,如下面的数据库中所述。如果邮政编码匹配,则状态必须自动填充。

我已经使用 API 实现了这一点。但知道我与数据库有关:

    INSERT INTO pages_zip_code (id, zip, city, st) VALUES
    (1, '00501', 'Holtsville', 'NY'),
    (2, '00544', 'Holtsville', 'NY'),
    (3, '00601', 'Adjuntas', 'PR'),
    (4, '00602', 'Aguada', 'PR'),
    (5, '00603', 'Aguadilla', 'PR'),
    (6, '00604', 'Aguadilla', 'PR'),
    (7, '00605', 'Aguadilla', 'PR'),
    (8, '00606', 'Maricao', 'PR'),
    (9, '00610', 'Anasco', 'PR'),
    (10, '00611', 'Angeles', 'PR'),
    (11, '00612', 'Arecibo', 'PR'),
    (12, '00613', 'Arecibo', 'PR'),
    (13, '00614', 'Arecibo', 'PR'),
    (14, '00616', 'Bajadero', 'PR'),
    (15, '00617', 'Barceloneta', 'PR'),
    (16, '00622', 'Boqueron', 'PR');

网址.py`

    path('autostate', views.autostate, name='autostate'),

视图.py

    def autozip(request):
    if 'term' in request.GET:
    qs = zip_code.objects.filter(zip__istartswith=request.GET.get('term'))
    zip_list = list()
    for zip_c in qs:
    zip_list.append(zip_c.state)
    return JsonResponse(zip_list, safe=False)
    return render(request, 'home.html')

html页面

<input class="InputZip" name="Zip" placeholder="Zip Code" type="text">
<input class="Inputstate" name="state" placeholder="State" type="text">

    <script>
    function is_int(value) {
    if ((parseFloat(value) == parseInt(value)) && !isNaN(value)) {
    return true;
    } else {
    return false;
    }
    }
    $(".InputZip").keyup(function() {
    // Cache
    var el = $(this);
    // Did they type five integers?
    if ((el.val().length == 5) && (is_int(el.val()))) {
    // Call Ziptastic for information
    $.ajax({
    url: '{% url 'autostate' %}',
    cache: false,
    dataType: "json",
    type: "GET",
    success: function(result, success) {
    $(".Inputstate").val(result.state_short);
    },
    });
    }
    });
    </script>

标签: htmljquerydjango

解决方案


推荐阅读