Django 简明教程

Django - Ajax

Ajax 本质上是将技术组合在一起以减少页面加载次数。我们通常使用 Ajax 来方便最终用户体验。在 Django 中使用 Ajax 可以通过直接使用 Ajax 库,如 JQuery 或其他库来实现。假设您想要使用 JQuery,那么您需要下载并通过 Apache 或其他方式在服务器上提供该库。然后在您的模板中使用它,就像您在开发任何基于 Ajax 的应用程序时所做的那样。

Ajax essentially is a combination of technologies that are integrated together to reduce the number of page loads. We generally use Ajax to ease end-user experience. Using Ajax in Django can be done by directly using an Ajax library like JQuery or others. Let’s say you want to use JQuery, then you need to download and serve the library on your server through Apache or others. Then use it in your template, just like you might do while developing any Ajax-based application.

在 Django 中使用 Ajax 的另一种方式是使用 Django Ajax 框架。最常用的是 django-dajax,这是一个功能强大的工具,可以使用 Python 和几乎没有 JavaScript 源代码轻松且快速地开发 Web 应用程序中的异步演示逻辑。它支持四种最流行的 Ajax 框架:Prototype、jQuery、Dojo 和 MooTools。

Another way of using Ajax in Django is to use the Django Ajax framework. The most commonly used is django-dajax which is a powerful tool to easily and super-quickly develop asynchronous presentation logic in web applications, using Python and almost no JavaScript source code. It supports four of the most popular Ajax frameworks: Prototype, jQuery, Dojo and MooTools.

Using Django-dajax

首先要做的是安装 django-dajax。可以使用 easy_install 或 pip 完成此操作 −

First thing to do is to install django-dajax. This can be done using easy_install or pip −

$ pip install django_dajax
$ easy_install django_dajax

这将自动安装 django-dajaxice,这是 django-dajax 所需的。然后我们需要配置 dajax 和 dajaxice。

This will automatically install django-dajaxice, required by django-dajax. We then need to configure both dajax and dajaxice.

在 INSTALLED_APPS 选项中,在项目的 settings.py 中添加 dajax 和 dajaxice −

Add dajax and dajaxice in your project settings.py in INSTALLED_APPS option −

INSTALLED_APPS += (
   'dajaxice',
   'dajax'
)

确保在相同的 settings.py 文件中,您具有以下内容 −

Make sure in the same settings.py file, you have the following −

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 文件 −

Now go to the myapp/url.py file and make sure you have the following to set dajax URLs and to load dajax statics js files −

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(指无需刷新)来存储它。

Let us create a simple form based on our Dreamreal model to store it, using Ajax (means no refresh).

首先,我们需要在 myapp/form.py 中的 Dreamreal 表单。

At first, we need our Dreamreal form in myapp/form.py.

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。这就是我们的逻辑所在,这是我们放置保存我们的表单的函数的位置,然后返回弹出窗口 −

Then we need an ajax.py file in our application: myapp/ajax.py. That’s where is our logic, that’s where we put the function that will be saving our form then return the popup −

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 模板 −

Now let’s create the dreamreal.html template, which has our form −

<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 中添加与模板相对应的视图 −

Add the view that goes with the template in myapp/views.py −

def dreamreal(request):
   form = DreamrealForm()
   return render(request, 'dreamreal.html', locals())

在 myapp/urls.py 中添加相应的 URL −

Add the corresponding URL in myapp/urls.py −

url(r'^dreamreal/', 'dreamreal', name = 'dreamreal'),

现在让我们在我们的模板中添加 Ajax 工作必需的内容 −

Now let’s add the necessary in our template to make the Ajax work −

在文件的顶部添加 −

At the top of the file add −

{% load static %}
{% load dajaxice_templatetags %}

在 dreamreal.html 模板的 <head> 部分添加 −

And in the <head> section of our dreamreal.html template add −

我们为这个示例使用 JQuery 库,所以添加 −

We are using the JQuery library for this example, so add −

<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 函数 −

The Ajax function that will be called on click −

<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 静态文件都在您的静态目录下提供,请运行 −

Note that you need the “jquery-1.11.3.min.js” in your static files directory, and also the jquery.dajax.core.js. To make sure all dajax static files are served under your static directory, run −

$python manage.py collectstatic

Note − 有时 jquery.dajax.core.js 可能丢失了,如果遇到这种情况,只需下载源代码,并将该文件放入静态文件夹中即可。

Note − Sometimes the jquery.dajax.core.js can be missing, if that happens, just download the source and take that file and put it under your static folder.

访问 /myapp/dreamreal/ 后,您将看到以下屏幕 −

You will get to see the following screen, upon accessing /myapp/dreamreal/ −

using django dajax

提交后,您将会看到以下屏幕 −

On submit, you will get the following screen −

using django dajax response