使用基于类的视图和 ajax 的 Django 应用程序?

发布于 2024-12-14 12:34:50 字数 166 浏览 1 评论 0原文

我正在学习 Django,发现了基于类的视图,我想知道如何在这些视图上实现 Ajax。

我在 github 上搜索了一个 django 项目,发现一些使用基于类的视图,但没有使用 ajax。

那么...有人知道使用这两种东西的开源项目吗?这样学习起来更容易。

谢谢 :)

I'm learning Django and I found class-based views and I wonder how to implement Ajax on those views.

I searched github for a django project and I found some using class-based views but not ajax.

So... Anybody knows an open source project that use both things? It easier to learn that way.

Thank you :)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

黎歌 2024-12-21 12:34:50

不使用流行的 dajaxic 和 dajax 包,它仍然是一件简单的事情。

编写一个装饰器来包装 django 的 is_ajax() 函数来请求对象会有所帮助,如下所示:

def ajax_request(function):
    def wrapper(request, *args, **kwargs):
        if not request.is_ajax():
            return render_to_response('error/ajax_required.html', {},
                context_instance=RequestContext(request))
        else:
            return function(request, *args, **kwargs)
    return wrapper

假设有一个名为 ajax_required 的模板来处理这个特定的失败。如果您不想要这样的内容,则可以阻止用户在浏览器中输入您的 ajax 特定 url。

因为它的示例较短,所以下面是一个基于类的 ajax 视图,用于呈现模板。

from django.views.generic.base import TemplateView

class AjaxGeneral(TemplateView):
    template_name= None
    def get(self, request):
        data={}
        return render_to_response(self.template_name, data,
            context_instance=RequestContext(request))

    @method_decorator(ajax_request)
    def dispatch(self, *args, **kwargs):
        return super(AjaxGeneral, self).dispatch(*args, **kwargs)

现在,对于只需要渲染 html 片段的所有 ajax,您可以定义基于类的简短视图,例如:

class ShowSomeTable(AjaxGeneral):
    template_name="some_table.html"

假设 some_table.html 中有一些 html 片段。

现在,该视图的 urls.py 条目将如下所示:

url(r'showtable/

您可以像平常一样在 js 中调用它:

$(#dynamic-content).load('/showtable');
, ShowSomeTable.as_view()),

您可以像平常一样在 js 中调用它:

without using the popular dajaxic and dajax packages, its still a straightforward affair.

It would help to write a decorator that just wraps around django's is_ajax() function for request objects like so:

def ajax_request(function):
    def wrapper(request, *args, **kwargs):
        if not request.is_ajax():
            return render_to_response('error/ajax_required.html', {},
                context_instance=RequestContext(request))
        else:
            return function(request, *args, **kwargs)
    return wrapper

assuming there is a template called ajax_required to handle this particular failure. Something like this prevents a user from entering your ajax specific url in the browser if thats what you don't want.

Because it makes for a shorter example, the following is a class based ajax view that renders a template.

from django.views.generic.base import TemplateView

class AjaxGeneral(TemplateView):
    template_name= None
    def get(self, request):
        data={}
        return render_to_response(self.template_name, data,
            context_instance=RequestContext(request))

    @method_decorator(ajax_request)
    def dispatch(self, *args, **kwargs):
        return super(AjaxGeneral, self).dispatch(*args, **kwargs)

now for everything ajax that just needs to render an html snippet you can define short class based views like:

class ShowSomeTable(AjaxGeneral):
    template_name="some_table.html"

Assuming some_table.html has some html snippet in it.

Now your urls.py entry for this view will look like:

url(r'showtable/

and you can call it in the js as normal like:

$(#dynamic-content).load('/showtable');
, ShowSomeTable.as_view()),

and you can call it in the js as normal like:

无人问我粥可暖 2024-12-21 12:34:50

ajax 视图与普通视图没有太大区别,只是您通常希望在处理普通请求时返回不同的格式。这种格式通常是 JSON。

该文档有一个可用于返回 JSON 的 mixin 示例,因此这是一个很好的起点:

https://docs.djangoproject.com/en/dev/topics/class-based-views/mixins/#more-than-just-html

你想要你的view回复普通请求还是只处理AJAX请求?如果是前者,唯一的技巧是在 render_to_response 方法中写入一个小检查以拒绝任何正常的 GET 请求。如果是后者,上面的链接将继续讨论一种情况,您可以创建一个视图来处理 ajax 请求和普通请求。

An ajax view isn't much different to a normal view except that you usually want to return a different format then when processing a normal request. This format is usually JSON.

The documentation has an example of a mixin that can be used to return JSON, so this is a good starting point:

https://docs.djangoproject.com/en/dev/topics/class-based-views/mixins/#more-than-just-html

Do you want your view to reply to normal requests or only deal with AJAX requests? If the former, the only trick would be to write in a small check in the render_to_response method to reject any normal GET requests. If the latter, the above link goes on to discuss a situation where you can create a view that will deal with ajax requests and with normal requests.

千里故人稀 2024-12-21 12:34:50

如果您想同时支持 AJAX 和传统视图,您可以在 CreateView 中添加类似的内容:

# at top of file
from django.http import JsonResponse  

# inside CreateView class
def render_to_response(self, context, **response_kwargs):
    """ Allow AJAX requests to be handled more gracefully """
    if self.request.is_ajax():
        return JsonResponse('Success',safe=False, **response_kwargs)
    else:
        return super(CreateView,self).render_to_response(context, **response_kwargs)

这通常会处理常规视图(使用重定向等),但对于 AJAX,它会返回 JsonResponse。在返回“成功”的地方,您可能想要添加更复杂的逻辑,但这是基本思想。

If you want to support both AJAX and traditional views, you can add something like this to your CreateView:

# at top of file
from django.http import JsonResponse  

# inside CreateView class
def render_to_response(self, context, **response_kwargs):
    """ Allow AJAX requests to be handled more gracefully """
    if self.request.is_ajax():
        return JsonResponse('Success',safe=False, **response_kwargs)
    else:
        return super(CreateView,self).render_to_response(context, **response_kwargs)

This handles regular views normally (with redirect etc.) but for AJAX, it return a JsonResponse instead. Where it returns 'Success', you may want to add more sophisticated logic but this is the basic idea.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文