Answer the question
In order to leave comments, you need to log in
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,)
class BookForm(forms.ModelForm):
class Meta:
model = Book
fields = '__all__'
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()
???
{% 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
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')
$.ajax({
method: 'post',
url: your-url,
data: serialized-data
}).done(function(response){
console.log(response.data)
});
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 questionAsk a Question
731 491 924 answers to any question