上一节:

  Django - AJAX

  • 简述

    Ajax 本质上是一种技术组合,它们集成在一起以减少页面加载次数。我们通常使用 Ajax 来简化最终用户体验。在 Django 中使用 Ajax 可以通过直接使用 Ajax 库(如 JQuery 或其他库)来完成。假设您想使用 JQuery,那么您需要通过 Apache 或其他方式在您的服务器上下载并提供该库。然后在您的模板中使用它,就像您在开发任何基于 Ajax 的应用程序时可能会做的那样。
    在 Django 中使用 Ajax 的另一种方法是使用 Django Ajax 框架。最常用的是 django-dajax,它是一个强大的工具,可以轻松、超快速地在 Web 应用程序中开发异步表示逻辑,使用 Python,几乎不需要 JavaScript 源代码。它支持四种最流行的 Ajax 框架:Prototype、jQuery、Dojo 和 MooTools。
  • 使用 Django-dajax

    首先要做的是安装 django-dajax。这可以使用 easy_install 或 pip 来完成 -
    
    $ pip install django_dajax
    $ easy_install django_dajax
    
    这将自动安装 django-dajax 所需的 django-dajaxice。然后我们需要配置 dajax 和 dajaxice。
    在 INSTALLED_APPS 选项的项目 settings.py 中添加 dajax 和 dajaxice -
    
    INSTALLED_APPS += (
       'dajaxice',
       'dajax'
    )
    
    确保在相同的 settings.py 文件中,您具有以下内容 -
    
    TEMPLATE_LOADERS = (
       'django.template.loaders.filesystem.Loader',
       'django.template.loaders.app_directories.Loader',
       'django.template.loaders.eggs.Loader',
    )
    TEMPLATE_CONTEXT_PROCESSORS = (
       'django.contrib.auth.context_processors.auth',
       'django.core.context_processors.debug',
       'django.core.context_processors.i18n',
       'django.core.context_processors.media',
       'django.core.context_processors.static',
       'django.core.context_processors.request',
       'django.contrib.messages.context_processors.messages'
    )
    STATICFILES_FINDERS = (
       'django.contrib.staticfiles.finders.FileSystemFinder',
       'django.contrib.staticfiles.finders.AppDirectoriesFinder',
       'dajaxice.finders.DajaxiceFinder',
    )
    DAJAXICE_MEDIA_PREFIX = 'dajaxice'
    
    现在转到 myapp/url.py 文件并确保您具有以下设置 dajax URL 和加载 dajax 静态 js 文件 -
    
    from dajaxice.core import dajaxice_autodiscover, dajaxice_config
    from django.contrib.staticfiles.urls import staticfiles_urlpatterns
    from django.conf import settings
    Then dajax urls:
    urlpatterns += patterns('',
       url(r'^%s/' % settings.DAJAXICE_MEDIA_PREFIX, include('dajaxice.urls')),)
       
    urlpatterns += staticfiles_urlpatterns()
    
    让我们基于我们的 Dreamreal 模型创建一个简单的表单来存储它,使用 Ajax(意味着不刷新)。
    首先,我们需要 myapp/form.py 中的 Dreamreal 表单。
    
    class DreamrealForm(forms.Form):
       website = forms.CharField(max_length = 100)
       name = forms.CharField(max_length = 100)
       phonenumber = forms.CharField(max_length = 50)
       email = forms.CharField(max_length = 100)
    
    然后我们需要在我们的应用程序中创建一个 ajax.py 文件:myapp/ajax.py。这就是我们的逻辑,这就是我们放置将保存我们的表单然后返回弹出窗口的函数的地方 -
    
    from dajaxice.utils import deserialize_form
    from myapp.form import DreamrealForm
    from dajax.core import Dajax
    from myapp.models import Dreamreal
    @dajaxice_register
    def send_form(request, form):
       dajax = Dajax()
       form = DreamrealForm(deserialize_form(form))
       
       if form.is_valid():
          dajax.remove_css_class('#my_form input', 'error')
          dr = Dreamreal()
          dr.website = form.cleaned_data.get('website')
          dr.name = form.cleaned_data.get('name')
          dr.phonenumber = form.cleaned_data.get('phonenumber')
          dr.save()
          
          dajax.alert("Dreamreal Entry %s was successfully saved." % 
             form.cleaned_data.get('name'))
       else:
          dajax.remove_css_class('#my_form input', 'error')
          for error in form.errors:
             dajax.add_css_class('#id_%s' % error, 'error')
             
       return dajax.json()
    
    现在让我们创建 Dreamreal.html 模板,它有我们的表单 -
    
    <html>
       <head></head>
       <body>
       
          <form action = "" method = "post" id = "my_form" accept-charset = "utf-8">
             {{ form.as_p }}
             <p><input type = "button" value = "Send" onclick = "send_form();"></p>
          </form>
          
       </body>
    </html>
    
    在 myapp/views.py 中添加模板附带的视图 -
    
    def dreamreal(request):
       form = DreamrealForm()
       return render(request, 'dreamreal.html', locals())
    
    在 myapp/urls.py 中添加相应的 URL -
    
    url(r'^dreamreal/', 'dreamreal', name = 'dreamreal'),
    
    现在让我们在模板中添加必要的内容以使 Ajax 工作 -
    在文件顶部添加 -
    
    {% load static %}
    {% load dajaxice_templatetags %}
    
    在我们的 dreamreal.html 模板的 <head> 部分添加 -
    我们在这个例子中使用了 JQuery 库,所以添加 -
    
    <script src = "{% static '/static/jquery-1.11.3.min.js' %}" 
       type = "text/javascript" charset = "utf-8"></script>
    <script src = "{% static '/static/dajax/jquery.dajax.core.js' %}"></script>
    
    单击时将调用的 Ajax 函数 -
    
    <script>
       function send_form(){
          Dajaxice.myapp.send_form(Dajax.process,{'form':$('#my_form').serialize(true)});
       }
    </script>
    
    请注意,您需要静态文件目录中的“jquery-1.11.3.min.js”,以及 jquery.dajax.core.js。要确保所有 dajax 静态文件都在您的静态目录下提供,请运行 -
    
    $python manage.py collectstatic
    
    注意- 有时 jquery.dajax.core.js 可能会丢失,如果发生这种情况,只需下载源代码并获取该文件并将其放在您的静态文件夹下。
    访问 /myapp/dreamreal/ 后,您将看到以下屏幕 -
    使用 Django-dajax
    提交后,您将看到以下屏幕 -
    使用 Django-dajax 响应
上一节: