Django管理员添加表单ajax调用

时间:2012-05-03 04:00:30

标签: python ajax django django-admin django-views

所以我以前在Django / Ajax / Jquery上取得了成功,但我想知道我是否可以在管理控制台中完成它。当用户转到“添加新”表单时,我希望他们填写邮政编码并根据该邮政编码,根据我在数据库中对应该邮政编码的值过滤下一个字段中的可用选项码。

我正在尝试查找管理员视图,该视图处理该表单的POST,但我对django相对较新,并且遇到了麻烦。也许我正在思考这个并且有一个更简单的解决方案?

2 个答案:

答案 0 :(得分:4)

  1. 创建一个视图,给定一个邮政编码,responds with a json list可用选项(python)
  2. Override the admin template ,用于包含邮政编码字段的模型(模板)
  3. 添加监听器到邮政编码的keyupchange事件,queries the view并使用响应过滤下一个字段(javascript)

答案 1 :(得分:1)

urls.py

from django.conf.urls import url

app_name = 'your_app'
urlpatterns = [
    url(r'^query/page/(?P<otherModelSlug>[a-zA-Z0-9]+)/?', PageYouQueryFrom.as_view(), name='query_page'),
    …
    # yourWebsite.com/your_app/util/kittens
    url(r'^util/(?P<fieldValue>[a-zA-Z0-9]+)/?', GetDataUtilitly.as_view(), name='get_data_util'),
]

data_template.html

{{result_html}}

page_you_want_to_ajax.html

{% extends "base.html" %}

{% block script-inline %}  
  $(document).ready( function () {
    $("#place_to_query").change(function() {
      var queryURL = "/your_app/util/" + $(this).val();
      queryBox = $(this)
      $.get({
        url: queryURL,
        contentType: "application/x-www-form-urlencoded",
      })
        .done(function( data ) {
          html = $( data ).text()
          queryBox.parent().after(html)
        });
    });
  });
{% endblock script-inline %}

{% block content %}
  {{ otherModel }} <!-- or it could be a specific  field -->
  <input id="place_to_query"></input>
  <!-- The ajax will go here afterwards-->
{% endblock content %}

主视图-PageYouQueryFrom.py

# this is a Class Based View, but you can use a function based one too
class PageYouQueryFrom(TemplateView):
    template_name = 'path/to/page_you_want_to_ajax.html'

    def get_context_data(self, **kwargs):
        context_data = super(PageYouQueryFrom, self).get_context_data(**kwargs)
        context_data['otherModel'] = get_object_or_404(OtherModel, slug=self.kwargs['otherModelSlug'])
        return context_data

数据查询视图-GetDataUtilitly.py

from django.views.generic import TemplateView
import requests
from pyquery import PyQuery

# this is a Class Based View, but you can use a function based one too
class GetDataUtilitly(TemplateView):
    template_name = 'path/to/data_template.html'
    def get_context_data(self, **kwargs):
        field_value = self.kwargs['fieldValue']
            page = requests.get('https://www.page.com?searchField=' + field_value)
            pq = PyQuery(page.content)
            # Get the (html) portion of what you want
            result_html = pq('div.c-table__row').html()
            return {'result_html': result_html}