Home > database >  Add posts on the frontend in real time Django
Add posts on the frontend in real time Django

Time:08-04

I am looking for a way to add real-time posts to my Django blog. I would like to use a way to make them appear on the database as soon as I insert them, without refresh and without a setInterval or the like. Some idea?

CodePudding user response:

You can do that by setting up a simple CRUD API with the Django Rest Framework and then interacting with it from the page using a set of JavaScript asynchronous functions to create, edit, delete, etc.

The JavaScript would run in the background and make changes in real time to the page without the need for refreshing it.

This is the principle at the base of single-page applications. I have personally implemented stuff like this more than a few times but I find that it's not always a great idea, especially if you plan for your website to grow a lot. This type of JavaScript becomes really hard to maintain in almost no time.

If this is your personal project and you want to play around with it it's fine. If you plan to have other people work on it after you, it's going to become increasingly expensive as other developers will need time to decipher the tightly coupled relationship between your HTML and JavaScript.

CodePudding user response:

Not quite sure what you mean.

But if you want to post some data to the server without refreshing the page I'd do this with an AJAX call.

On the Django side I would make a view, where you will receive POST data, save it the database and return JsonResponse (you can use this to return error or success messages).

On the frontend I'd create a function that prevents postinging to the server event.stopPropagation(). Then using something like axios to POST the data to the above mentioned view and after receiving the response from the server updating the page content with JS (DOM manipulation) to display the new content and hide or disable the form (depends on how you already have this implemented).

You can also implement full CRUD API with something like Django Rest Framework. This is a bit more work, but it will enable you to separate the frontend from the backend 100%.

  • Related