a better way to do ajax in django

后端 未结 4 1597
情歌与酒
情歌与酒 2020-12-25 08:51

The other day I wrote some AJAX for a Django app that i have been working on.

I come from Ruby on Rails, so I haven\'t done much in the way of raw JS.

So bas

4条回答
  •  无人及你
    2020-12-25 09:45

    It kinda depends what you want to do I think. Ajax being quite a wide range of scenarios from Google Maps to a simple auto-complete varys greatly in complexity and the best approach.

    However, there are some useful things you can do that help.

    1) Template level

    Make sure you have "django.core.context_processors.request" in your TEMPLATE_CONTEXT_PROCESSORS setting. Then you can do this;

    {% if not request.is_ajax %}
    
      
      ...
      
      
      ...
    {% endif %}
    actual content
    {% if not request.is_ajax %}
    
    
    {% endif %}
    

    Basically then say this page is /test/ you can do a browser request and get the full content or a request via JavaScript and just get the content. There is a blogpost somewhere that explains this in more detail but I can't find it at the moment.

    2) In the view

    In the template we are just accessing the request object in the template. In the view you can do very similar things.

    def my_view(request):
        if requst.is_ajax():
            # handle for Ajax requests
    
        # otherwise handle 'normal' requests
        return HttpResponse('Hello world')
    

    The above methods don't really do it differently than you do but allow you to re-use views and write it bit more concisely. I wouldn't really say what you are doing is wrong or hacky but you could write it to make it more concise and re-use the templates and views.

    say for example you could have just one template and if its a Ajax request have it only return the section that will need to be updated. In your case it would be the tables views.

提交回复
热议问题