N
N
nurzhannogerbek2017-08-14 13:14:39
Django
nurzhannogerbek, 2017-08-14 13:14:39

How to refresh a page via AJAX in DJANGO?

Hello! Please help me figure it out.
The page has a modal window with a form for adding a new book. After successfully adding a new book, you need to update the block with the list of books on the page via AJAX. How to implement this using CBV and tell me how the AJAX request should look right?
models.py:

class Book(models.Model):
    header = models.CharField(max_length=200, help_text='Заголовок', blank=False,)
    description = models.TextField(help_text='Описание', blank=False,)

forms.py:
class BookForm(forms.ModelForm):
    class Meta:
        model = Book
        fields = '__all__'

views.py:
class DashboardView(View):
    template_name = "dashboard.html"

    def get_context_data(self, **kwargs):
        context = super(DashboardView, self).get_context_data(**kwargs)
        context['books'] = Books.objects.all()

    def post(self, request):
        create_form = BookForm(request.POST)
        if create_form.is_valid():
            create_form.save()
            ???

dashboard.html:
{% include ''books.html' %}

<div id="bookCreateModalBox" class="modal fade">
    <div class="modal-body">
        <form action="" method="post">
            {% csrf_token %}
            {{ create_form.as_p }}
            <input type="submit" value="">
        </form>
    </div>
</div>

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
tema_sun, 2017-08-14
@nurzhannogerbek

In the view:

def post(self, request):
        create_form = BookForm(request.POST)
        if create_form.is_valid():
            create_form.save()
            
        response = {"data": "goes here"}

        return HttpResponse(json.dumps(response), content_type='application/json')

In js:
$.ajax({
    method: 'post',
    url: your-url,
    data:  serialized-data
}).done(function(response){
    console.log(response.data)
});

Well, or something similar if you don't use jquery.

A
Alexey Ovdienko, 2017-08-14
@doubledare

You get serialized objects via Ajax and re-insert them at the front. It's ideal to use something like Vue for such a task, but for you it may be difficult and unnecessary.
After the payday - deserialize the objects and stupidly insert jquery into the list where you need it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question