how to use ajax function to send form without page getting refreshed, what am I missing?Do I have to use rest-framework for this?

后端 未结 11 2211
花落未央
花落未央 2021-01-05 03:37

I\'m trying to send my comment form using ajax, right now when user inserts a comment then whole page gets refreshed. I want this to be inserted nicely without page getting

11条回答
  •  时光取名叫无心
    2021-01-05 04:30

    For the sake of example, I would like to show how to achieve this using Django REST Framework and how much code you DON'T need to change.

    TL;DR

    Installing DRF doesn't break anything. Just add 8 lines of code (without imports), change 2 existing lines and get rid of your entire comment_create_view.

    For those who are interested in more details, please read further.

    1. Install django-rest-framework using this guide.

    2. Create a serializers.py file with the following contents

    class CommentSerializer(serializers.ModelSerializer):
        class Meta:
            model = Comment
            fields = '__all__'  # or specify the list of fields you want to be present
    

    Here you define the class that will serialize (transform a Comment model instance to a json object) and deserialize (inverse action of transforming a json object into a Comment instance) your comments.

    3. Add the following view to your views.py

    from rest_framework.generics import CreateAPIView
    class CommentCreateView(CreateAPIView):
        queryset = Comments.objects.all()
        serializer_class = CommentSerializer
    

    Note: These 4 lines of code actually substitute your whole comment_create_view.

    Here you define a generic view designed specifically for creation of objects. CreateAPIView will handle only POST requests and will use the CommentSerializer class to convert objects. A serializer class to Django REST framework is what a form class is to Django - it handles the validation of data and returns a response in form of json, or corresponding error messages (also in json) in case your data is not correct.

    4. Add the following to your main urls.py file

    url_patterns = [
        ...  # your urls here
        url(r'^api/v1/comments/$', CommentCreateView.as_view(), name='comments-list')
    ]
    

    Here you register your API view as a route to which you can send requests.

    5. Edit your ajax request

    $.ajax({
        type:'POST',
        url:'api/v1/comments/',  // switch to the API view url
        contentType: 'application/json',  // tell ajax to send it as `json` content
        data:{
          post_id:$('#post_id').val(),
          origin_path:$('#origin_path').val(),
          parent_id:$('#parent_id').val(),
          csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val()
        },
        success:function(json){
    

    You POST to the newly created API endpoint data in form of json and your serializer takes it and creates a Comment model instance from it that is saved to the database. In case you need some specific behavior while creating a Comment (or any other model) instance, you can override the .create() method of your CommentSerializer. For more details check the Django REST framework tutorial.

    6. Do whatever you need with the newly created comment

    This part applies to non Django REST framework scenarios as well. Once you've successfully created the comment, in your success function you will receive it in json form and depending on what you want to do with it, you need to define the desired behavior in this success function.

    Basically that's it. Please take into account that the example described here is a minimal required code to make it work for you. I've used the out-of-the-box Django REST framework features, but of course it has many more possibilities to make things work. Maybe you'll need to override some default methods, but in the end, because DRF is designed to deal with ajax calls, your code will be shorter and cleaner.

    Good luck!

提交回复
热议问题