I want to thanks you for the amazing tutorial. Thanks to you, I was able to have a better understanding on how to attach both Django and JS together which I didn't know before. Also, for those who wish to understand the problem that occurs at 30:35. I believe the reason the event listeners aren't working is because the wrapper.innerHTML is creating a whole new string each time it iterates through the for loop. When you create a whole new string, you lose the reference to all the previous event listeners that you have added because wrapper.innerHTML has been rewritten entirely again (it created an entire new string). A good example to compare would be creating a variable inside a for loop and the variable overwriting itself on each for loop. Now, as to why only the last button ends working, it's because on the last iteration of the for loop. You apply an 'addEventListener' to the last index [i] of wrapper.innerHTML and there isn't another iteration afterwards that would overwrite wrapper.innerHTML. To avoid creating a new string on each iteration (which can slow down the performance if a string gets too big and it has to copy itself over and over again). I learned the method 'insertAdjancentHTML' doesn't create a whole new string through each iteration, instead it injects (or inserts) the new html directly into the original html which is like 100 times faster. The solution at 31:12 would be to replace: wrapper.innerHTML += item to wrapper.insertAdjacentHTML('beforeend', item) Like below: var list = data for (var i in list) { var item = `
${list[i].title}
Edit
-
`
wrapper.insertAdjacentHTML('beforeend', item) // Inside the element, insert after its last child. var editBtn = document.getElementsByClassName('edit')[i]; editBtn.addEventListener('click', function() { editItem() })
Thanks a lot for the explanation! Won my upvote, kind sir. Nonetheless, any idea why JavaScript behaves like this? You mention "wrapper.innerHTML is creating a whole new string each time it iterates through the for loop:... but that line of code (ie: "wrapper.innerHTML += item") is using the '+=' operator... so shouldn't it be equivalent to "wrapper.innerHTML = wrapper.innerHTML + item" -> meaning that you first get the initial (previous) value and then add something to it? Thus one SHOULD NOT lose the reference to the variable? (ie: the reference to everything that you built so far & stored in the variable...) - this behavior is kinda unintuitive... but I feel I might be losing some fundamentals of JS..
@@munteanionut3993 No problem! It has to do with how innerHTML treats values as a string and strings in javascript are immutable. What this means is that each time you try to edit a string in js, it has to create a whole new object to store the new value. Since now you have a whole new object with your new data, all previous references are lost and the garbage collector will be clearing those variables from memory since they are now unreachable. Simple code example: // Initializes text with a new string object. var text = ""; for (randomText in listOfText) { // Each loop, the variable text is getting assigned a new string object // because strings in js are immutable and therefore to edit its content // it has to create a new object to accommodate with its new changes. // // Therefore, each time we make any edits to the variable text, a new string object is created // and the previous object reference of text is no longer accessible (since the variable is getting overwritten by a new object) // and now the js garbage collector is free to clear that data from memory since is unreachable. text += randomText ; } Hope this explanation is helpful!
The year is 2023, and the javascript error with editbtn and the for loop, has been moderated. Now the original code works fine now. `for(let i in list){let editbtn = document.getElementsByClassName('edit')[i] editBtn.addEventListener('click', function(){ editItem(list[i]); }` works fine now in Javascript. Big fan of your videos Dennis! Much love from Nigeria
I can't thank you enough for the quality content you make. These videos definitively deserve a lot more views and likes. You just got a subscriber. Cheers mate.
This was so cool. I didn't know much at all about webdev going into this, but it was still easy to follow and now I feel like I'll be able to use the django rest framework for the backend of my android app
Dennis Ivy, I wanted to tell you that you are doing amazing work with your tutorial! Tell me if you got any blogs or your own tutorial website! Can't get enough of your brilliant contents. Keep the good work! Thank you very much
At 53:45, instead of writing out a for loop just for 1 element, you can just remove the last extra element with document.getElementById(`data-row-${list_snapshot.length - 1}`).remove();
Hi Dennis. That was explosive. Thanks very much. I have a quick question. Why did you use POST method for Update instead of a PUT method? I am just curious.
At 31:00, you're creating a variable within a loop. If you do that the variable you've created would be deleted or overwritten in the next iteration. So each time the loop was looping, the variable was getting overwritten like second was overwritting first, third overwritting second ... sixth overwritting fifth and that's why you were left with the last one. Instead you could've created the variable outside the for loop and could've appended the data. That way you could've avoided the second for loop.
Thank you for this amazing tutorial, I have a better understanding of DRF now. There is an alternative solution for CSRF token that is: let csrftoken = document.querySelector('input[name="csrfmiddlewaretoken"]').value; then send this to the fetch header.
Dennis, I learn a lot from you but i have a question. For only an webapp (no mobile) is then only Django a good idee or advise you also to use django rest framework with react or Vue. And why should you use react over vue?
That's a good question. Django REST framework can be used for several reasons. 1. You want to build a mobile app or use something like React or Vue to render templates. Or maybe you just want to render via vanilla JS 2. You want to provide your data to others in JSON format and want to give them the ability to work with it. These are just a few reasons but ultimately if you just want to build a webapp and don't have a clear reason to use react or view then you do NOT need Django REST framework. To my understanding Vue is more light weight and easier to understand than react but I don't know enough to have a preference :)
what is the use of making rest framework in the backend if we can do all the CRUD operation from django-admin panel. Are both different? please reply to me .
This is a comment made by the creator. just re sharing. hope it answers ! That's a very practical question :) You technically don't need to use REST but its a common practice today because lots of websites use frameworks such as React and Angular or just use Javascript to render data. This is common because of AJAX lets us make our websites more dynamic and allows us to load/re-render data without reloading the page each time. A perfect example would be when we add or delete an item. Because of our API we are able to make a call to the database and re-render our list without ever needing to reload the page. Hope that makes sense :)
Simple to follow and love for all your training series. After following the edit event handler from you, I came up with the following idea for the delete buttons. //Adding event handler for all delete buttons buildList for loop let deleteCollection = Array.from( document.getElementsByClassName("delete") ); for (let i = 0; i < deleteCollection.length; i++) { deleteCollection[i].addEventListener("click", deleteItem); } //Delete Method function deleteItem(e) { e.preventDefault(); let url = `${baseURL}task-delete/${e.target.dataset.id}`; fetch(url, { method: "DELETE", headers: { "Content-type": "application/json", "X-CSRFToken": csrftoken } }).then(response => { document .getElementById("list-wrapper") .removeChild(e.target.parentElement.parentElement); }); }
**Question @33:41**: Do you think it's a good idea to use the Jquery Event Handler Attachment function (on)? I used it in the for-each call and it appears to bind the right data for each button to its respective event-listener.
Hi, Dennis I'm facing a problem "Uncaught (in promise) TypeError: Cannot read property 'addEventListener' of undefined". I followed everything what you have explained. Still, I'm facing this issue. At 31:52.
Hi Dennis! Great tutorial as always the best explanation on youtube. But I have a question, that confuses me a little. Why we use JS at all, why we don't do this with python if we already have the backend there? Is this like standard, I mean without JS we cannot provide something to the view? Thank you!
JS is language of browser, if you want your website to be modern, dynamic you have to implement JS. You can use django without JS at all but the aesthetic of web will not as good as
I have the same question, I guess in real world apps you would make your projects separate, like the api project hosted some where and HTML, JS project (React probably) hosted somewhere else.
16:40 - In my case, I had to made an amendment to what is line 127 on your screen at the time. I changed it to var list = data.results as my drf returns the number of objects and a bunch of other headers. I believe that you might have disabled that in your first video but I came straight here so if there is anyone out there wandering why they are getting errors, this maybe one of the reasons.
Hi guys, I keep getting the following error in the browser Console (via Chrome Dev Tools) at 13:15 when first running the builList() function Its supposed to list the entries from the api but I'm getting this error. Access to fetch at '127.0.0.1:8000/api/task-list/' from origin 'localhost:8000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. Any thoughts?
Hi Dennis! First of all I want to say thank you. You make really great content! Keep working like that :) I have also a couple of questions. Maybe you could give me some advices. I'm building a language learning app, kinda flashcards based app. I have users, each user should be able to add folders, each folder can consist multiple decks with flashcards, also some options like add tags or displaying infos about certain folder or deck etc. And such kind of dealing with creating/updating and displaying particular folders, decks and flashcards (and some extra options) is ideal to use AJAX, to not realoading the page etc, these are just some lists with extra pop-ups to display those extra infos. Is it a good option to use this kind of api? I need updating and getting data based of logged user, also want to use multiple models, some foreign keys, because I need for example display info about deck based of some data about flashcards etc. You also set some html in your javascript code, to generate items etc, but my content seems more complex, so is that good way to put that html in js code? If not, how can I generate some stuff based on what user is gonna do? Summarizing, what's a good way to deal with things that I want, with multiple models, and the models depend on each other and also generated view is more complex than just title or basic info (they consist for example extra pop-up, images etc)? Thanks for some advices :)
Hi Dennis! Question: why u write 'frontend.apps.FrontendConfig' instead of 'frontend' (app's name)? Thanks! Why do we need to write it so? Also, why we add 'rest_framework'? It is not an app as I understand..., or is it just a rule of thumb?
Hi Dennis, thank you for the great contents. I have learnt a lot from your videos. I am trying to follow this video too but I have no knowledge on Javasript, is it possible or should i learn javasript first ?
hi Dennis i have a issue, in min 22:40 when a submit a new item, it does duplicate my task but it dosent add my new item, i have no idea that's what happen ? javascript code var form = document.getElementById('form-wrapper') form.addEventListener('submit', function(e){ e.preventDefault() console.log('Form submitted') var url = '127.0.0.1:8000/api/task-create/' var title = document.getElementById('title').value fetch(url,{ method: 'POST', headers: { 'Content-type':'application/json', }, body:JSON.stringify({'title':title}) } ).then(function(response){ builList() }) })var form = document.getElementById('form-wrapper') form.addEventListener('submit', function(e){ e.preventDefault() console.log('Form submitted') var url = '127.0.0.1:8000/api/task-create/' var title = document.getElementById('title').value fetch(url,{ method: 'POST', headers: { 'Content-type':'application/json', }, body:JSON.stringify({'title':title}) } ).then(function(response){ builList() }) })
A little trick I did was to use Django template and secretly display the URL on the HTML and retrieve that URL with. You can get the full url path by using this: {{ request.build_absolute_uri }}{% url 'your URL name' %}
Hey @Dennis I want to show unique items like first todo for ID =1 on another URL like the api we built for unique items. Means only given id item to be displayed. is there a way we can do that? I know it's a bit confusing comment but I hope you get what I want to say. And any kind of help would be very kind of you.
Cool awesome tutorial hoping the knowledge from this will help in doing like a check box where I can select multiple element then edit all of it with just a single text and a click of a button
If anybody is having issues with No 'Access-Control-Allow-Origin' you have to install some middle-ware to fix it. Go here and follow the instructions: dzone.com/articles/how-to-fix-django-cors-error
for the strikethrough on items, i added this inside the build function and it did the trick. Using react for state management would make this so much more pleasurable!! - var strikeItemTitle = document.getElementById(`title-${i}`) if (list[i].completed === true) {strikeItemTitle.setAttribute("style", "text-decoration: line-through")} else { strikeItemTitle.removeAttribute("style")}
i got my rest Api created and perfectly functional but I do the post method Javascript using fetch() part and it's perfectly written and doesn't give me any errors but it DOES NOT get saved on the database sigh 😫... this ishhh is giving me a big headache...because something that's literally impossible is happening... the url I pass is the endpoint I have on my api for posting stuff (when I post stuff from the django rest framework interface it does work and gets saved) but does not get added on the database from the frontend interface using js... and I've written every single line of code as shown in the video.... the fuction submit does work and run from top to bottom, and zero errors reported... but it just does NOT get added on the database.. 🤷🏽♂️ 🤷🏽♂️ 🤷🏽♂️ No idea... I'm lost and confused and dissaponted asf
Yes you can build todo application using django a beautiful frontend using templates and logic in views nice and simple. but say today you built it and it's working great --- tomorrow you want to explore something else say react native (for andriod app ) and you want to create a todo application in it too now there are two ways to do that 1. create frontend and along with it write the logic for application functionality from scratch Or just create frontend in react native and reuse your well written backend of 'todo application' ( that you wrote for django app) as an api for this application too. so now there is only one backend but two applications 1. a webapp 2. a mobile app running on top of that using the api you had created --- speaking of DjangoRestFramework well it's just a recommended library for creating your api specifically designed to work with django --- you may use it or may just use django and create api without it that's upto you ---but if you do use it; it does provide nice features
Hello sir, I loved the way you deliver the content, although it is more for an intermediate coder/developer. But i have a question regarding this video: Why we have to show the similar json response in our frontend - JS console aalso while we are using that Django api framework to show the same responses. SIr please answer this question asap :'))
That's a very practical question :) You technically don't need to use REST but its a common practice today because lots of websites use frameworks such as React and Angular or just use Javascript to render data. This is common because of AJAX lets us make our websites more dynamic and allows us to load/re-render data without reloading the page each time. A perfect example would be when we add or delete an item. Because of our API we are able to make a call to the database and re-render our list without ever needing to reload the page. Hope that makes sense :)
hey! dennis, I didn't get the same item while clicking the edit button(with this part 👇) as you got, but pretty much i followed you everywhere.I have used custom http library using fetch and promises, that was the little change i did.But i don't think that, this should be problem solver in this case. ``` for(let i in list){ let editBtn = document.getElementsByClassName("edit-button")[i] editBtn.addEventListener('click', function(){ editItem(list[i].title); }) } ```
Hi Dennis! First of all thanks to you for this amazing tutorial. So, I think I was found the best solution for preventing the flash when we call buildlist(): code: data.forEach((el, ind) => { let title = `${el.title}` if (el.complete) { title = `${el.title}` } let item = `
Anyone point me to any similar videos to work within the structure of Django RESPT API + Javascript but to additionally integrate OpenAI's text completions to let's say, add a "Assist" button to send the ToDo list item title to OpenAI and to receive and display a response from OpenAI? Love your videos Dennis. Thank. you for your time.
Ali Arshad I used to help with technical things when I had the time but now days I’m lucky if I can get to a fraction of my emails/comments. So I guess the answer is I check my emails when I can but I rarely get to reply :/ Hope you understand.
For those who are waiting for Dennis's React TODO project with RESTApi. ... I have done the same project using Vue.js with DjangoRestapi.......link : github.com/Aasess/Django-RESTAPI-Vue.js
Another way to solve the event listener being added to only the last item. for (var i in list){ let editBtn = document.getElementsByClassName('edit')[i] let item = list[i] editBtn.addEventListener('click', function(){ editTask(item); console.log(item); }) }
Don't forget to check out my Complete Django course! dub.sh/NvGboTI
I want to thanks you for the amazing tutorial. Thanks to you, I was able to have a better understanding on how to attach both Django and JS together which I didn't know before.
Also, for those who wish to understand the problem that occurs at 30:35. I believe the reason the event listeners aren't working is because the wrapper.innerHTML is creating a whole new string each time it iterates through the for loop. When you create a whole new string, you lose the reference to all the previous event listeners that you have added because wrapper.innerHTML has been rewritten entirely again (it created an entire new string).
A good example to compare would be creating a variable inside a for loop and the variable overwriting itself on each for loop.
Now, as to why only the last button ends working, it's because on the last iteration of the for loop. You apply an 'addEventListener' to the last index [i] of wrapper.innerHTML and there isn't another iteration afterwards that would overwrite wrapper.innerHTML.
To avoid creating a new string on each iteration (which can slow down the performance if a string gets too big and it has to copy itself over and over again). I learned the method 'insertAdjancentHTML' doesn't create a whole new string through each iteration, instead it injects (or inserts) the new html directly into the original html which is like 100 times faster.
The solution at 31:12 would be to replace:
wrapper.innerHTML += item
to
wrapper.insertAdjacentHTML('beforeend', item)
Like below:
var list = data
for (var i in list) {
var item = `
${list[i].title}
Edit
-
`
wrapper.insertAdjacentHTML('beforeend', item) // Inside the element, insert after its last child.
var editBtn = document.getElementsByClassName('edit')[i];
editBtn.addEventListener('click', function() {
editItem()
})
thanks, this seems less lines of code and insertAdjacentHTML document states that it is more faster in operation
Thanks a lot for the explanation! Won my upvote, kind sir.
Nonetheless, any idea why JavaScript behaves like this? You mention "wrapper.innerHTML is creating a whole new string each time it iterates through the for loop:... but that line of code (ie: "wrapper.innerHTML += item") is using the '+=' operator... so shouldn't it be equivalent to "wrapper.innerHTML = wrapper.innerHTML + item" -> meaning that you first get the initial (previous) value and then add something to it? Thus one SHOULD NOT lose the reference to the variable? (ie: the reference to everything that you built so far & stored in the variable...) - this behavior is kinda unintuitive... but I feel I might be losing some fundamentals of JS..
@@munteanionut3993 No problem! It has to do with how innerHTML treats values as a string and strings in javascript are immutable. What this means is that each time you try to edit a string in js, it has to create a whole new object to store the new value. Since now you have a whole new object with your new data, all previous references are lost and the garbage collector will be clearing those variables from memory since they are now unreachable.
Simple code example:
// Initializes text with a new string object.
var text = "";
for (randomText in listOfText) {
// Each loop, the variable text is getting assigned a new string object
// because strings in js are immutable and therefore to edit its content
// it has to create a new object to accommodate with its new changes.
//
// Therefore, each time we make any edits to the variable text, a new string object is created
// and the previous object reference of text is no longer accessible (since the variable is getting overwritten by a new object)
// and now the js garbage collector is free to clear that data from memory since is unreachable.
text += randomText ;
}
Hope this explanation is helpful!
@@imsKo yes, it is! Thank you!
Thank you, this works perfectly
The year is 2023, and the javascript error with editbtn and the for loop, has been moderated. Now the original code works fine now. `for(let i in list){let editbtn = document.getElementsByClassName('edit')[i] editBtn.addEventListener('click', function(){ editItem(list[i]); }` works fine now in Javascript. Big fan of your videos Dennis! Much love from Nigeria
I can't thank you enough for the quality content you make. These videos definitively deserve a lot more views and likes. You just got a subscriber. Cheers mate.
I liked the video before I watch it.
Thanks for your consistency and regularity Dennis
I appreciate you Ryan! Thanks for your support :)
I like his videos before watching them too. I am assured of the quality. Thank you Dennis
Your videos are mad good, you somehow always upload what I need, and after watching your explanations I can always start to work off of them.
Thank you for creating same project in Django without Rest Framework, Django with Rest Framework and React+Django. It helped a lot.
This was so cool. I didn't know much at all about webdev going into this, but it was still easy to follow and now I feel like I'll be able to use the django rest framework for the backend of my android app
Waaooooooo! I admit that this is one of the best videos I have ever watched. Thanks very much Dennis Ivy
Look forward to watch that of React
I love how u try to fix the problems and keep going with the tutorial
Thank you so much @Dannis for this session, I just now completed this, growing my skills from here...
What a way to say good morning to me. Thank you Denis
Hope you like this one :)
@@DennisIvy Always
Dennis Ivy, I wanted to tell you that you are doing amazing work with your tutorial! Tell me if you got any blogs or your own tutorial website! Can't get enough of your brilliant contents. Keep the good work! Thank you very much
Something that I really wanted! You are doing a great job :) Thank you for this content.
Am loving this. I am gonna start implementing javaScript and react to my channel. Thanks, Dennis
At 53:45, instead of writing out a for loop just for 1 element, you can just remove the last extra element with
document.getElementById(`data-row-${list_snapshot.length - 1}`).remove();
Love your django tuts
You just explain it perfectly.
Awesome content! Thank you so much dear. Please build more content.
Ma mann thank you, this tutorial is so good, dislikes are from haters.
I'm new to javascript! Is ajax is also covered in the video? I think only REST framework is covered. Or am I not understanding it properly?
34:36 you may use let instead of var to avoid the complicated nest function calls, but you would lose some backward compatibility with older browsers
Thank you for understable and compact lesson!
Hi Dennis. That was explosive. Thanks very much. I have a quick question. Why did you use POST method for Update instead of a PUT method? I am just curious.
I am curious too, though I made mine function with the PUT method, don't want story in the future 😅😅
i think he just made a mistake or forgot it.
At 31:00, you're creating a variable within a loop. If you do that the variable you've created would be deleted or overwritten in the next iteration. So each time the loop was looping, the variable was getting overwritten like second was overwritting first, third overwritting second ... sixth overwritting fifth and that's why you were left with the last one. Instead you could've created the variable outside the for loop and could've appended the data. That way you could've avoided the second for loop.
Thank you for this amazing tutorial, I have a better understanding of DRF now.
There is an alternative solution for CSRF token that is:
let csrftoken = document.querySelector('input[name="csrfmiddlewaretoken"]').value;
then send this to the fetch header.
Great Explanation as Before
Dennis,
I learn a lot from you but i have a question.
For only an webapp (no mobile) is then only Django a good idee or advise you also to use django rest framework with react or Vue.
And why should you use react over vue?
That's a good question. Django REST framework can be used for several reasons.
1. You want to build a mobile app or use something like React or Vue to render templates. Or maybe you just want to render via vanilla JS
2. You want to provide your data to others in JSON format and want to give them the ability to work with it.
These are just a few reasons but ultimately if you just want to build a webapp and don't have a clear reason to use react or view then you do NOT need Django REST framework.
To my understanding Vue is more light weight and easier to understand than react but I don't know enough to have a preference :)
wow ...Thanks a lot for this awesome content!
Hey man, i love your tutorials. Keep up the good work!
By the way, the issue at 32:12 can be solved by using "let i" instead of "var i"
Yes, because of the previous iteration the value for "i" remains the last value. Thus it was only accessing the last element of the list.
Thanks man you helps me alot to complete my tasks
what is the use of making rest framework in the backend if we can do all the CRUD operation from django-admin panel. Are both different? please reply to me .
This is a comment made by the creator. just re sharing. hope it answers !
That's a very practical question :) You technically don't need to use REST but its a common practice today because lots of websites use frameworks such as React and Angular or just use Javascript to render data. This is common because of AJAX lets us make our websites more dynamic and allows us to load/re-render data without reloading the page each time.
A perfect example would be when we add or delete an item. Because of our API we are able to make a call to the database and re-render our list without ever needing to reload the page. Hope that makes sense :)
Simple to follow and love for all your training series. After following the edit event handler from you, I came up with the following idea for the delete buttons.
//Adding event handler for all delete buttons buildList for loop
let deleteCollection = Array.from(
document.getElementsByClassName("delete")
);
for (let i = 0; i < deleteCollection.length; i++) {
deleteCollection[i].addEventListener("click", deleteItem);
}
//Delete Method
function deleteItem(e) {
e.preventDefault();
let url = `${baseURL}task-delete/${e.target.dataset.id}`;
fetch(url, {
method: "DELETE",
headers: {
"Content-type": "application/json",
"X-CSRFToken": csrftoken
}
}).then(response => {
document
.getElementById("list-wrapper")
.removeChild(e.target.parentElement.parentElement);
});
}
**Question @33:41**: Do you think it's a good idea to use the Jquery Event Handler Attachment function (on)? I used it in the for-each call and it appears to bind the right data for each button to its respective event-listener.
Hi, Dennis I'm facing a problem "Uncaught (in promise) TypeError: Cannot read property 'addEventListener' of undefined". I followed everything what you have explained. Still, I'm facing this issue. At 31:52.
Love your work
Thank you :)
Денис, это шикарно! Спасибо огромное)
Пожалуйста :)
Он крут
@@Dante-fk4yi О, я не один такой с комментами на русском) Он крут не то слово!!!
@@MrYoklmn Нас много)
I had another idea on the editItem part: put an inline onclick function and pass the current item id as a parameter.
Thanks, learned a lot. Opened a pull request ;P Consider looking into it.
Hi Dennis!
Great tutorial as always the best explanation on youtube. But I have a question, that confuses me a little. Why we use JS at all, why we don't do this with python if we already have the backend there? Is this like standard, I mean without JS we cannot provide something to the view?
Thank you!
JS is language of browser, if you want your website to be modern, dynamic you have to implement JS. You can use django without JS at all but the aesthetic of web will not as good as
I have the same question, I guess in real world apps you would make your projects separate, like the api project hosted some where and HTML, JS project (React probably) hosted somewhere else.
Thank you for your wonderful lesson!!!
Awesome. Thank u so much Dennis.
16:40 - In my case, I had to made an amendment to what is line 127 on your screen at the time. I changed it to
var list = data.results
as my drf returns the number of objects and a bunch of other headers. I believe that you might have disabled that in your first video but I came straight here so if there is anyone out there wandering why they are getting errors, this maybe one of the reasons.
Hi guys,
I keep getting the following error in the browser Console (via Chrome Dev Tools) at 13:15 when first running the builList() function
Its supposed to list the entries from the api but I'm getting this error.
Access to fetch at '127.0.0.1:8000/api/task-list/' from origin 'localhost:8000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
Any thoughts?
I am having the same issue also
you need to install and use django-cors-headers
github.com/adamchainz/django-cors-headers
Here's a video on how to deal with this issue:
ruclips.net/video/EY6HhmGDLsg/видео.html&feature=emb_logo
Hi Dennis, you have another Django todo app video on your channel. is it totally different from that one?
Hi Dennis! First of all I want to say thank you. You make really great content! Keep working like that :)
I have also a couple of questions. Maybe you could give me some advices. I'm building a language learning app, kinda flashcards based app.
I have users, each user should be able to add folders, each folder can consist multiple decks with flashcards, also some options like add tags or displaying infos about certain folder or deck etc. And such kind of dealing with creating/updating and displaying particular folders, decks and flashcards (and some extra options) is ideal to use AJAX, to not realoading the page etc, these are just some lists with extra pop-ups to display those extra infos. Is it a good option to use this kind of api? I need updating and getting data based of logged user, also want to use multiple models, some foreign keys, because I need for example display info about deck based of some data about flashcards etc.
You also set some html in your javascript code, to generate items etc, but my content seems more complex, so is that good way to put that html in js code? If not, how can I generate some stuff based on what user is gonna do?
Summarizing, what's a good way to deal with things that I want, with multiple models, and the models depend on each other and also generated view is more complex than just title or basic info (they consist for example extra pop-up, images etc)?
Thanks for some advices :)
Денис ты крутой чувак , даже лучше чем Хауди Хо
Awesome man! Love it
Hi Dennis! Question: why u write 'frontend.apps.FrontendConfig' instead of 'frontend' (app's name)? Thanks! Why do we need to write it so? Also, why we add 'rest_framework'? It is not an app as I understand..., or is it just a rule of thumb?
Hi Dennis, thank you for the great contents. I have learnt a lot from your videos.
I am trying to follow this video too but I have no knowledge on Javasript, is it possible or should i learn javasript first ?
anyone reading this i will answer by myself, yes you do need to know javascript. thnk you!
Excellent work, Also hope a tutorial "schedule request" (celery)with drf and build a aweome series with
drf
Thanks for the recommendation :)
thank's a lot, u'v rockd it at all
This is a great video
hi Dennis i have a issue, in min 22:40 when a submit a new item, it does duplicate my task but it dosent add my new item, i have no idea that's what happen ?
javascript code
var form = document.getElementById('form-wrapper')
form.addEventListener('submit', function(e){
e.preventDefault()
console.log('Form submitted')
var url = '127.0.0.1:8000/api/task-create/'
var title = document.getElementById('title').value
fetch(url,{
method: 'POST',
headers: {
'Content-type':'application/json',
},
body:JSON.stringify({'title':title})
}
).then(function(response){
builList()
})
})var form = document.getElementById('form-wrapper')
form.addEventListener('submit', function(e){
e.preventDefault()
console.log('Form submitted')
var url = '127.0.0.1:8000/api/task-create/'
var title = document.getElementById('title').value
fetch(url,{
method: 'POST',
headers: {
'Content-type':'application/json',
},
body:JSON.stringify({'title':title})
}
).then(function(response){
builList()
})
})
img source
imgur.com/a/4FxDP8J
Thank you Dennis!
Thank you very much!!! useful tutorial....
Great tutorial...can you please suggest how to use dynamic url instead?
A little trick I did was to use Django template and secretly display the URL on the HTML and retrieve that URL with. You can get the full url path by using this: {{ request.build_absolute_uri }}{% url 'your URL name' %}
Sorry, use this instead: {{ request.META.HTTP_HOST }}
Thanks for your helpful tutorial videos. Hope you have a series combination of django and react (native)
Hey @Dennis I want to show unique items like first todo for ID =1 on another URL like the api we built for unique items.
Means only given id item to be displayed. is there a way we can do that? I know it's a bit confusing comment but I hope you get what I want to say. And any kind of help would be very kind of you.
One word for you, 'Genius'.
Hello Dennis, this is an amazing video but I have a question when I send request, that error occurred "Unsupported media type"
Cool awesome tutorial hoping the knowledge from this will help in doing like a check box where I can select multiple element then edit all of it with just a single text and a click of a button
What if I wanna deploy the api app only and use my endpoints in another website uploaded on some other platform like netlify?
If anybody is having issues with No 'Access-Control-Allow-Origin' you have to install some middle-ware to fix it. Go here and follow the instructions: dzone.com/articles/how-to-fix-django-cors-error
thanks a lot! worked like a charm! you should be higher in the comments list : D
Your comment saved me, thank you so much^^
for the strikethrough on items, i added this inside the build function and it did the trick. Using react for state management would make this so much more pleasurable!! -
var strikeItemTitle = document.getElementById(`title-${i}`)
if (list[i].completed === true) {strikeItemTitle.setAttribute("style", "text-decoration: line-through")} else { strikeItemTitle.removeAttribute("style")}
why on minute 32 you dindt just do : Edit?
i got my rest Api created and perfectly functional but I do the post method Javascript using fetch() part and it's perfectly written and doesn't give me any errors but it DOES NOT get saved on the database sigh 😫... this ishhh is giving me a big headache...because something that's literally impossible is happening... the url I pass is the endpoint I have on my api for posting stuff (when I post stuff from the django rest framework interface it does work and gets saved) but does not get added on the database from the frontend interface using js... and I've written every single line of code as shown in the video.... the fuction submit does work and run from top to bottom, and zero errors reported... but it just does NOT get added on the database.. 🤷🏽♂️ 🤷🏽♂️ 🤷🏽♂️ No idea... I'm lost and confused and dissaponted asf
Why are we using the rest framework and api. When we can build a todo site with only django.. can anyone tell me the difference ?
Yes you can build todo application using django a beautiful frontend using templates and logic in views nice and simple.
but say today you built it and it's working great --- tomorrow you want to explore something else say react native (for andriod app ) and you want to create a todo application in it too
now there are two ways to do that
1. create frontend and along with it write the logic for application functionality from scratch
Or just create frontend in react native and reuse your well written backend of 'todo application' ( that you wrote for django app) as an api for this application too.
so now there is only one backend but two applications
1. a webapp
2. a mobile app running on top of that using the api you had created ---
speaking of DjangoRestFramework well it's just a recommended library for creating your api specifically designed to work with django --- you may use it or may just use django and create api without it that's upto you ---but if you do use it; it does provide nice features
Hello sir, I loved the way you deliver the content, although it is more for an intermediate coder/developer.
But i have a question regarding this video:
Why we have to show the similar json response in our frontend - JS console aalso while we are using that Django api framework to show the same responses.
SIr please answer this question asap :'))
You use the django api to comunicate with the Database, JS to communicate with Browser
hello sir, won't u continue this series? this is awesome series. please add more videos about this. thanks
Awesome. Thank u so much
:)
when i try to update the task a new task is added to the list. I can't figured the mistake what i done, can anyone help me !
Thanks for sharing... We won't forget to subscribe.
Appreciate it :)
what are the benefits of using this over a react Django rest type architecture?
awesome,I love it
Why do you need to have rest why not use Django only. Its a noob question but i just wanna know
That's a very practical question :) You technically don't need to use REST but its a common practice today because lots of websites use frameworks such as React and Angular or just use Javascript to render data. This is common because of AJAX lets us make our websites more dynamic and allows us to load/re-render data without reloading the page each time.
A perfect example would be when we add or delete an item. Because of our API we are able to make a call to the database and re-render our list without ever needing to reload the page. Hope that makes sense :)
I was looking for django videos series, number 13, but I couldn't find it
That one was supposed to be pagination but I had to skip it due to time constraints. I'll get it added soon :)
@@DennisIvy thanks, I'll be waiting for that, Blessings
Hi Dennis nice video, will you make a tutorial on consuming this API with VueJS ?
Thanks for the good tutorial. However what you did with the edit and delete event listeners was very poorly explained.
hey! dennis,
I didn't get the same item while clicking the edit button(with this part 👇) as you got, but pretty much i followed you everywhere.I have used custom http library using fetch and promises, that was the little change i did.But i don't think that, this should be problem solver in this case.
```
for(let i in list){
let editBtn = document.getElementsByClassName("edit-button")[i]
editBtn.addEventListener('click', function(){
editItem(list[i].title);
})
}
```
thanks ! good info
Very thank you!
Excellent videotutorial
01/08/2020
thank you so much sir
sir, can you please tell me where the JAVASCRIPT code is?
Hi Dennis! First of all thanks to you for this amazing tutorial. So, I think I was found the best solution for preventing the flash when we call buildlist():
code:
data.forEach((el, ind) => {
let title = `${el.title}`
if (el.complete) {
title = `${el.title}`
}
let item = `
${title}
Edit
Delete
`
html += item;
});
wrapper.innerHTML = html;
Amazing
How can we do auto reload page in django,so that you don't have to do reload manually?
When you say "auto reload page" i presume you mean re-render data? If not, why might you want to reload the page?
@@DennisIvyI guess he's talking about django channels/web sockets or if it is in react's term then obviously re rendering component.
he is probably talking about live server extension of VSC but it doesn't work with django
@@Jobin-at-CodingOutright yeah might be 😄
Thank you very much
Anyone point me to any similar videos to work within the structure of Django RESPT API + Javascript but to additionally integrate OpenAI's text completions to let's say, add a "Assist" button to send the ToDo list item title to OpenAI and to receive and display a response from OpenAI?
Love your videos Dennis. Thank. you for your time.
I have a quick question. If we are stuck or need to ask you some thing is there any way to send you a message ?
Ali Arshad I used to help with technical things when I had the time but now days I’m lucky if I can get to a fraction of my emails/comments.
So I guess the answer is I check my emails when I can but I rarely get to reply :/
Hope you understand.
@@DennisIvy okay thanks buddy yes i can understand you situation. Keep up the good work :-)
Thank you!
Why you didnt use the jinja2 in html?
THE BEST
For those who are waiting for Dennis's React TODO project with RESTApi. ... I have done the same project using Vue.js with DjangoRestapi.......link : github.com/Aasess/Django-RESTAPI-Vue.js
Where have you uploaded your templates?
And the static?
You don’t need to create a folder « frontend » within your templates folder
Another way to solve the event listener being added to only the last item.
for (var i in list){
let editBtn = document.getElementsByClassName('edit')[i]
let item = list[i]
editBtn.addEventListener('click', function(){
editTask(item);
console.log(item);
})
}
Thank you !!!
my create function worked but i didnt submit my csrf token can anyone explain why?
you need to update this with the latest js