Python Django Tutorial | Learn Python Django In 3 Hours | Python Web Development | Edureka

Hello everyone. My name is Aayushi and I welcome you all tothis Django Full Course Session. Now, I know many of you will beexcited just by its name. But before we actually getour hands on it, let’s see What’s our agenda for today. So we’ll start of the session by having a quickintroduction to Python. And why do we need it? We’ll also have a lookat the various libraries that python offers and why Django is so importantWe will also have a look at the Django features and architecture. Now Django offers an MVCand MVT architecture, which basically meansmodel view controller and model view template. Then we move forward and learn the prerequisites tolearn Django and will also see how to install Django. Then comesthe most exciting part that is how to create a websitefrom the scratch. Now this will includeboth your content as well as backing now, we also see how do you connectdatabases with the project and will alsotest the application? Moving ahead.We’ll see theDjango rest framework. And how do you createa simple apis using Django moving headwill also see some dos and don’ts and some frequentlyasked questions regarding Django and finally I wrap upthe session by discussing some of the important Djangointerview questions and answers. So I hope you guys are clearwith the agenda. So let’s begin also, don’t forget to subscribe to anyvehicle YouTube channel and hit the Bell icon to stay updated. Thank you. We shall first begin witha small introduction to python followed by the differentweb development Frameworks that are available in Python. Then we shall take a lookat what exactly is Django and the features of it following that we should take a deep lookat the architecture of Django followedby its installation and then I’ll be showingyou all how to create your own website from scratch.Finally. I’ll be coveringa few Django interview questions before winding up. Okay. So without any further delays, let’s get started python as we all know is a high-levelinterpreted programming language created by Guido van Rossum in One it’s a greatgeneral purpose language capable of creating anything from desktop softwareto web applications and Frameworks talkingabout web applications in particular python allows you to dynamically buildweb applications grants East to buildmulti-protocol networks provides quick processing letsyou build more functions with fewer lines of code. And the best of all, you don’t usuallymess up using python unlike other languages apart from that python alsoprovides a number of web development librariessuch as cherry pie Django web 2 pi pyramid turbo gas flaskEtc talking about Django.It’s a high-level python webdevelopment framework that encourages rapid developmentand clean pragmatic design. Django is an opensource web framework, which was namedafter Django Reinhardt. It follows the principleof don’t repeat yourself as the name saysthe principal is all about keeping the code simpleand non-repeating Django is also a high level mvt architect. Stands on the model view template Django alongwith python is used by many of the top companies such asGoogle YouTube Dropbox Etc.Now the reason why all these companiesmake use of python along with Django is because ofthe remarkable features that Django provides. Now, the reason whythese companies make use of python along with Django is because of the key features ofDjango Django is extremely fast and encourages rapid developmentwith a clean pragmatic design. Like I’ve already mentioned before it’s freeand open source, which helps developersto complete their app as fast as possible apart from its speed Django also providesa huge number of packages that help you developyour websites faster and easier. It is also highly secureand scalable last but not the leastDjango is versatile, which allows youto build any sort of web application you desire. So now let’s move on and take a look atthe Django architecture Django follows the MVC mvtarchitecture MVC actually. Stands for model viewcontroller it is used for developing web applications where we break the codeinto three different segments namely module View and the controller a modelis basically used for storing and maintaining your data.It is the back end where the databaseis defined a view is all about the presentation and it is not at all awareof the back end. So basically whateverthe user sees on a webpage is returned by the viewscomponent the controller on the other hand isof business logic which will interactwith the model and the view now talking about the MV t or the model viewtemplate structure in the MVC architecture. There’s a predefined templatefor the user interface. For example, say you want towrite several static HTML forms, like hello user 1 hello user doand so on with template you’d be having only one filethat prints hello along with the variable name. Now this variablewill be substituted in that particular templateusing some ginger logic.That’s the magic of template you don’t needto Add the goat again and again in case of mvt Django itself takescare of the controller. The controller is inbuilt into Django and youdon’t have to bother about it. So taking a deeper lookat what we were talking about before so basicallya template is a front end which will interactwith the views and the model will be usedas the backend the viewers basically acts as both the model and the templatesand Maps it to the URL after that Django playsthe role of controller and serves it to the user. So given this I’m sureyou have a brief idea about what is Djangoand it’s architecture. So now let’s move on and see what are the prerequisitesrequired to learn Django. The first thing that you’ll have to know isthe oops Concepts this is because we’d becreating many classes objects sub classes Etc. Also, you’ll have to know how to use the Pythonprogramming language SQL queries html/css Etc in case you havedifficulties with any of these you can check outErica’s YouTube channel and the blog series which will Only helpyou so moving on.I’ll be showing you allhow to install Django on your systems. Okay. So one thing I wantyou all to note is that I’ll be using pycharm. You can use any IDof your choice, but personally I feel pycharm isthe best for creating websites. So the first thing you’ll haveto do is download python on your PC’s to do that. You can go to the officialpython web site. Go to downloadsand select any version that suitable for your PC’sand select the installer that is suitablewith your operating system.Once you’ve downloaded python, you’ll have to goto the jet planes website to download pycharm on your PC’sso after downloading python, so after you’re donewith the setup go to the advanced system settings. Choose the optionof environment variables and over here in the systemvariables choose the new Option and type python underscorehome now to enter the value of this variable. You’ll have to look for the part where you have installed pythonon your PC’s to do that. You can simply type pythonin the search bar. Right click on itand open the file location after this simply copythe path and enter it as the value of this variablethen click on OK. So after you’ve donethat select the path variable that’s present selectthe path variable and towards the end of it. If you don’t see a semicolon add a semicolon and withintwo percentage symbols, as you can see over herewrite python underscore home once this is done clickon OK So now to download pycharm on your PC’s simplyType download pycharm.And then you can download it from the official jetbrainswebsite select the version that’s suitable for your OSand you can choose between the professionaland the community version where the professional version is paid and the communityversion is free. So after you’re donewith the pycharm installation complete the setupand open pycharm on your PC’s since I already haveit downloaded on my PC. I’ll just open pycharm. So once you’re donewith the setup, you will be seeing something similar to what you see on thescreen when you open up pycharm. I’ve already createda project over here. However, if you want to createa project click on file and select new project, it will ask you to entersome name just give some name of your choice and hitthe create button.Okay. So after creating a projectopen up the terminal and type whip install Django. So when you’re installing Django along with DjangoSQL parse data base and the PYT said module alsogets installed SQL parse is actually an on validatingSQL parser for python. It provides supportfor passing splitting and formatting SQL statements. Now, this is actuallycompatible with versions of python from 2.7. The pyd said module brings the Olsen teaserdatabase into python, this Library allows accurate and cross-platformtime zone calculations using python 2.4 and higherit also solves the issue of ambiguous times at the endof daylight saving time. However, this Librarydiffers a little from the documented python API for tea set infor implementations. So now comingback towards Django. Once the installationis completed. You will see a message sayingsuccessfully installed Django and the version of Django.Now to cross verify if Django has beensuccessfully installed go to the command prompt. And type python -em Django – – version. So as you can see when you type this command itReturns the version of Django that’s been installed. So now going back to pycharm. I’ll be showing you allhow to create a Django project to create a new project. You’ll have to make useof the Django admin to do that type Django – admin start project followedby the name of the project. You can give any nameof your choice guys. I’ll just name it as website. I’ve made a spelling mistake. I’ve missed in from Django. So now my projecthas been created and as a CD into my project so CDand the name of the project, which is website. So now I’m in the project that I’ve created with the helpof the Django admin to see what the Django adminhas created for you within this project clickon the project directory.So as you all can seeon the screen the Django admin has created a numberof files for us. The outer website root directoryis just a container for your projectthe name however does not matter to Django and you can name it asanything you like after that the very important filethat Django creates for you is the managedot py file the managed of py file does the samething as Django admin but takes careof a few things for you.It puts your projects packageon system path. It sets the Django settingsmodule environment variable so that it points to yourproject settings dot py file. Next is the in its dot py file. This is an empty filebut tells python but this directory should beconsidered as a python package. A package is a way of structuring pythonsmodule name Space by using dotted module names the in it dot py filesare required to make python treat directoriescontaining the file as packages. This prevents directorieswith a common name unintentionally hidingvalid modules to occur later on the module search path in the simplest case in it’snot py can just be an empty file but it can also executeinitialization code for the package followedby that is the settings not py file this file actuallyconsists of the settings or the configurationsfor this Django project. The Django settings dot py filecontains all the configurations for your Django installation.It’s basically justa python module with module level variables because the settings fileis a python module. It does not allowpython syntax errors. It does not allowfor python syntax errors, and it can assignsettings dynamically using normal python syntax. It can also importvalues from other. Files so now let’s take a lookat the URLs dot py file. Let me just clear these commentsthe URLs dot py file consists of all the URL declarationsfor the Django project. It is basically like a table of contentsof your Django part site. So basically when a userrequests for page from a Django path sitethis file determines which python code to execute Django determines the rootURL conf module to use loads that python module and looksfor the variable URL patterns. So this should actually bea part of the URLs instances Django then runs througheach URL pattern in order and stops at the first one that matches the requestto the URL.Once that is match DjangoImports and calls the given view which is a simple pythonfunction that returns to the user the pagethat he has requested. So now let me show you allthe wsgi file the wsgi done py file is an entry point forthe wsgi compatible web servers. So if your project wsgi actually stands forweb server Gateway interface, it is a specificationthat describes how a web server communicateswith a web applications and how the web applicationscan be chained together to process one request. So now I hope you have a clearidea about what these files are.And what is the purpose ofcreating them now to make sure that your project is runningsimply type python manage that py run server. Sorry, I forgot to givea space over here. Okay, so as you can seewhen I hit this command, it has returneda URL for me now. Let me show you all what happenswhen I click on this URL. So congratulations guys, when you see this rocket,which is ready to take off. It means you’ve installedDjango successfully without crashing your systems. So now I’ll get back to pycharm and show you allhow to create an app. Ok. So now let’s get back to pycharmthe development server. However will be running unlessand until you press control C in the terminal all the changes that you maketo your project will be seen on the development server justby refreshing the page. Therefore, you don’t haveto type python manage that py command each timeat this point of time. I want you all to knowthe difference between a website and a web application a web siteis actually a bigger domain that contains different webapplications a web application is a part of a website if you’re callinga website your website is basically the main project which contains many otherweb applications in it.So whenever you visitany website, it consists of different applications that are joined togetherto make one complete website. The application is basicallyA sub part of that website which has a specifictask and app is basically a web application that does something a project on the other handcan maintain multiple apps and an app can bein multiple projects. Okay. So now to create an app, I’ll go back to my terminal hitcontrol C and then type python – 2py startapp followedby the name of the app.You can give any nameof your choice. I’ll just name itas technical courses. Sorry guys, I’ve givena space by mistake. So now my app technical courseshas been created. Now. When I go back to our projectI can see over here that my app technical courseshas been created. When you open this youcan find the Django has created many other files againfor us the apps file which consists of a class forall the installed apps models, which I’ve already explainedto you all before a test start py file and the views file.So now let me runmy server again. So one thing I wantto all to note is that Django already knows that each website will havean admin section to access that you can simply type slashand then hit admin. So when I type admit over here, you can see that it’s throwingan error now this is because we have notcreated any admin. I just came to this pageto show you guys that this page actually existsand it’s already created and the settings for it havealready been created by Django.So now let’s get backto our home page. So my first bitof code for my website, I’ll be writingin the views file. So when you open the views file, you can see the Djangohas already imported render, but for this case are not beusing the render method. I’ll be using the HTTPresponse method instead. So to do that,I’ll type from Django dot http. Import HTTP response boththe lines are not highlighted because I’m not making use of those functionsanywhere in my program. So to define a newfunction in Python, you’ll have to make useof the d e f keyword after that.You’ll have to specify some namefor your function in my case. I’ll just name it as courses and within this I’ll passthe request function as a parameter Now All I Want by function to do isto return a message saying that this is my homepage to do that. I’ll just write return and I’ll be usingthe HTTP response function of here and thenI’ll just give an H1 tag. Sorry. I have to specify thiswithin quotes and I’ll write this is my home page.So now the views componentis ready to display this message on my homepage. But to make this function return what I want I’ll have to connect this view start py fileto the URLs to py file which is present in my project. So to connect the viewsnot py file which is present in my app to the URLs that py file which is presentin the project. I’ll have to create another URLsthat py file within my app. Now this is donebecause I do not want to mess up with the originalURLs to py file which is present in my project. So in case you havea number of URLs and apps to be returnedthe original URL start py file present in my projectcan get too cluttered and that becomes messyand to avoid that. I’m going to createanother URL start py file within my app, which is alsothe conventional method.So now this URL stuff py fileis very much similar to the URLs that py file which is presentwithin my project. So all I’m going to do within the newlycreated URL start py file in my app directory isto import the path function from Django dot URLs. So from Django dot URLs,I’ll import the path function. So now for the URL pattern, I’ll just copy thisand I’ll paste it in the URL statpy file of my app and I’ll just deletethis admin URL and I’ll leave this blank now. I’m leaving this blank because I want this functionto be returned on my homepage. Okay. So now what you have to do is specify the viewstaught courses function within the URLs dot py filepresent in your app to do this. Just type views dot nameof the function, which is courses in my case followed bythe name of your page. You can give any nameof your choice. I’ll just name it as home page.Now as you can see, I’ve added the functionpresent in the views file in the URL path, but I’ll have to specify from where this function hasto be taken to do that. I’m going to importthe views function present in this directory. And for that I’ll typefrom dot import views now getting back to the URL startpy file present in my project. I’ll have to includethe path of my home page. So I’ll createanother path function and within this I’ll specifyan empty string and then use the include function and specify what I want toinclude over here.So basically I wantto import this file which is technical courses /URLs dot p y, so I’m going to specifythat as technical courses. Dottie Waddles after thisI’ll just close this function and close the path function. Okay. So one thing I don’t know if youguys have noticed I’ve made use of the include function, but I’ve notimported this function. This function has to be importedfrom Django dot URLs. So to import that functionaljust right comma include so now I’ll get back tothe development server and see what is returns. Congratulations guys this timeinstead of seeing the rocket that was ready to be launched. My website isdisplaying the message that I wanted to display. So now your websiteis ready to be launched. Okay, so our websiteis executing very well, but I want toshow y’all something that’s displayed as a messagefor me in the terminal. So as you can see it saysyou have 17 unapplied migrations and it says your projectmay not work properly until you applythe migrations for the apps.Now, this is basicallyto notify you that your app or your projecthas not been connected to the database. So coming back to the projectdirectory over here. You see something calledas the dpd sqlite3. So this is basicallythe default database that is installedalong with Django the settings for this databaseare already included in the settings dot py file. So let me just clearthe comments of here. And within the settingsdot py file, I’ll just look for databases. So as you can see over here, the default database sqlite3has already been installed for us by Django. However, if you wish to use any other database install theappropriate database bindings and change the keys in thedatabases default item to match a database connection settings.However, for a detailedinformation on this you can check outthe original documentation where you’ll find allthe details required for the settings of the databaseyou prefer to use in addition to databases. The settings don’t py file also has installed apps now to showy’all what that exactly is. So basically Django dotcontributed admin is the admin site Django dotconducted admin is for the admin site wat is for the authenticationsystem content type is basically a framework for the contenttypes sessions is for a session framework messagesfor a messaging framework. And static files is a frameworkfor managing the static files. So now to connect my projectto the database. I’ll hit control Z againin my terminal and over here.I’ll type the command python -. P y migrate. So now I run my serveragain and show you what a displaced this time. So as you can see unlikebefore I have got a message saying system checkidentified no issues. So this means our projecthas been connected to the database successfully. Now what exactlyhappens over here is the migrate command looksat the installed apps settings and creates any necessarydatabase tables according to the database settingsin your settings to py file. Then the database migrationsare shipped with the app.So now that my projecthas been connected to the database. The next thing that I’m going to do iscreate models for my website. So to create models, I’ll go to the models to py filewhich is already created for me by Django. I’ll clear this commentof here and as you can see it has alreadyimported models for me. So within this file over here, I’ll be creating two classes where the first classwill be the all courses class and it’s going to holdthe name of the course and the instructorsname to do that. I’ll just type class. And give the name as all coursesyou can give any name of your choice guys. Now within thisI’ll just write models. dot module Now like I’ve alreadytold you all within this class. I’m going to writethe name of the course and the name of the instructor.So for that I’ll just takea variable say course name and then I’ll specifythis two models dot since this is goingto be characters. I’ll use the function since this is goingto hold on the characters. I’m going to use the functioncare field and for the length of this I’ll just specify asmax length equal to anything say 200 after this. I’ll just writethe instructors name. So I’ll just take a variable sayins name and again over here. I’ll use the care field method. And I’ll give a max lengthof stay a hundred.Okay. So the first classhas been created now, I’ll create another class which is going to holdthe details of each course, so to do that, I’ll just type classand I’ll say details as the name of this function. So as many of you know, the course typesthat are available at Ed Eureka are either self-pacedor instructor-led. So I’ll createthe same over here. I’ll say self-paced. I’ll just say SP and over here. I’m going to dosomething very interesting. So before I do that, I’m going to createanother variable say course and using this variable. I’ll connect the subclass to the main class using theforeign key method to do that. I’ll just type modelsdot foreign key. And since this method is inheriting theall courses method, I’ll just type all coursesand then I’m going to use the on delete function. Now, you all might be wonderingwhy I’m using this function. Okay, I’ll just tell you that in a while and I’ll justtype models dirt Cascade. Okay, the purpose of using thison delete function over here is because in case I deleteany course present in all courses section, I want to delete the detailsof that function as well.So in case you haveany other website, we’re in it’s not necessaryto delete something present in the detail section. When you delete an objectof your main class, you may omit using the ondelete attribute So within this like I already told y’allI’m going to have two variables which is for the self-pacedand over here again, I’ll be making useof the Care field function. So to specify that I’ll just takea variable say SP and then I’ll use the samefunction again just to specify what is present in that course. Now the lengthof it can be changed according to your preferences. So in this case, I’ll just change it to 500 so that I can specify allthe topics the second type of course that’s available if the instructor-led courses so for that I’ll just takea variable say IL and again, I’ll be using the same function and I’ll changethe length to 5 hundred. Okay. So now I’ve createdmodels for my project. So basically each class that I’ve created overhere is a subclass of the Django dot DBdot models dot model.Each model has a numberof class variables both my classes havea few variables Each of which representsa database field in the model. Now, this field is actuallyrepresented by an instance of the field class. For example, the care field functionthat are used over here for characters thisbasically tells Django what’s type of dataeach field holds. So now talking aboutthe foreign key function that I’ve used over here. Now this function is actuallyused to define a relationship. So it basically Don’t jangle that each detail is relatedto a single course in addition to this the small bit of model code that we’ve writtenover here gives a lot of information with this Djangois actually able to create the database schema or the create tablestatements for this app. It also createsa python access API for accessing all coursesand the details classes. So now to tell Django that we’ve installedan app into our website. All we have to dois go to the settings to py file go to installthe apps and over here.You’ll have to specifythe name of your app which in my caseis technical courses. Dutch apps go to the apps fileover here and from here take the class name and paste itin the settings dot py file where you’re creating the appand paste it over here after this just closethe inverted commas and do not forgetto specify the comma now, we’ve told Django that it has to includethe technical courses app after this you’ll haveto run another command. So I’ll just returnthe control back to my terminal and I’ll use the commandpython managed at py make migrations and the nameof my app python manage that py make migrationsand the name of my app.It has thrown an error. It says type errorin the Cascade function. So I’ll just get back to models. Oh here it is. I’ve not specifiedany attributes to this. So I’ll just removethis from here. So I’ll just clearthe brackets save this come back to my terminal. So here it is make migrationsbasically tells Django that you’ve madesome changes to the models and the Django should store these changes as a migrationmigrations are basically how Django storeschanges to your models after this you’ll have to usethe SQL migrate command that takes migration namesand returns their SQL. So all you have to do is usePython managed py SQL migrate and specified this IDwhich is present over here. So it’s not not not one. So just type the sameand hit enter. I forgot to specifythe name of my project. I’ll just specify the nameof my project over here.So as you can see, the table namesare automatically generated by combining the name of the app and the lowercase nameof the module. Also, the primary keysare added automatically now. All you have to do is runthe my great again to create a model table in your database. So here I’ll type pythonmanaged rpy and migrate. So now the migrate commandtakes all the migrations that haven’t been applied and runs them againstyour database migrations are very powerful guys.And this actually letsyou to change your models over time as in how yourequire to develop your project because of this you do not haveto delete your database or tables and make new ones. The reason that there areseparate commands to make and apply migrations is because you’ll commit migrationsto your version control system and ship them to your app. They not only makeyour development easier. They’re also usableby other developers and in the production. So now that my database is set. I’m going to jump onto the interactivepython shell to make use of the free API Djangohas given me to open the shell you can simply type the pythonmanage dot py shell command in the terminal or inthe command prompt of your system. So I’ll just open up the commandprompt again and over here. The first thingthat I’m going to do is get into the directorywhere I’m creating my project so to do that, I’ll just CDinto pycharm projects. Flash Django full course, I’ll get into my websiteproject and hit enter. Okay now I’ll just typein the command python managed py and I’ll specify shell and I’ll use the shell command.Now I’m doing thisbecause it’s easy for y’all to see what exactly I’m doingwith the database. The first thing that I’ll haveto do is import the classes that I’ve createdin my models file. So for that I’ll just usefrom the name of my app, which is technical courses. Dot models. I want to import the classes that I’ve createdwhich is courses and details. Let me look backinto the name again so that I don’t makeany mistakes it was models and just close this. It’s not courses. It’s all courses. And details so before movingon let me just show you all what is presentin the all courses set. So to do that, I’ll just have to type allcourses dot objects dot all so as you can see over here. It has returnedthat my set is empty. Naturally. It has to return an empty setbecause of not added anything to the courses class yet nowto add something to this class.I’m going to takea variable say a and then I’m goingto take the name and then I writethe name of the class, which is all courses. Now within that I’ll haveto specify the course name and the instructor name since these arethe two variables that I’ve createdwithin my class now to do that. I’ll just get backto the shell and I’ll have to write the course name. Let me just cross checkthe name again. So it’s course nameand ins name? So course name. I’ll just saythe course name is python. Followed by the name of theinstructor sew ins name equals. I’ll just take some random namesay XYZ after this. I’ll have to make useof the save function to save this to the database. Now in case I want to printout the name of the course, I’ll just have to usea DOT course name and hit enter.So as you can see when I remove the course nameof a it has returned that the course nameof this is python. So now in case I wantto add in more courses, I’ll just take another variablesay be I’ll copy this. And for the course name, I’ll just name it as Java andfor the instructor name, I’ll just say ABCafter this just like before I’ll have to save it. So I’ll say B dot save hit enter and now just to show y’allwhat is present within P.I’ll use B dot coursename and hit enter. So as you can seewhen I used a DOT course name, I got Python and when Iused B dot course name, I got Java as my outputnow one more thing. I want you guys to know isDjango is going to assign some primary keyto both these courses. So in case I want to retrievethe ID for Python and Java, all I have to do is hit a DOT IDor a DOT PK hit enter. So as you can seewhen I hit a DOT ID, it has returnedthe primary key for python. Now, you have another optionover here in place of ID. You can also make use of PK which will returnthe same result. Let me just show that to you all so I’ll justuse B dot PK and hit enter. So as you can seethe primary key of B is 2 and the primary key of A is 1 so now let me showyou all what is present within the database usingthe All function.So I’ll just rerunthe command I’ve used earlier which is all courses taughtobjects dot all hit enter. So now our set is not empty, but you can seethat it has a return something specifying the primary keysfor both my courses, but this is not exactlyvery clear now to have a clear output. I’ll just get backto my models file and I’ll make a small changewithin the classes that I’ve created over here. An override the Str function and then the default parameterfor every python class. So now if you havea doubt of why self has been added over here, you’ll have to remember guys that whenever you’re creatinga function within the class, you will have to specifythe self parameter. Unlike Java in Python. It’s compulsory to specifythe self parameter. So now all I wanted to returnis the name of the function. So I’ll just sayreturn self dot course name. I’ll do the same withinthe details class as well.I’m for the details class. I’ll just returnthe self-paced course for now. So having added this Str method. Let me just tell you that it is very importantto add this not only for your own convenience when dealing withthe interactive prompt, but also because objectsrepresentations are used throughout Django’sautomatically generated. Admin save these changesget back to your shell and now I’ll just exit this. I’ll type python managed or pyI’ll get into my shell again using python managedat py Shell command. And after that I’m goingto run the previously used function again, that is all coursestaught objects dot all. Oh sorry guys, I forgotto import the functions. So first I’ll have to import and then I’ll haveto retrieve it. It has not returned the nameof the course again seems like I’ve made some mistakes. I’ll just get backto the modules file here. It is insteadof a double underscore. I’ve used the triple underscoreand since I copied that of here, let me remove that save this getback to my shell exit this one.And then I’m going to hitthe Bison managed to achieve I shall command again. Import my classes and then I’ll use all coursestaught objects at all. Okay. So there it is instead of returning the primary keyof both these courses. It has now returnedthe name of the courses, which I wanted it to returnnot just this guy’s you can actually filterout anything you want from the database to do that. You can make useof the filter command. So for that you’ll use all courses taughtobjects dot filter and within this I’ll justspecify the parameter as ID equal to 1 I’ll hit enter.So as you can seeI’ve specified the ID as one and it has filtered out Pythonand return the same similarly. You can also make useof the get method to do that just specify get and within thatI’ll say ID equal to 2. So now the get method has itreturned Java as the name of the course having ID to okay so till now we’ve been seeing how to add and filter itemsfrom the database now, I’ll get back to my pie. And show y’all how you can actually workwith the admin to do that open up the adminfile present in the pap. Now for this. I’ll just open upthe terminal and over here.I’ll just type the commandpython managed to py create super user createsuper user is one word. So just be careful guys. So python manage dot py createsuper user So the first thing is going to ask you isto enter a username. I’ll just enter the usernameas editor acre and hit enter after this. It will ask you to entersome email address. You can specifyany email address since this is justa test project. I’ll just say Eddie Rekhaat the rate gmail.com. After this, it will askyou to enter some password. I’ll just I’ll just usesome password say ABCD. I’ll give some passwordof my choice.You can give any passwordof your choice guys. Once I’ve entered that I haveto re-enter the password. So now once the super userhas been created you will see this message saying superuser created successfully now, all you have to dois run your server again and for that you’ll have to makeuse of the Python managed to py run server command. Okay. For this is my home page now to go to the admin sectionwithin the address bar.I’ll just type slash. Admin. Okay. So here it is. The Django Administration sitehas been opened now, make sure you remember. What was the user name youentered and the password. So my username was at Eurekaand I’ll just enter the password that I had saved. Once I’m done with that a login, so as you can see over here, the Django Administration sitehas opened now to make my app modifiable in the admin. I’ll have to import that into my admindot py file to do that. I’ll get backto my admin dot py file and within this admindot py file I’ll type from dot models. Import the all courses class once I’ve done thisI’ll type admin dot sight dot register. And the name of my classwhich is all courses. I’ll save this and I’ll get backto my development server and I’ll refresh this page.You can easily see the changesI’ve made to my project. The all course isclass has been added to the admin section. Now when I clickon this you can see that both the courses that I had added in the databaseare shown up in my website now in case you want to addin any other course, you can use the addall courses option over here and specify someof the course name this time.I’ll just say seethe instructor name. I’ll just use XXXI’ll save this. So as you can see the course that I’ve added is Cand that has been added to the all courses optionin my website. Not just thisfrom the admin site. You can delete any courseof your choice, but just clicking on thatand using the delete option that’s present over here. So I hope you all have noticed that this form hasautomatically been generated from the all courses module for I hope you are clear to all that’s been explained stillhere now get back to pycharm. I’ll open the views file and I’ll modify this view isbasically a type of web page in your Django application guys that generally serves asa specific function and has a specific template say, for example, you havea Blog application.So in the blog application, you will have somethingcalled as the blog homepage. So for that you’ll have a Blog homepage detail pageEtc now for my application, which is technical courses. I’m going to includethe home page and The Details page. Fun open up the views fileand over here. I’ll Define another functionand I’ll name it as detail. I’ll have to pass inthe request parameter and within this I’llspecify another argument to this function which will be the course ID. So course underscore ID. And again, I’ll writea return statement. So return HTTP response, so I’ll just createh2 tag at this time within quotes again. So H2 I’ll say that these arethe course details just close the h2 tag again. I’ll just save this now. I’ll have to goto the URLs dot P wife.I love my app and within thisI’ll have to include the part for my Details page. So for that I’ll just write path which is the nameof the function now over here. I’ll just specify that in t should bethe course ID which I specified earlier. And I’ll have to end thiswith a backslash following this I’ll just have to writeviews detail view stir detail and I’ll give a nameto this saying that this is the details page. I’ll close this functionand write the comma and not to forget the comma. Let me save this. I’ll get back to my serverand over here. I’ll go to my homepage. Sorry guys. I’ve made a mistake of here.It’s views dot detail save thisand I’ll rerun my server. Okay, so now I’ll justspecify the idea over here. I’ll say the IDS1 and hit enter. Okay. So as you can see overhere now it is returning what is presentin my Details page. So as you can see over here,I’ve specified the ID as one which is the primarykey for Python. And when I hit enter you can see that it has returnedwhat I had specified in the details function now, let me give some primary key that is not at all presentin my database say for example 5 and hit enter. So as you can see Ihad only two courses which had primary key one andtwo but when I’ve entered five even then it has returnedthe same page now.If you don’t wantyour server to do this, you’ll have to include the HTTP for not for functionin your Details page. So now let me Define a littlemore to this function instead of returning the these arethe course details. I’ll include the ideaalong with this. So I’ll just use for Course IDand over here just close this. I’ll add the string. Of course ID. Please make a note that I am usingthe same spelling. I’ve used everywhere now. I’ll save this and I’ll rerunmy development server. Okay. I’ve just made a spellingmistake over here. However, that’s just HTMLso I can change it anywhere. So having done this. I’ll get back to my pycharmto create some templates for my website.So before moving ontowards templates, I’m going to makea small change over here. I’ll just remove this. I’ll create a variablefor all courses. So I’ll just name it as DC and within this I’llsave all the courses that are present in my database. So all coursesthe objects dot all. Now I’ll create another variableset template and I’ll use the loader function. And get underscore template.Okay, so I forgotten to importthe load of function. I’ll import it over here. So from Django dots templates. from Django template import loader So nowit should be fine. So now to create the templateI’ll right click on the app that I’ve createdchoose new directory and I’ll name it as templates. Now within this templatesdirectory, I will create another subdirectory which will have the same nameas my application.So I’ll name itas technical courses. So if you’re wonderingwhy I’m doing it this way, it is just the standardconvention to create templates within your code. It also makes it very easy for Django to look for templateswithin the app itself. So now within the sub directory,I will create an HTML file. And since this isfor the courses page, I’ll just writecourses dot HTML. So this isbasically my homepage. Also guys, I’ll just clearthis and I’ll be here I’ll just create a list sayordered list within this.I’ll just writesome python code remember that whenever you’reincluding python code within HTML you have to do itwithin the curly braces and the Ampersand symbols just as shown on screen. I’ll just make useof the for Loop. So for X in all courses Sowithin this I’ll create a list and not just thisI’ll create a link as well. So I’ll link this. So I’ll use the HR function. So for that I will haveto use the anchor tag and hrf now over here. I’ll have to specify the nameof my application. That’s technical courses. flash goes ID and thenI have to close this. Now I’ll just link thisto the name of the course.So I’ll use all coursesdot course name. Okay, so that’s it. Finally I’ll have to endfor so to do that. I’ll have to do itthe same way I’ve used for So within the curly bracesdo percentage symbols, which is going to containthe end for statement. I’ll see if this Okay, so now I’ll get backto my views function and over here. I’ll have to specifythe path of my file so which is withinthe technical courses technical courses directory and the name of my fileis courses dot HTML. So over here, I’ll create anothervariable named context.The context is a dictionarymapping template variable name to python objects So within this I’ll haveto store the dictionary of all the elementsor all the courses that are present. So that’s a see. And now coming towardsthe return statement. So I want to returnthe template dot render and that will be context and the request so now my viewsfiles seems to be ready. I’ll get backto my development server. Looks like somethingis missing over here. I have the list but Ido not have the items. So let me get back to my courses dot HTML file and checkwhat mistake I’ve made. Okay. So here it is. I’m using the for Loop over herewhere I’ve used for X in AC.So now to actually returnthe items instead of all courses and supposed to use xdot course name. So now let me savethis back to my server and I’ll refresh this page. Okay. So here it is as youcan see all the courses that are present in my databaseare returned on my homepage. So I hope you allhave understood to here. So now what if the userrequests for a course that does not existon my website in that case.I actually want to Is a for not for error manyof you might be aware of the for not for errorit is it is the very famous the page not found error. Django actually hasa function named HTTP for not for which will allowyou to raise this page not found error in casethe user requests for something that’s not presenton your website to do this. I’ll be using the tryand except blocks.So first I’ll writethe try block and within this I’ll createa variable named course, I’ll store all courses. So all courses dirt objects and here I’ll be using the getmethod with the primary key. So PK is equal to the course ID. Okay. So after this comesthe except block, so here I’ll be raisingthe does not exist except method to do that. I’ll just writeall courses dot does not exist. Be careful withthe spellings again, and then I’ll justraise the http. Phone out for error. I’ll specify some messagesaying course not available. So now I’ve actuallynot imported the HTTP for not for method. So I’ll just importit over here. So HTTP for not forokay so looks cool.I’ll have to change this. I’ll change the return methodfrom HTTP response to the render method. This is actually a shortcut method you can specify the request parameter and the link to the details pageas well as the dictionary as a parameter to this function. Okay. So just clear this up and first I’ll have to returnthe request then I’ll have to specify the pathof my Details page. So it is within thetechnical courses template and the name is Details pageso detail dot HTML, so I’ll specify the course.Okay now I’ll see if this now I’ll get backto my details homepage. So my variable name isnot a see its course. So of course, let’s save this get backto my development server and over here. I’ll just specifythe primary key for python which was 1 and hit enter. So as we all know the primarykey for python was one and when I’ve specifiedthe primary key. It has returned python, which is actually presentin my Details page. So now let me give some otherID and see what happens. So I’ll specifyto so the primary key for Java was too and thereforewhen I’ve specified that I’ve got the outputas Java over here now in case I specify some ID that’s not presentin my database say for example, 45 and hit enter. So here it is the page not found error has been raised and itsays course not available.So I hope everyone’sunderstood till here. So now getting back to pycharm. So I had just written thisin the details homepage for y’all to see Happenswhen I do this now. I want to define something elsealso in my details homepage. So before definingour detailed HTML page, what I’m going to do is go getback to the admin dot py file and over here. I’ll register the details classalso at my admin section. So here I’ll useadmin dot sight dot register. And the name of my classwhich is detailed. Okay, so I’ll have to importit over here first so details and then details, okay, and I’ll save this I’ll get backto my development server. So now I’ll get back tomy admin section and hit enter. So as you can seeover here previously in the technical courses sectiononly one option was shown which was all courses now, I’ve specified the details and now I’ve addedthe details class as well.Now when I clickon this you can see that there are zero details, which means we had not enteredanything in the database to add something to The Details pageyou can do it in the database or over here directly. So what I’m going to do isadd some details to my page, I’ll choose the coursetype to be python. So here I’m justgoing to describe what the self-pacedcourse actually means. I just tried self-paced courseprecedes based on the learner. For the instructor-led course, I’ll just write the coursewill be taught by an instructor. I’ve made a spellingmistake hits instructor. Okay, maybe that’sa very basic information. But since it’s justa test website, I can enter anythingof my choice. You can enter anything you want.So I’ll just save this. So as you can see over here,I’ve added some details. The reason why I’m seeingthis over here is because I’ve asked my functionto return the self-paced course now to change this I’ll getback to my function. So that wasn’t my models file. So I’m going to be makinga small change of here instead of returning the detailsof the self-paced course.I want to returnthe primary key of my courses. So that would be PK and this has to bewithin a string. Okay, so I’ll save this nowI’ll go from the terminal. So I’ll get back to my server. I’ll just click on the link. So I’ll go to theadmin section again. Okay, I’ll click on details. So as you can see insteadof returning the details of the self-paced course, it has returnedthe primary key of python, which is 1 now. I’ll click on this andas you can see over here, it has returned that the course is Pythonand Test 2 types, which is self-pacedand instructor-led. So all this is working on the back end of your projectthe front end basically deals with HTML python actuallyworks in the back end of your websites. So now coming backto our Details page. What I’m going to do over hereis print out the course name the instructor name as wellas link the course name to the course landing pageof Ed Eureka to do that.What I’m going to do isuse the if else statements. The first thingthat I’m going to do is write some python code with an HTML. So here it will be if course dot pk is 1 which means if it’s python then I wantto return the course name and I want to make this an H1 tag and thenI’ll create an anchor tag to which I’ll link the courselanding page of Erica.So I’ll just open up the browser and I will takethe link from here and I’ll paste itover here after this. I’ll just close this. And the course name, I’ll have to close the anchortag and close the H1 tag. So there it is. Now. What I’m going to dois return the name of the instructor as well. So of course dot ins name, please be carefulwith the spelling’s use the same spellings thatyou’ve used for each variable.So now we’ve done for Python and now we have to dofor C++ and Java, I’ll just return the nameof the instructor in h2 tag, so that it’s more visible allthis is your choice guys. You can make it. However you want. And now what I’m goingto do is use the else if statement so to percentage signs closethe curly braces and over here. It will be LF course dot PK is to what I’m going to do iscopy this It stood over here and I’ll just change the link. I’ll take a Dura Costco’slanding page of java and I’ll just copy thisand I’ll paste it over here. So now similarly youcan do for C++ as well. I’m just showing to observe. I’m just going to do itfor Python and Java. So I’ll just copy this again and I’ll paste it overhere then for C++.Then for the else statement, I’ll just writethe course name of C++. I’m not linking this because I’ve alreadyshown you two examples. So course nameand the instructor name that will bein the H1 tag again. Sorry. So H1 course nameand close each one after that. The course instructornamed just copy this one. So now I have to end this and I have to end itin a similar way that I’ve been writingthe else if block so it will be end if okay now I’ll save this so I’ll get backto my homepage and over here. Alright / primarykey of python, which is 1 and hit enter. So as you can see over here when I enteredthe primary key of python, which was one earlier. It was just showingthe name of the course. Now as you can see, my course name has been linkedto the official website of Erica similarly.If I do for two and three,I’ll get the same. But if I hope you’ve understoodthis so you can add on whatever detailsyou want to your page. Just like how I’ve shown you. So now coming back to pycharm. I want to actuallylink my courses page to my Details page. Now, what I’m going to dofor that is actually I’ve made a mistakeof here in the reference. I’ll have to removethis and over here. It will not be course ID. It will be x dot ID and that iswhat I’m going to link. Okay, so xdot course name now, I’ll just save this.I’ll get back to my serverrefresh this page and I’ll click on python. So as you can see over here, I’ve linked my home pageto The Details page now if I click on this as I’ve alreadyshown you it will go to the course landing pageof Eddie Rekha. So now we’ll get backto my development server. Now as you can see, I have my back and beingdisplayed on my front end. So now what I’m going to dois add on some more details to my homepage if my home page doesnot look beautiful.I don’t think many peoplewould even like to visit my website now basicallybeautifying your home. Is depends on how you use yourHTML and CSS now to do that. I will get back to coursedot HTML page and over here. I’ll write some text as H1 tag and that will be welcometo edu recur after this. I’ll just add on some image. So I’ll just add onand Erica image over here. I have the source link. So I’m just pasting itover here guys after this. What I’m going to do is closethis image tag, obviously. Now, let me save this and getback to my server and see what happens when Irefresh the page. I refresh this. So there it is guys. Welcome to edu Rekhaand the edge Erica image. So now to add some moredetails to my homepage. I’ll go to the officialbootstrap website and I’m going to copy pastesome part of this code. So I’ll just copy this guy’sbootstrap is very good in helping you createyour HTML web pages.So just to beautify my page. What I’m going to dois add this right in the beginning of my code. Let’s save this. I’ll get back to my websiteand I’ll rerun this. Okay. So I hope you seethe changes our website before was looking very dull and now it looksmuch more beautiful compared to what it was before. Okay. So my website as of now does not have anythingsuch as a menu bar or something. So let’s move on and add that so I already havea piece of code for that just copy it. And I’ve bested this is welcometo I do they go. Okay. Sorry for that.So I’ll just add it here. Let’s save this and I’ll rerunmy development server. Okay, as you can see overhere a menu bar has been added to my homepage. Okay. So all these bitsof codes are taken from bootstrap website. You also can take itfrom there guys. So as you can see over here, my Details pagelooks too plain. So to make it more descriptiveI’ll be adding on some images and we’ll create a form for the user to selectbetween self-paced course and the instructor-ledcourse options to do that. I first need to make changesto the models to our py file from my project. So I’ll get backto my project and over here. I’ll open upthe models dot py file. So the first thingI’m going to do over here is add a new variable that will specify the date from when the coursehas been started. I will name it as started from and we’ll usethe date and time field of the models class.So to the all course is class. I’ll Adding a new variable named as started from startedfrom and I’ll be using the models dot daytime field. Please be carefulwith the spellings. So that is date daytime field and within this I’llsay started from so once I’ve done this, I’ll add another custom methodto my all curses class that will be waspublished recently. Now, this is going to describe when my coursehas been published. Okay. So now I’ll justDefine the class. Let’s say waspublished recently. So I want this class to return when my coursehas been published. So for that I’ll just writereturn self dot started from and this can be greaterthan or equal to X owned now. – date-time the time Delta. So one thing I wantyou guys to know is that time zone dot Now function is present withinthe Django dot utils module and the time Deltamethod is present within the date-time module.I’ll just specify the numberof days to be one. So if you want more informationabout the daytime module, you can check outany records videos and blog on the same. Okay, so here I’llneed to import it. So I’ll just import date timeand from Django Dot utils. I’d have to import. Time zone. Okay. I’ve forgotten thespace over here. So that will be time zone. Okay, so are allcourses classes ready. And now in the details class. I’m going toremove the self-paced and the instructor-led variables and I’m going to replace itby a single variable that will hold both the values. So I’ll just clearthis from here. I’ll create a new variable. I’ll just name it as CTwhich will be the course type.And since this is goingto hold characters, I’ll use the care field method. Okay, so I’ll justspecify the max length of this to be anything say 500. So I need another variable which is goingto store the option that is selected by the user. So for that I’ll justname it as your choice and then I’ll be usingthe Boolean field present in the models class of here. So that’s Boolean. Okay. Yeah, Boolean fieldand the default. I’ll just set it to be false. Now instead of returningthe primary key. I want to returnthe course type. So I’ll just change it. So yeah, okay. So now my models are ready now, once this is done, I’ll have to make these changesusing the make migrations and the migrate command. Okay, so I’ll justopen up the terminal I’ll return the control backto the terminal and over here.The first thing that I’ll haveto do is python -. P why? Mick migrations followedby the name of the app, which is technical courses. Please be carefulwith your spellings. Okay. I’ll just hit enter of this. I’ve just madea spelling mistake. Sorry guys. Okay, so that’stechnical courses. So as you can see over here,it’s asking me a question.If I’m if I’ve renamed the details dot il-2 details dotc t so I’ll just say yes, I’ll hit enter. So now after this since I’ve added a new Field named started from it’s askingme to provide one default value or to quit and let me adda default value in the models dot py file itself. I’ll just choose the firstoption and I’ll hit enter. So now to set the time I’ll justuse time zone dot Now function which is going to setthe current time. So that’s time zone dot nowand I’ll hit enter. Okay. So as you can seemy tables are ready again, and this time I’ve got a new ID, which is triple zero to sonow I’ll have to use Python – turd py migrate. And I’ll hit enter. I’ve made aspelling mistake again. That’s my great. So after I’m done with that, I’ll have to use Pythonmanaged py SQL migrate and I’ll have to specify the ID which was Triple zero tofollowed by the name of my app, which is technical courses.Once I’ve done this,I’ll hit enter. Sorry guys. I’ll have to specify the nameof my app before the ID. So that’s technical courses. Followed by the ID which is triple zero twoand then I’ll hit enter. Okay. So now my tables are ready. The next thing that I’ll haveto do is open the python shell so for that I’ll just open upmy command prompt and over here. I’ll have to getinto the directory which holds my project. I’ll just copymy project path from here. And I’m goingto paste it up here. Then I’ll get into my projectwhich is website. And after this I’ll haveto write python managed at py Shell. Okay. So by running the makemigrations command, you’re telling Django that you’ve made some changesto your models. And now you like the changesto be stored as a migration. So migrations are basicallyhow Django stores changes to your models and thusto your database schema.They’re just files on the disk. You can read the migrationfrom your new model. If you like. There’s a commandthat will run the migrations for you and manage yourdatabase schema automatically and that is the migrate commandthe SQL migrate command takes migrations namesand returns their SQL. Okay, the table names are automatically generated bycombining the name of the app and the lowercase nameof the module. So in my case the nameswere all courses and details so correspondinglyin place of capital A. I’ll have a small a and since my details classalready has a small D. It will remain the same. Another thing I wantto guys to note is that the SQL command doesn’t automatically runthe migration on your database. It just prints it on the screen so that you can see whatSQL Django thinks is required. It is useful for checkingwhat Django is going to do or if you havea database administrators who require SQLscripts for changes.So for some more informationabout the migrate command, it basically takesall the migrations that haven’t been applied and runs them againstyour database essentially synchronizing the changesyou made to your models and the schema in the database migrationsare very powerful guys, and they let you changeyour models over time as you develop your project without the need to deleteyour database or tables and make new ones.It actually specializesin upgrading your database live without losing data. So now coming backtowards our database. I’ll just show youwhat’s present in my database. So for that I’ll haveto use the all function. So I’ll just type all courses. So all the objects presentin the all courses class will be retrieved. I have to first import it so from technicalcourses dot models. I’ll have to importall courses class. And the details class. I’ll just checkif my spelling’s are correct. So that’s detailsand all courses. Okay. It’s not and over here. It’s a comma. So after this, I’ll just run the commandall courses taught objects. Not all so as youcan see over here. I have three objects, which is pythonJava and C now.Like I’ve already shownyou before in case I want to retrieve just one objectwhich is present in my class. All I have to do is typein the same command, which is all courses taughtobject and instead of the all method. I’ll have to use the get method and I’ll just specifythe primary key to be one and then I’ll hit enter. So as you can see the object whose primary keyis one is python. You can also make useof the filter method to do that. Just change the get methodto filter and then hit enter. Okay, so as you can see the getjust like the get method the filter methodhas also returned python when I’ve specifiedthe primary key as one now. I will be importing the Django dot utils timezone method over here.So from Django dot utilsimport time zone, please be carefulwith spellings. Okay. Sorry for that. I told you guys to be careful and I myself madea mistake of here. So that’s Django. Okay, after thisI’ll take a new variable which will after this. I’ll take a new variable namedOscar named as current year and I’m going to equate itto the year of the current date. So for that I’ll just writecurrent on the score here equals x own dots now. Dottie oh after this,I’ll take the all courses class.And I want to fetch the objects that have been publishedin this year. So I’ll use the get method. I’ll use the current your objectthat I just created and I’ll equate thisto start it from object that I’ve createdin my class to this. I’ll just specifyunderscore underscore here because I wantto retrieve the year. And then I hit enter I’ve madea spelling mistake. Sorry for that. It’s started from Soas you can see over here, it says get has returnedmore than one objects from the all courses class. Now, this is because I had set allthe courses starting date from the time zonedot Now function, which means I had set it to the current timefor all three courses. So now I’ll take a new variableQ within which I’m going to store one of the objectspresent in the all courses. So it’d be eitherpython Java or C.I’ll just specifythat through the primary key. So that will be allcourses dot objects dot get I’ll use the primary key as oneitself and then I’ll hit enter. Okay. So now if I want to check if this coursewas published recently. So for that I’ll just typeQ dot was published recently, which is the nameof my class, which I’ve defined already. So was publishedOn the school recently and then I’ll hit enter. Okay, so looks like I’ve encounteredan error over here. It says can’t comparedate time the date time to date time dot date. Okay. Looks like I’vemade some mistake within my models over here.So let me just check. I’ve imported the data module and I’ve importedthe time zone method as well. So as you can see overhere instead of making use of the date-time field. I’ve made use of the date field and that is why itis throwing an error of here saying can’t comparedate-time dot date time to date time dot date. So let me just makethat change over here. It states Time Field. I have to save this. So since I’ve madea change of here, I’ll run the makemigrations command. And after that I’ll have to usethe migrate command as well. Okay. So after thisthe SQL migrate command, of course and the ID that is generatedthis time is triple 0 3 so now my databaseis ready and over here. Let me just exit thisand I’ll clear the screen.So now again, I’ll use Pythonmanaged or py shell. And I’ll have to import. I have to import time zone. Sorry for the mistake guys. I use the commandwhich I used previously and I had made a mistakein the spelling over there. Okay? I’ll also have to importthe models present in my app so from technical courses. Dot models, I’ll haveto import the classes which is all coursesand details after this. I’ll have to importthe daytime module. So import Dave time. Okay now just tocheck my database. I’ll just run the command all courses dot objectsnot all and I’ll check what it returns. Okay. So now my database is ready. So getting back towhere we stopped earlier. So I had just createda new object q and I had storedthe element having the primary key as one into it. So I’ll do it again. And after this I’ll use thewas published recently method.She looks like we’ve encounteredanother error over here. So I’ll get back to my models. And it shows that there’s some problemwith this variable over here. So what I’m goingto do is just remove this variable for a secondand I’ll just comment these out I’ll just open upmy terminal again and I will makemigrations to this then I will use the migratecommand and I’ll use SQL migrate again. So what’s the IDS IDstriple zero eight? Okay. Okay. Now I’m going to addon this again. So that doesn’t showme an error again. I got to make migrations again. The reason why I’m doing thisis previously it was showing that this variableof mine is of none type.But actually we have to equateit to the current time, which is x 1 dot Now function. So just to not encounterthe same error again, I deleted that variable or that element from my tableand I’m adding it again so that it’s createdas a new variable. So now I’ll add the startedfrom variable again, I’ll save this and asusual I’ll have to make the migrations and I’ll haveto migrate it again. The option over here. I’m going to choose is one hit enter use time zonemethod time zone dot now to be specific andhit enter after this.I’ll have to migrate. And then usethe SQL migrate command. So the idea that this time is 9and I’ll hit enter. Okay, so now my table is ready. So as you can see over herepreviously, it was just showing me the started from name and now it’s showingme the date and time. So now I’ll get backto my command prompt. Okay, so now I’ll getback to command prompt just exit from hereand I’ll clear the screen.I’ll get into mypython shell again. And after this I’ll haveto import everything that’s required whichis timezone method from Django Doodles. The models file from technicalcourses website or application and then the daytime module. Okay. So now I’ll takenew variable say and I’ll say all coursesdot objects dot get and I’ll use the primary key as one. Now I’ll use the was publishedrecently method and see what it returns was published. recently So as youcan see over here, it says that the prime that the objectwhich holds primary key as one which is pythonwas published recently and it says this is true. Okay. So I hope everyone’sclear till here. So one thingthat’s very important that we learn to be here is while making changes to your model you will haveto make migrations and then migrate it and then use the SQL migratecommand with the ID that is generated bythe migrate command. So any time you make changes you will have to do allthese three things. Even if you make some mistake within the modelsdon’t be scared because each time you makea mistake you get to learn even more from that.So as we all knowmy details class is interlinked to my all courses class, which means my detailsclass is derived from my all courses class. Now this connectionis actually made through the primary key andthe foreign key relationships. So before makingany more changes of here, what I’m going to do is get backto my development server and over here. I’ll go to theadmin section now, I’ll get into the all courses that are presenton my website and over here as you can see Ihad three courses which was C Java and python now when I click on oneof these you see that previously onlythe course name and the instructor name wasshown but now it also specifies when my course has been started.So as you can see over herepreviously you could see self-paced and instructor-ledcourses over here. So now what I’m goingto do is click on this and I’ll just clearthis from here. So I just killed the details. So now I’ll go to my database. I’ll exit this and I’ll haveto re-enter my shell again. I’ll import my classes again. And I’ll usethe previous commands Okay, so now I’ll just take the object a and I’ll say detailson this course set dot all.So as you can see over here, I deleted the details that were presentfrom my admin section and that is reflectedover here as well. So what I’m going to do nowis set to values for my variable which was CD that iscourse type to do that. I’ll use a DOT detailson this corset and instead ofthe all functional use the create functionwith the help of this create function.I’ll be able to assignone or more values to the curse type field. That is CT. So I’ll say CT isequal to self-paced. Okay, so that was my firstoption and now I hit enter. Okay. So one option I’ve alreadycreated which is self-paced. Now. I have to create another optionwhich is instructor-led. So for that I’ll usethe same command again and I’ll just change fromself-paced to instruct a lit. And I’ll hit enter. Okay, so now I’vegiven two options. But when I gave the firstoption it will turn that the details are self-paced and when I gavethe second option, it has a return that the detailscontain instructor-led. Now if you want to see if both these options are storedin the detailed set.All you can do is make useof the count method. So instead of thisall method of here, I’ll use a tooth details dotcount and I’ll hit enter. So as you can seeit has returned that I have to detailsfor this object, which is python which means pythonhas two objects, which is self-pacedand the instructor LED options. So I’ll repeat thisfor another course, which is presentin my database say for Java. So I’ll take a new variablethis time and instead of a I’ll rename this as Band the primary key I’ll specify as to so now let mejust retrieve the course name.For this primary key, which is 2 so nowas you can see the curse name, which is present at primary key. Number two is Java now we’ll setthe options for this as well. So I’ll use B dot detailson this corset dot create and I’ll givethe same options again, which is CT is equal toself-paced and another option, which I’m going to giveis instructor lid.Okay now I’ll hit enter. So now let me givethe count option for be as well. So as you can see, I’ve created twooptions for Java which is instructor-ledand self-paced courses. Okay. So I hope everyoneunderstood till here. So now I’m done with the models and I’ve donewith the database now, I’ll have to modify my viewersand my templates so to do that, I’ll go to My Views fileand over here. I’ll make some modificationswith regards to the changes. I’ve made to my modelsso over here, I’ll be creating a new functionnamed your choice that will hold the users choiceand we’ll save it after the user has selectedthat particular type, of course he intends to enroll for so here I’ll be makinguse of a new function which is present inthe Django dot shortcuts module and that is the get objector for not for method.So for that I’ll justimport it over here. So that will be get objector phone out for since I’m not made useof this it’s not Highlighted so like I’ve already told y’all I’mgoing to create a new function which will bethe your choice function. Now this function will actuallystore the user’s choice and it will reflect the same after the userhas made his choice between instructor LEDand the self-paced options.So now I’ll bedefining the function. So it’s D E F your choice. And as usual, I’ll have to passthe request parameter. And I’ll have to specifythe course ID. So within this function I’ll make useof the get object or the for not for method to do that. I’ll just take a newvariable say course and I lose get underscore objectnot for not for method and I’ll specify all courses. And the primary keys. Okay, I’ll justchange this to course and we here I’ll saycourse underscore ID after this I’ll be making use of the tryand except block. Now. This is in casesome course is not present. I want to catch that error usingthe try and the except block.So I’ll just useanother variable over here. I’ll say selected selectedcourse type equals details on this corset dot get And I lose the primary keyequals request dot post method. And within this I’ll justspecify this as the choice. So now done with the try block. I’ll have to go to theexcept Block in case there is a key error. I’ll use the method key error and all courses dotdoes not exist. Now make use of the return statementwith the render method.Remember guys that the render methodis always a shortcut to the HTTP responsemethod So within this the request parameter again, and then all courses /details or detail dot HTML, which is the nameof my target file after this as a specifythe dictionary which holds what to return for courseand for the error message and now the error message erroron Disco message. So the error message Iwant to display is select a valid option in case the userprovides some invalid option. So that will beselect valid option. Okay, so in casethe user does not make a selection and hitthe submit button. It’s going to return a messagesaying select a valid option. So after this, I’ll have to use the else blockand then if in case he’s made the selection selectedcourse type dot your choice.When the user hasmade some selection, I want to set the value of theselected course type to be true and then I’ll just savethis using the save method so selected selectedcourse type dot save And then I’ll just make use ofthe return random method again. Now here it’s going to return. I want to redirect My Viewsto the templates, which is the detaildot HTML so for that. So technical courses / details dot HTML nowthe dictionary that specifies my details again. So that’s courseand the value is course itself. So one thing I forgotto do over here is import the details class as well. So I’ll import that and one small changewithin the detail class. I’ll just clear this. And over here, I’ll just say courseequals get object or for not for and over here. We all coursesand the primary key, which is equal to the cosine tSo I’ve made use of cou SE and not cou RSE and everywhere. I’ve been usingthe same spelling.So just be careful guys in caseyou’ve given some other spelling then be careful that whenever you’re referringto that variable. You give the correct spelling that you’ve mentionedin your app. So after thisthe return statement again, so return render and requestwhich is the first parameter and it’s and thentechnical courses. slash detail dot HTMLAnd then the dictionary again, so I’ll just copy paste it from here. I’ll just clear this methodwhich I’m not been using. Okay, and actuallyI’ve not made use of the details class as well. So I’ll just remove it. Looks like I’ve missedsomething of here, which is the course dot detailsand this corset dot get so here. There’s another change asthis cross-checking my file and I found another changewhich is technical courses. So now I’ll just seeif this okay.So now everything looks perfect. So once My Views are ready, I’ll have to go towardsthe templates now the page which I’m targeting over hereis the detail dot HTML page. So I’ll just open upthe detail dot HTML page. So as you all know previously, I’ll just get backto my development server and show youwhat this page shows. So here it is the detail startHTML page basically Returns the name of the coursewith the name of the instructor.Now this looks too plain. So I want to add on somethingthat is so basically what I’m going to do is addon an image of this course, and then I’ll be creating a form for the user to selectbetween the self-paced and the instructor LED options. So now to do that,I’ll get back to pycharm. And over here, I’ll just insert some imagesfor my courses. So the first thingI’m going to do is make use of the image tag and the source. I already have it somewhere. So I just copy it. So I’ve just copied the link ofa python logo here after this.I’ll have to createthe list of options present within this course, so to do that, I’ll just take an unordered listand within that I’ll use Python code again. So I hope you all remember how we have to specifypython code with an HTML. It is between two curly bracesand to Ampersand symbols. So that’s 4X in all courses dot set dotall I’ll say create a list and I’ll say x dot c tthat’s course type. And for okay, I’ll seeif this and I’ll just show you what changesI’ve done over here. So I’ll get back to python. Okay, so as you can seepreviously it was just showing me python which is the name of the courseand the instructors name. Now I’ve added on an image and it shows methe image over here.Now. My details dot HTML pageis still not complete. So for that I willbe creating a form. So as you all saw I made two changes oneis adding the image and the other changewas adding a list that contains the self-pacedand the instructor LED options. Now you would be wonderingwhy only one change is being reflectedon the development server. Now this is because I’ve not madechanges to the URL. So as you all have seenI’ve made two changes to my details dot HTML page, but only one was being reflectedon the development server. Now this is because I’ll haveto make changes to the URLs dot P Wi-Fi as well.Now before doingthat I’ll just complete the form that I was goingto create on this page. So for that I’ll have to includesome more python code over here and this time I’ll usethe if statement. so if error message thenI’ll just give a paragraph tag. And I will give this a strong. And to this I’ll specifythe error message which I’ve previously defined. Now I’ll just closethe if statement. So that’s endif. So now to create a formI’ll be making use of the form tag presentin HTML many of us would know every form hasan action to which I’m going to specify the your choicefunction present in views.So for this I’ll openthe curly braces and within the Ampersand symbol, I’ll say URL and I’llsay technical courses. Now the reason why I’m going to use the technicalcourses name over here is because this is the nameof my app and I’m going to be using this name space for all the URLspresent for this app. I’ve not made that change asof yet in the URLs that py file so when I’m doing that you will understand thisin a better manner.So that’s your choice. And then I’ll specifythe course ID then I’ll just close this. So the method that I’m going to specify overhere is post method equals post. So I’ll just closethis over here. So now I’m going to be makinguse of something very special which is the csrf token. So that’s csrf underscore token. So before explaining thisto y’all in detail, I’ll just complete the codeand then get back to it. So now we’ll be makinguse of the for Loop. so far choice in courseDodge detail on this corset dot all so for all the elementspresent within the detailed set. I want to create an option for the user to selectbetween the self-paced and the instructor-led courses. So here the input typeinput type will be radio and the name is goingto be Choice. I’ll just name it as choiceand ID will be choice and that is going to befor Loop dot counter and the value willbe the choice ID. So now I’ll just createa label tag for choice.For Loop counter againAnd I’ll close this. So the text that I want to displayover here is the choice underscore CT which isthe course type Choice dot c t which is the course type. Okay, so close the label tag. And I’ll createa line break over here. So let’s be our now. It has to bewithin the Ampersand. Okay, so I’ll just save this and I’ll createan input button over here.So that’s going to beinput type will be submit and the value alsois going to be submit. So now I’m donewith the detail dot HTML page. But before moving ontowards the development server, I’ll have to include thiswithin the URL study py file that I’ve createdfor the technical courses app. The URL start py file can havea number of URLs for each app that is created nowto distinguish between each app. It’s better to givea name to that app. So that the URLspecific to that a par with in the name of that appitself now to distinguish between each of them. It’s better to givea name to each app so that the URL specific to itwill be within the name of that app itself.So I’ll just namethe app of here. I’ll say app underscore name isthe name of my app, which is technical courses. So after this is done, I’ll have tocreate another path. So I’ll just copy thisand within this the page that I want to referwill be your choice and that will be with regardsto the primary key that we’ve already created. Okay, so just copy that and I’ll say your choicewhich is the name of my function and then / ok, so that will beviews dot your choice and the name will beyour choice again. You can give any nameof your choice just like before so nowmy file is already.The first thing that we did was madechanges to our models and then we storedthe changes in our database after making the changesto our models and database. I was supposed to makechanges to views which I’ve done alreadyand then the templates so that is details dot HTML page. Finally. I’ve linked the details dotHTML page to the URL stood py file present within my app. Okay, so I’ll just save everything and I’llrerun My code to see if this and I read on my server. Okay my development so it doesn’t seemto be running. Okay. I’ve made a mistake of here. It’s your choice not hoist. So I’ll just see ifthis I’ll get back to my server and I’ll rerun this. So looks like we’veencountered some error. So let me just get backto my Details page and over here. I’ll just cross check what I’ve done soit’s a link error.So I just have to go to the link and check what mistakeI’ve done over here. Okay. So that’s URL technicalcourses: your choice. Oh here it is. Instead of typing course dot ID. I’ve typed course underscore ID. So I’ll just say coursedot ID save this will get back to my development serverand I’ll rerun this. Okay. So congratulations guys. Our form is ready. So when I select anyof these options and I hit on submitit is going to save that as my option. So whenever I login next time it will just show methe option that I’ve enrolled for and it will not showme the other option. So before doing that I’ll just explainto y’all what’s happening on this detail about HTML page.So our details dot HTML pagehas created a radio button for each option that is Well spaced or instructor-led the valueof each radio button is the associatedcourse type ID the name of each radio buttonI’ve given is Choice which means when somebodyselects one of the radio buttons and submits the form it willsend a post data saying Choice which is equal to Hash where hash is the IDof the selected choice. Now, this is the basic conceptof all HTML forms. So we’ve set the forms actionto the URL as technical courses: your choice and choice dot ID, and the method we’ve used is post using the postmethod is very important because the act of submittingthis form will alter the data on the server side, whenever you create a form that alters the dataon the server side, you will have to make useof the post method and not the get method.So you all have noticed that I’ve made use of thefor Loop dot counter method. Now this actually indicates how many times the for taghas gone through its Loop Since we are creatinga post form which will have effecton modifying the data in our database. We need to worry about the crosssite request forgeries. Thankfully, you don’t haveto worry too hard because Django comeswith a very easy to use system for protecting against itin short all post forms that are targeted at internal URLs should usethe csrf token template tag. So over here csrf actually stands forcross-site request forgeries. Okay, so I hopeeveryone’s clear till here. So the next thing that we’re going to be doingover here is creating tests, which is very important for every website you create Sobefore moving on to show y’all how to write testsfor our website.I’m going to be sharing someimportant details about testing. So first of all, what are automated tests testsare simple routines that check the operationof your code testing operates at different levels. Some tests might applyto a tiny detail While others examinethe overall operation of the software. So that is something which is same aswhat we’ve done while using our python shell. So we’ve use the python shell toexamine the behavior of a method and running the applicationand entering data to check how it behaves. So what’s differentin an automated test is that the testing work is donefor you by the system. You create a setof test once and then as you make changes to your app, you can checkthat your code still works as originally intended withouthaving to perform time-consuming manual testing again, and again, so why do youneed to create tests? You may feel that you’ve done quiteenough on your plate? Just learning Pythonand Django and having yet.Another thing to learn may seem overwhelming and perhapsunnecessary after all as you all have seenour website is working quite happily now goingthrough the trouble of creating automated tests is not going to makeit work any better if creating the technicalcourses application is the last bit of Django programming youwill ever do then true. You don’t need to knowhow to create automated test. But if that’s not the case, this is the best timeto learn testing. Okay, so tests can actuallysave you time up to a certain point checking that it seems to work will besatisfactory test in more sophisticated applications. You might have dozens of complex interactions betweencomponents a change in any of these components couldhave unexpected consequences on the applicationsBehavior checking that it still seemsto work could mean running your coats functionality with 20 different variations of your test datajust to make Sure, you haven’t broken something which is definitelynot a good use of your time. That’s especially true.When automated tests could dothis for you in seconds. If something’s gone wrong testswill also assist you in identifying the code that’scausing the unexpected Behavior. Sometimes it may seema cord to tear yourself away from your productivecreative programming work to face the unglamorousan done exciting business of writing tests particularly when you know, your code is working properly. However, the task of writingtests is lot more fulfilling than spending hours of testingyour application manually or trying to identifythe cause of the newly introduced problems. Hold on tests. Don’t just identifythe problems. They also prevent them. It’s a mistake to thinkof test merely as a negative aspect of developmentwithout test the purpose or intended behaviorof the application might be rather opaque evenwhen it’s your own code.Will sometimes findyourself poking around in it trying to find out what exactly it is doingtests actually change that they light up your code from the inside andwhen something goes wrong, they focus the light on the partthat goes wrong even if you hadn’t even realizedit had gone wrong test also make your code more attractive. You might have createda brilliant piece of software, but you will find that many other developerswill simply refuse to look at it because it lackstests without tests. They won’t trust it. According to Jacob Kaplan Moss. One of Django’soriginal developers code without tests is broken by Design other developers wantto see tests in your software before they take it seriouslyand that is just another reason for you to write your tests.Last but not the least testhelp teams work together. The previous points are writtenfrom the point of view of a single developer maintaining an applicationcomplex application will be maintained byteams tests guarantee that colleagues don’tinadvertently break your code. And also you don’t break there’s without knowing so nowmoving on I’ll be sharing with you all a fewbasic testing strategies. There are many ways to approachwriting test some programmers follow a disciplinecalled test-driven development.They actually write their tests before they writetheir code this might seem counterintuitive. But in fact, it’s similar to what most peoplewill often do anyway, they describe a problem thencreate some code to solve it test-driven developmentsimply formalizes the problem in the python test casemore often a newcomer to testing will createsome code and later decide that it should havesome tests perhaps it would have been betterto write some tests. You but it’s never toolate to get started. Sometimes it’s difficultto figure out where to get startedwhile writing test. If you’ve writtenseveral thousand lines of python code choosing something to test mightnot be easy in such a case.It’s fruitful to writeyour first test the next time you make a change eitherwhen you add a new feature or fix a bug. Okay, so now I’ll be movingon to show y’all how to write the first testfor your application. So the first thing that we’ll have to do isidentify the bug that’s present in our application. I’m sure many of youwouldn’t have noticed but fortunately there’sa little bug in my application as I’ve shown youearlier the method that I’ve created which was was publishedrecently returns true if the course was publishedwithin the last day but also if the all courses startedfrom field is in the future, it will show through nowthe show this to y’all I’ll just open up the command promptand I’ll open my shell again.So I’ll just clear the screen. And now I’ll getback to my shell. And over here, I’ll importthe date-time module. And then from Django doodles. I’ll import. I’ll import the times on method. Now after this, I’ll have to importthe all courses and the details class presentin the technical courses app. So from technical courses. dot models import all courses, details I’m not givinga space over here. Okay. I’ve just madea spelling mistake of here. I’ll correct ittechnical courses. Okay. So now I’ll be creating a newobject over here and I’ll name it as future course, so I’ll just sayfuture underscore course. And the date for the publishingof this course will be 30 days from today. So what I’m going to dois take all courses. And I’ll take my variablewhich was started from.And within this I’ll juststore time zone dot now. Plus date time dot time Deltaand I’ll specify that as 30 days. So this means that the future coursewill start after 30 days from the current date. So for this I’ll use the was published recentlymethod and see what it returns. So I’ll say future course. Future underscore course isthe name of my variable dot was underscore publishedunderscore recently and now I hit enter so as you can see over here, the course is intendedto be published after 30 days. But when I use the was published recentlymethod it’s returning true, which is actually wrong. Now. I actually want to create a testthat will expose the bug what we have just done inthe Shell is to test the problem and it’s exactly what we can doin the automated tests as well.So let’s turn thisinto an automated test a conventional placefor an applications test is in the applications test dot py file the testing systemwill automatically find tests in any file whose namebegins with test. Okay. So to create a test, I’ll open this test or py fileand as you can see over here, it has already importedthe test case method for us from Django DOT test class. So one more thing I wantto import over here is the data. Time module so I’ll sayimport date time. And also I want to importthe time zone method present in Django dot utils.So from Django dot utilsimport time zone. After this, I’ll alsohave to import the models that are presentwithin this app. So for that Ali was from dot modelsimport all courses, so we here I’ll createa new class so class. And I’ll just givesome random name to this. So I’ll say all courses. model test you can give any nameof your choice guys.Okay, so I’ll have to usethe test case method over here. So that’s test case within thisI’ll Define a function that is going to returnfalse for the courses who’s publishing date is in future. So to do that. I’ll just take a newvariable say time. equals x own judge nowand I’ll add this to date time. Time Delta. after 30 days Sorry guys withoutspecifying the function itself. I’ve started writing the code. Define I’ll just give the name as test underscorewas published. Recently, which meansit’s the test for was published recentlymethod with future course. And I’ll just hit tab over here. Okay, so now I’lltake another variable which will be future question. And this will be equalto all courses and started from Started from will be equalto the current time plus 30 days now losethe self parameter. And I’ll usethe assert is function. And I’ll use futurefuture question dot was published recentlyand I’ll set this to false. So here we’ve actually created a Django DOT test DOT testcase subclass with a method that creates an all coursesinstance with a started from in the future.I’m then goingto check the output of was published recentlywhich ought to be false. Okay. So I’ll just save this. I’ll open up the terminalI’ll return the control back to my terminal by hittingCtrl C and over here. I’ll type in the command python managed py test followed bythe name of my application, which is technical courses. So what exactlyhappened over here is this the managed of pytest command actually looked for the all courses application after that it found a subclassof the Django DOT test the test case class it thencreated a special database for the purposeof testing then looked for the test methods the oneswhose name begins with the test in the function testwas published recently with future cores. It created anall courses instance who’s start date is30 days in the future. And then usingthe asset is Method. It discovered that thewas published recently returns true though. We wanted it to returnfalse the test informs us which tests failed and even the line on whichthe failure occurred.So as you can see over here, I have a message sayingthe test has been failed. So the next thing is to fixthe bug we already know that the problem isin all courses was published recently method and thatshould actually return false if the publishing date, Of that course is in the future. So now what I’m going to dois get back to my models that py file and over here. I’ll have to make changes to thewas published recently method.What I’m going to do isadd a new variable thin now and I’ll equatethis two time zones now. After this, I’ll just changethis return statement. So I just returned now – the dates timedot time Delta. of one day and then I’ll comparethis with the published date. So now that I’ve madethe required changes, I’ll just save thisand rerun the test again.So it’s python managedof py test technical courses. So as you can see over here,unlike the previous result. I’ve got an okay, which means I’veactually fixed the bug. So basically what I’ve doneover here is identify the bug and I wrote the code that exposes it and correctedthe bug in the code. So my test passes generallymany other things might go wrong with our applicationin the future, but we can make sure that we don’t inadvertentlyreintroduce this bug because simply running this testwill one has immediately so that was justwriting a basic test. I think I’d preferto write some more tests for my application. So while I’m here I’m goingto further pin down the was published recently method because it’s goingto be very embarrassing if in fixing one bug Iwould have introduced another so I’m going to addtwo more test methods to the same class to testthe behavior of the method more comprehensively.So I’ll just open upthe test dot py file. I’ll Define two morefunctions over here. So this will be testwas published recently. with old course Sothis method basically returns false for the courses who’s published dateis older than one day. So I’ll just takea new variable of here. I’ll say test and I’ll saythat this is time zone dot now. – date-time dot time Deltato know more about time Delta.You can actually referto the video and the blog on editor Acres channelfor the daytime module and within this I’ll specifyone day and one second. I’ll create a newvariable say old course. And then I’ll usethe all courses class and I’ll use startedfrom started from variable and I’ll equate this to time. Okay, I’m sorry. I actually intendedto name this time not test. Now finally, I’ll be usingthe asset is function and old course. . Was published recentlyand I’ll set this to false now will bedefining another function. I’ll just copy this. And I’ll change itfrom old to recent. I’ll just copy everything up from here and I’llpaste it over here. I’ll make the requiredchanges so over here it’s going to be ours. And that will be23 hours 59 minutes. and 59 seconds Which meansit’s less than one day and the value over hereis going to be true not false. So basically what’s goingto happen over here is if the course has been publishedwithin a day it will return true and if it’s older than it will return false andif it’s in the future also, it’s going to return false.Okay, so I hopeeveryone’s understood this. So basically we have createdthree tests for all courses dot was published recently method and this will definitelyreturn sensible values for past recentand future courses. You can also createa test for review. The technicalcourses application is fairly undiscriminating. It will publish any course including the ones whosepublished field is in future. We should actuallyimprove this setting the started from variablein the future should mean that the course is publishedat the moment but invisible until then so to createa test for a view when we fix the bug earlier, we wrote the test firstand then the code to fix it. Fact that was a simple exampleof test-driven development, but it doesn’t really matterin which order you do the work in our first test.We focused closely on the internal behaviorof the code for this test. We want to check Its Behavior as it would be experienced bya user through a web browser before we try to fix anything. Let’s have a look at the tools at our disposalthe Django test client Django provides a test clientto simulate a user interacting with the code at the view level. We can use thisin the tests dot p y or even in the Shell. So first, I’m going to startwith the shell again here. I actually need to doa couple of things that won’t be necessaryin the test start py file.So for that I’ll just openup the command prompt. And over here, I’ll say from Djangodot tests Dot utils. import setup test environment So now I’ll call the setuptest environment method. And I’ll hit enter the setuptest environment method installs a template renderer which will allow us to examinesome additional attributes on responses such asresponse dot context that otherwisewouldn’t be available. Please make a note that this method does not setup a test database.So next I’ll need to importthe test client class from the Django DOT test module. So from Django DOTtest import client now, I’ll create a variable namedclient and I’ll say this is equal to the client method. Okay. So with this we can ask ourclient to do some work for us. I’ll take a new variablesay response and I’ll say this is equal to client dot get and I’ll just checkthe response dot status code. So as you can see over here, it has returned 200as the status code for this website. Now. This actually means that our websiteis responding well now in case I want to retrievethe content on this website, I’ll just use response dotcontent and I’ll hit enter.So as you can see over here, it has returned all the contentthat’s present on my website. Okay, so till now we’ve actuallybeen working mostly on the back end of our project. But if you’re thinkingthe Django only helps you develop the back endand not the front end wait Django allows you to makeyour website’s beautiful as well now to do that, you will need to learn some of the HTML Basicswhich I’ll be teaching you all. Now, I know manyof y’all would be aware of it. But for those who don’t knowI’m going to help you out by brushing the basicsof HTML to begin with let’s first describe. What exactly is HTML HTML standsfor hypertext markup language a markup language isa computer language that is used to apply layout and formatting conventionsto the Next document markup languages makes the textmore interactive and dynamic.So basically textcan be converted into images tables links Etc. HTML is the standard markuplanguage for creating web pages and web applications. It’s used to describethe structure of web pages using markup the HTML structureHTML tags have two main types. That’s Block Leveland the inline tags Block Level elements takeup the full available space and always start a new linein the document. For example, the tags, including the headings andthe paragraphs inline elements only take up as much space as they need and do not startin the new line on the page. They usually servethe format the inner contents of Block Level elements. Some of the examplesof inline tags are links and emphasized strings. The three Block Level tags that you will needfor an HTML document are the HTML tag the head tagand the body tag.The HTML tag isthe highest level element tag that encloses every HTML pagethe head tag holds meta information such asthe page title and the cassette finally the body tag and closesall the content that appears on the page. So how exactly does htmlwork HTML documents and with the dot HTMLor dot HTML extension. You can view it usingthe web browser. The browser reads the HTML fileand renders the content for the users to view iteach HTML page consists of a set of tags or Elements which are known as the buildingblocks of web pages.They create a hierarchy that structures the content intosections paragraphs headings and other content blocks. So no talking about the HTML headingsHTML headings are defined within the H1 to H6 tags. H1 defines the mostimportant headings. Whereas H6 defines. The least importantones paragraphs in HTML are defined usingthe paragraph tag or the P tag. There is no limit to the numberof paragraph tags. You can add to your contentlinks HTML links are hyperlinks.You can click on a linkand redirect to another document or a web page to create a link. You’ll have to make useof the anchor tag or the are tagged. Okay. So images imagesare required to beautify and depict complex Concepts in simple ways on your webpageHTML images are defined with the IMG tags the sourcefile alternative text width and height are provided asattributes to the image tag. The button element is used for creating an HTML button allthe text between the opening and the closing tags appearsas a text on the button. It defines. Clickable button insidethe button element. You can add text or images lists HTML provides three ways to specifylists of information all lists must containone or more list element.So basically you can haveunordered list ordered lists or a definition list, which arranges your itemsin the same way as they are arrangedin a dictionary. You can also create tablesin HTML using the table tag Rose in HTML are defined within the TR tag headersare defined within the th tag and the cells are definedwithin the TD tags. So now just to showy’all one example of this. I’ll create a newproject of here. I don’t want to messwith the current projects. I’ll just createa new projects HTML. Okay, and over here, I’m going to show y’allsome basics of HTML. I’ll create a new file of herethat we an HTML file. I’ll just name it as sample. So as you can see over here, my ID has already providedthe basic HTML tags for me.I just clear this off from here and I’ll use some alreadywritten in HTML code. So as you can see over here, I basically havea title with says what is HTML after that. I just specifiedthe background color to be black and the font color to be white. I’ve written some text over heresaying welcome to Eddie Rekha and learn about HTML5 center-aligned an image usingthe center tag and the image tag with Source altand the style of it. After that. I’ve created an unordered list which contains a few coursesthat are available at Ed Eureka. Finally. I’ve created a button, but I’ve not linkedthis to anything. So now let me just show you allhow this runs on the browser.Okay. So here it is. I have a black background. I have white font color. I have an image and Ialso have created a button which have notlinked to anything. So now let’s get backto our project. So over here to designmy courses dot HTML page. I’ve already createdsome HTML I’ll just copy paste that code over here. And I’ll save this and I’llrerun my development server. Okay, I forgottento run my project. So I’ll use Pythonmanaged to hpy. runs over Okay, so now my serveris ready to run. I’ll reload this page. So here is the web pagethat I have created. I’ve created a nav barand over here. I have a few options andwhen I click on these options, it leads me to that particularpage on the Adriatica website. Okay. So when I click on edit Erica, I go to the officialaudio record on your website. When I click on blogs and videos it will lead meto that particular website of Eddie Rekha in caseyou want your links to open in a new page.You can specify the targetelement as underscore blank. Now when you do this, what happens is when you clickon the link it will open on the new page. Okay, so there when Iclicked on community, it has gone to the editora community website. So as you can see over here, I have all my options that is python Java and cand I also have some description regarding the self-pacedand the instructor-led courses. I’ve also addedon some images to my website and at the end I’ve specifieda footer with some text regarding my website. So I hope you guyshave liked the sample website that I’ve created. However, there areenormous more options that I leave you guysto explore before moving on towards the do’sand don’ts of Django.I’d like to take a quick recapof what we have done till now. So is the first place we’ve seen how to install Python pycharmand Django after that. We created a Django projectusing the Django admin following that we’ve seenthe various files that Django created for us along with the project namelythe managed py settings dot p y in added py W SG. I dot p y and the URLs dot pyfiles And then using the manage to py file, we’ve gota development server running. The next step was creatinga first app using python manage dot P whitestartapp command after that.We’ve seen how to createour models views and templates. I’ve also shown you guyshow to connect the project to database using migrate andthe make migrations commands. Also our projecthas an admin section that has the abilityto make changes as in how the admin decides to do it. We’ve also created a few testsfor our website in order to keep it free from Bugs. Finally. We’ve seen how to beautifyour website using HTML. Okay. So I hope you guyshave enjoyed this demo something very importantfor you guys is the do’s and don’ts of Django.So coming towards the do’s and don’ts while writingtemplates views and models. So while writingthe Django template code but one and only one spacebetween the curly brackets and the tag content. So as you can see on the screen when you’re writing somethingbetween the curly braces keep in mind not toinsert Extra Spaces and also avoid not givingany space at all. So while writing the Djangoviews the first parameter in a view functionis called as request. So we do writing this parameterspecify it as the complete name which is reqest and not req or any other shortforms the models while writing yourmodels make sure that the field namesare in lower case and it’s better to useunderscores instead of camel case the orderof models inner classes and the standard methodsshould be as follows.The first should be alldatabase Fields followed by the custom manager attributes then is the class meta followed by the Ring methodsafe method get absolute URL and any other custom methods that are left over. So those were a few do’sand don’ts of Django. So moving on towardsthe most frequently asked questions about Django. The first one is according to Django the mostfrequently Asked question is why does this project existsDjango actually grew from a very practical need World online a newspaper weboperation is responsible for building intensive web applications onjournalism deadlines in The fast-paced Newsroom Worldonline often has only a matter of hours to takecomplicated web application from concept to public launchat the same time.The World online web developers have consistentlybeen perfectionists when it comesto following best practices of web development the Worldonline developers ditched PHP and began using pythonto develop its website as they built into Civrichly interactive sites such as Lawrence. Cam they began to extract a generic web developmentframework that let them build web applications moreand more quickly. They tweak this frameworkconstantly adding improvements over two years in Summer 2005 World online decided to open sourcethe resulting software, which is Django Djangowould not be possible without a whole hostof Open Source projects. That is Apache Pythonand the postgre SQL. Okay. So next time on the list iswhat does Django mean? And how do you pronounceit Django is named after Django Reinhardt who’s actually a jazz guitarist from the 1930sto early 1950s to this day.He’s considered one of the bestguitarists of all time. Django is pronounced as Jang. Oh, make sure to keepthe Diaz silent. Another very commonquestion is that if Django is stable? Yes, it’s quite stable companieslike discuss Instagram Pinterest and Mozilla have been usingDjango for many years. Sites built on Jangohave weathered traffic spikes of over 50,000 hits per second. Okay. So now moving on manypeople also asked if Django can scale. Yes compared to the developmenttime Hardware is cheap. And so Django is designedto take advantage of as much Hardware as you can throwon it Django uses a shared nothing architecture, which means you can addHardware at any level that is database servers cachingservers or web applications or servers the framework cleanly separate componentssuch as the database layer and the application layer and it ships with a simple yetpowerful cash framework.So now to answer the question if Django isa Content management system. No Django is not aContent management system or any sort of trunky product. It’s a web framework. It’s a programming toolthat lets you build websites. For example, it does not makemuch sense to compare Django with something like Drupal. This is becauseDjango’s something that you use to createthings like Drupal, of course Django’s automatic. Admin site is fantastic and time-saving butthe admin site is one module of Django the framework. So what python version can you use with Django Djangocan be used with any of the Python versionsstarting from 2.7 till 3.7 Python 3 isactually recommended now, this is because Django 1.1 isthe last version to support Python 2.7 since newer versions of python are oftenfaster have more features and are better supportedthe latest version of Python 3 is recommendedSo one of the very important and the most frequentlyAsked question is how to make changes to modelsand to update the database.Like I’ve alreadytold y’all before when you make changesto the models just py file you have to runthe make migrations command, which is nothingbut python managed or py make migrations now, this will create the migrationfor those changes after that. You’ll have to runthe migrate command which is nothing but pythonmanaged to at py migrated to apply the changesto the database. The reason that there areseparate commands to make and apply migrations is because you’ll commit migrationsto your version control system and ship them with your app. They not only makeyour development easier. They’re also usable by other developersin the production. So can Django supportnosql databases nosql databases are not officially supportedby Django itself. There are however a numberof side projects and forks, which allow nosql functionalityin Django like Anand Rel so how can you customizethe functionality of an admin interface? You’ve got several options? If you want to piggybackon top of the add or change form the Djangoautomatically generates, you can attach arbitraryJavaScript modules to the page via models class.Admin JS parameterthat parameter is a list of URLs as strings pointingto JavaScript modules that will be includedwithin the admin from via a script tag. If you want more flexibility than simply tweakingthe auto-generated forms, feel free to writecustom views for the admin. The admin is powered byDjango itself and you can create custom views to hook into the authenticationsystem check permissions and do whatever you want. This session is mainlya practical session. But before we beginthe Tactical aspect, there is some amountof technical knowledge that you need to have sowe begin the session by first understanding Is an API and how @apifits into the Django after that we’ll havea brief introduction to this framework.And what exactly is this APIand how does it work? Then? We’ll move on to a demo part. We will be buildinga restful web API from the scratch. So let’s begin the session and discuss the veryfirst topic that is what is an API so API refers to applicationprogramming interface. Now, let me break it downinto simple words. So the veryfirst is application. Now, you must be awareof an application. If you’re usinga smartphone say the games that you play in your phoneor the social networking apps that you scroll around or any other software that youuse in your day-to-day life. So all these comesunder your application.Next is your programming. So programming is basicallya set of instructions that you tell a computerto perform a specific task Now using that program. You can build a software whichmakes the life much easier. So that is what programmingis last is your interface now when interface is a point where two applications or you can seeprograms meet at In graph with each other now it basically allows to communicate with oneanother and hence API is a way for programmers to communicatewith various applications. Now if you goby the Google detonation it is set up different subroutines different protocols aswell as different tools that you need to buildan application software. So these are the terminologies that the developermust be knowing. Now. If you look at the imageto the right, you can seehow different environments that are runningin application are communicating with each other through the APInow for running these API, all you need is an environmentthat supports the application and the API which is a partof an application. So with this I guess you’ve gota simple understanding of what is an API.Now if you have any doubtsany query related to any of the concept that I will be teaching youcan feel free to comment below and I’ll be happy to helpyou with the same. Now. Let us move on to our next topic that is an introduction to restFrame Book today’s basically describes an architecture which stands forrepresentational State transfer it is used. Both this of their baby isfor data communication. It also supports some of the common HTTP methodsto make interaction between the machinesor you can say applications. Now some of the HTTP methodsthat are commonly used in this architectureare get put post and delete. So the very first method is dead now get is basically usedto return the records or you can see the datathat you filled in. So basically get is usedto retrieve a resource. Next is your put soput is used to change the state or you can say update a resourcewhich can be a file. It can be objector any block thirdly its post post is usuallyused to create the resource and last is delete which is used to deleteor remove that resource.So this was all aboutresp am work now. Let us seewhat exactly is a rest API. So any web service that uses a rest architecturethey are called as display apis or you can see rest apis. So you must have heardabout Facebook apis or Google apisor maybe Twitter apis. So all of them are -hey, PA, similarly, if you take it on yourselfsay for example, you own a website. You have all your code. You have yourdatabase connection and everything is working fineover there now suddenly you have more users comingto your website and then you decidedto build an iPhone app, or maybe an Android app. So now your next stop would be how to connectthe database online. And now let’s saysome more requests come in and you want to makea software desktop application.So again thesame question arises that how an iPhone connects or how an Androidconnector database online. It needs a website data from there and updatethe same over here. So isn’t this looks confusingand extremely complicated? So what you can do here,you can create a restful API which will serve allyour purpose in one go now making a restful API, you need to have a device access to web site datathrough a common format. So here we’ll be using Json now. Json is the data format and it is not at all specificto any of the device. So basically useJson to communicate within a specific format so that we can buildan Android app and IOS app or any other software that you want to make nowone more key feature that comes into picture is that if you have an API thatperforms certain operations, then you don’t have to rewritethat as part of your code. And thereby it also reducesthe size of the code now, I guess enoughof theoretical part.So let’s just directlyjump into the demo where I’ll be helpingyou to create the first restful API from scratch. So for that you need to Firstinstall the rest framework, so everything can be installedusing python package manager. Now, if you’reusing command line, it is very easy to install as you just have to type in PIPinstall Django rest framework, or if you’re using pycharm, you can directly install itby going to your settings and it’s the same way you do itfor other packages now once your installation is done, you need to add this frameworkin your installed application. So let me go backto my project and explain you how practically it is done. So first of all,let us create a project. I am in my C drive users. Ayush and my Chum project.So here I createa new folder by calling it by Django rest framework. And inside this willbe creating a project. So let me goto my command prompt and I will give this location. Now once you’re under this, let’s just firstcreate a project. So for creating a project youhave to type in Django admin start project for it by the nameof the project is in my case. The name of the projectwould be my project. So as you can see here,I have my project. So once you click on it,it has one more file, which is named as my projectonly and one manage file. So if you go and clickon my project, it has some of I’ll sayin its settings URLs and wsgi. So if you have any confusion, or if you want any explanationrated these files you can go to my previous recording and getthe concepts here. Next what we have to do wehave to create an application.So for that letsgo to my pycharm and open this project. So this is my communityversion of Pi jump. So let me open it. It’s in my see users and chunk projects tango lessonover and my project it is. So this is my pie chart now, you can do the exact same thingsover here as well. Now for that you can goto the view tool windows and you can open upthe terminal like this you first have to installyour Django rest framework. So for that you have to type in pick installDjango rest framework and can click on enter. So now I’ve already installedmy Django rest framework. So it seems that requirementis already satisfied.That is like mine. Well, just clear my screen. So now I’ll be creating a simpleapplication say web app. Now. What are we doingin that application is I’ll be storing some employersinformation say for example, your first-name lastname salaryand all that other stuff. So for that you first need to type in Python managedot P Vai startup and the name of your application. Let’s say it’s web app. You can do the samein your command prompt as well. But I feel my charm ismore convenient for me. So if you go on my project, you see the web appis initialized over here. Now inside this it hasdifferent files it has in it. It has admin panel. It has application does modelsand many more now if you remember Ihave already explained in the presentation that first you need to goto a project settings and configure everything. So I’ll go to my project. This is my settings and inside this I have to goto my install applications and have to writeit rest framework. I also have to writein the name of the application that have just created.So once my projectsetting is configured to what I’ll do next I goto my application and I’ll go to my models. So here I’ll be creating a model or you can say databasevery good feeding all the necessary detailsof the employed. So here I create my first model. I don’t need this so I will create a classover here grasp employees. modest Let me fill in somedetails for the employee class. Let’s say your first nameof the employee or the last name or some employee to it. So let me feedin some details to it. But I’ll mentionthe max length to say 10. Next is my last name attribute. Again, Max and should be10 and let’s say one more field. I want to feedin say employee ID. This should bean integer field next what will have will havea string representation of this. So here what I will be doing.I’m creating a methodthat returns all your fields. And it returns sayself DOT first name. Next what can I do? I can go to my admindot py file now here I can add and delete employeesfrom the admin panel. So for that we needto First import the model that you’ve just created sohere my Adam is important. So here I haveimportant my model which is named as employees. Next up is register this model so that we need to writeadmin dot sight register and your name of your mother. That is my employees. So once your adminpanel is created, you need to Firstcreate a super user so you can again go to your terminal and you cancreate a super user for that. So here is my terminalI can directly write python manage dot Pby P it super user. Oops, no hate you some error or because I’m notmigrating my table. So first we needto migrate a table. So for that we need to typein Python manage dot P Vai and make my gracious.So this will basicallyupdate your table structure. So once you migrations are done,you just need to migrate it. So you have to write my great. So basically creates your tablewith the current structure and it feeds in all the details that you have writtenin your model. That is your employee class. So here your projecthas been migrated now. Let me create a super user. So notice me for username.So let me typein my Yoshi email address. You can leave it blank as welland after given some password. Make sure you havea strong password for this. So now my Superior createdsuccessfully so now I can turn my server for unmaskover the command. Is python manageddot P by 1 Circle? Now it is successfully started. So I’ll open my Google and Iwrite it over here localhost. So here as you can see, there is no web pagethat can be displayed over here. But we do havea sweet admin page. Let me open the add newpage view so ask them for the username and passwordthat are just created. So my username is IU sheand I have some password. So as you can see here, I have that web app thatI’ve already created inside that I have graded and modelwhich says employees now once we go into that it hasan option to add an employee. So now let me add some detailsto these employees. So the very first nameis say Swati last name.Let’s an employee ID is 1 now. Let me add some more to thisso it may be baked. Say to and I’ll addone more appeal Ash. So the employee ID, so and I’ll add onemore that is so neat, but I do spy. Now here as you can seethere is a list of employees that have just added now. Once you click on them, you’ll see all the necessaryinformation regarding it the first name the last nameand the employee ID that you have assigned to itand you can directly delete it from here as well. Now while going back to it the seat again the listof the employees now, let me go backto my code and see what else you have to do. Now. Let us create a CLI is a class. Now. This class is used to convertyour model to your Json data. So Jason and I have alreadytold you this in is a format and is know-it-all specificto any application. Now Jason is used because whenever a userrequests a web site, we usually send them back a regular old HTML formatwhich team responds now, however, we don’t want HTML.It’s only when you wantinformation from the browser. So here we’ll be sendingthem Json for that. We need a way to convertthis model to Json. So hence as Eliezer is usedso I’ll go to my application. And I create a newpython file and name it as she realizes. So you can see this file righthere in the web application. So inside this we need to importsome stuff from this paper. So first I’ll importthose things from rest framework Imports eliezer’sNext I have to import my model that is employees. So here now. Let’s create a class. So class employeeforward bias utilizar. teenagers So herethis is my model name, which is my employeesfollowed by a Serial iser. So whatever model you want tosee the lies just say the name of the class followedby his Eliezer keyboard next this utilizers not model serializer is your inbuilt thing youdon’t have to worry about this because you just haveyour modern as a blueprint which the serializer needsto convert to Json format. So next what we haveto do we have to create a class meta and forthe configure it so I’ll create a classand fill in the various fields that are usedin an employee model.I’ll create a cast metal and here I will writemodel the name of my model is employees next haveto configure my feel. So if I open my models and here I have first namelast name and employee ID. So let’s say I just needfirst name as a response. So here what I’ll doI’ll hear right feels equal to your first name. If you need one more field, let’s say last name you needfirst name you need last name, but you know need employee IDso you can manually write that you need to display onlyfirst name and last name or if not this you can do one morething to display all your fees that is feels equal to underscore underscore alland double underscore again.So this is basicallyreturn oil fields present in your employ a model. So now it will display a firstname last name and employee. So I have done this because I don’t havemuch feels to return that’s why I returned all next. Let us go to the Viewsto py file and see what we need to displaywhen we hit the API. So this is my viewtop view by file. So in this file top youhave to do we have to just request an API and getthe Json back for that. First of all,you need some imports. So I’ve already copied them. So let me just paste it overhere the say it’s my time. Now don’t worry. I’ll explain each one of them. So the very first is by default. Next is your HTTP response, which have been usingfor any program to turn.The response. Next is your get object or 404. Now we get 404 windowobject doesn’t exist. Say for example, York where some randomname let’s say Emit and this doesn’t existin the company’s database. So what will happenit will return a photo for so for example, I show you practically soas you can see here, I have these men employs overhere and say I have requested some different name. Let’s say I’m it and this doesn’t existin my company’s database. Therefore it will return a photofor now coming back to my code. Next is your API viewNow API view is used so that the normal view scanreturn an API data next is your response. So this is where youget back the status or a particular response. Now, everything went fine. It will deter a 200 response or you can see two zero zeroresponse similarly the 404 that we have just discussed. It says that youhave requested something but it doesn’t exist anymore. So these are someof the HTTP responses and there are many morelike that say 401 is not found 500 is a server errorand things like that.Next is your status which will basicallysend back status. After that. We have the name of the modelthat is my employees and then the name of the serialize orthat is employee serializer next what we have to do we haveto create a class based view which basically inheritsfrom an API view. So let me create a classfor it C-Class employee list. And this inheritsfrom an API view. So here we will createtwo method get method and a post method. So the very first methodthat is your get method. It is used to return allthe employees in our model and then the second method which is your post methodit helps you to create a new employee. So let me createthese methods one by one. And the next methodthat is my post. So now what I’ll do is I’ll goin my first method. I’ll just remove the scarswhich basically means to nothing and here I will passin the request.Now we’ll create a variablewhich stores all my object. So let me name it as employees or you can see employeesone will have my model and will say object at all. Next we have to see youlike them which means that it will takeall your object and convert them into Json. So I’ll take thishere Eliezer for that. That takes Eliezer. So this is the nameof my serializer and here I will passin the employee which means all your objects and the second parameterwould be many is equals to 2. So this second parameterthat you can see here. It means that thereare many of them. So here you don’t have to returnjust one Json object next. We know every view functionreturns an HTTP response. So in our case, it’s Json.So what we have to do wehave to return a Json. serialized dataThis is sterilizer. Next is imposed function withsay submitting all your data. Whereas your gate functionis reading or taking your data. Now with this we havecompleted our views pain. Now what you have to dohave to connect or link it. So for that we haveto go to URS fine. So here we go to a main project that is my project and we’ll goto URL start py file. So here you haveto add some imports which are compatible with apisand rest framework.So I will add herefrom this pain book. Explaining later as we go on and have more functionsto play with. So in my code, you will not be requiring thisas such but other things you require is to import your view. So for importingyour view you have to type in import loose now, as you can see here, it is onlylinking to my admin panel, but now we have to createour own URL to display the view for that. I’ll just copy the same lineand I’ll paste over here. So you must be knowing that these are in the formof regular expression. So in spite of admin I can type in employees so thatwhenever I hit on employees if you return my view just to make it easier I haveto type induce dot employee list that we have just created.So by hitting on employees, it will connect to my viewand in my view there is a class called as employees. So I’ll go to My Viewsand here I’ll see I have my list that is employee list and we’ll turn these thingsas a view therefore going on employees. It will go to My Viewsand then it will turn the class that is employee list as view. So in this way, we will get the datain a Json format.So with thisAccord is completed. Now what you have to do youjust have to throw this URL and connect toany website database and from that you can get allthe information from any device in the world be it. I phone with Android anything. So now let me go backto my server and see whether this APIis working or not. So this is my Local Host till I have to writeemployees which is My URL that I’ve just created.Okay. So this is showing me an errorthat name true is not defined. So let me go backto my code and see in My Views file. Now this will work. So well again, go to my local hostand I’ll refresh it. So, yes, it displayed. So as you can see here, I haveall my employee information. I have their IDstheir first name and the last name. So this is the format of Json which are basicallysurrounded by curly braces having all your dataand a descriptive title to it. Now using this URL. You can check it anywhere andretrieve the same information. You can get it using any device in the world with your iPhoneAndroid or anything. So I’ll just copy this URLand go to the browser and I’ll open my Postman. So here I just paste my URL.So as you can see here, we are differenttypes of requests. We have Gerd we have post putpatch delete and many more. So here I’m going to Simplymake a get request. So I already pasted my APIand does I have to send it. So yes, this datais going displaying. So as you can see here,I have my data in Json format, which means that my APIis working perfectly fine. Let us move forwardwith the project. So here I have justcreated a demi website which displays all yourcourses the description along with the date and time bagged upwith the database. So in this I have usedfew of the companies that we have discussedand some of the advanced stuff.So let me just showcase the project view. So let me open my project. It’s in my DIY Yoshi and Djangoproject Django tutorial. Even current window now, let me just runthe server and let’s see what exactly this place. Oops, I guess Ihave not imported with the manager py file. So let me do it again.So inside Django toil demo. I have a managed a py file. So again, I haveto run my server so we serve is now running. So let me just open itand I’ll just go to Local Host. So this is how my websitelooks like now here. I have some static filesand some text displayed. So here ismy python Java tutorial, which is the headerof the website and here in the left hand side. I have their doregalo go just below that I have a navigation barwhich contain three tabs. That is Home tab courses Tab and contacts tab after thatin the same div container. I have place for static files, which says Eddie Rekhahas live classes. It has exposed instruction. It has wrinkles and supportand flexible scheduling and towards the endin the photo. I have given contact youcan contact the Ada regard supported recorded for then we haveFacebook Facebook page of a dairy cow opens up next.We have YouTube. So here I have given the link which opens upthe Eddie reoccur channel. So this ishow the website looks like now if I go to home itwill just Okay, because I’m doing it Rica but if I go to courses so it will providea lot of courses. So here I put a slider with changes automaticallywith a number of objects that it has. So right now I justhave Django and python. So if you click on python, the detailed descriptionwill be displayed. So Python and The Coresubscription is below and when it was published,it’s all written. It’s the date and timehas been mentioned similarly. If I go to courses again sameis the case with Django Django, it displays the descriptionand the date and time with respect to itlast we have contact.So in contact I have justdisplayed The View which says contact in support and Erica.com which basicallygives 24/7 support. So this is how my website lookslike now in the courses tab, I just have two objects. So let me go to admin page andlet’s add few more courses. It’s already createda user name for this project. So the username is IU sheand the password and specifying so this ismy Administration panel that we have just split now one more thing that youmust be noticing over here is the courses now here you have just letme pull it through here. So inside courses I havea model which is post. So once you click on this ithas boast now here it displays just two objects now here Ican add unlimited courses. Now, let’s haveto upload a new course which has a name. Let’s say uphere and description. I just write thisis a new course. So then you can just providethe date you can select today and you can selectthe time is now and then you justsimply have to save it.So now as you can seethe post has been added once you go backto your website here will see the course will be added. I’ll just refresh this page. So here as you can see our PAis added now if I click on that it will display with the descriptionthe date and time. So this ishow the website works. So now let me just walk youthrough the code of it. So for that I’ll justcome out of my server. So this is my project structure. Now, the main applicationthat I have is demo. So I’ll go to my project demo and I will see the settings areyou can see the URLs where the user is been hitting.So there are three URLs. The first is the adminwhich is by default. Secondly, I have createdmy daughter URLs and then I have createda separate application which is courses and I’ve given a separate URLthat is courses that URL. So these arethe two applications that have created and I’ve givena separate URL to it. So now let me goto my first application. That is my so I’ll goto my application and go to URL State p y so hereI’ve defined my URL patterns. Now, we know that you area patterns are in the form of Rebel Expressions.So this is my home pagewhere we have a view where we have index method which must be placed in View and we have givena name space to it second. We have contacted again. I have created contact methodand given a name space to it. Let me just reviewthese two methods in the views of py file. So here these twomethods are defined. So the very firstmethod is index. So here we have againnot return the HTTP response. So here what we have done. We have simplyreturn the templates. So what I have done I have Ihave created a template which is home dot HTML and thereI have passed dictionary which has a key post and then it has post oneand postal similarly contacts.I have created one more HTMLthat is basically HTML and there I have justpassed a dictionary which has a kiosk content. So this is my dictionary and then I have passedthe content to it, which says contact supportedEddie regarded go. So, these are my two temples which says home but HTMLand basic dot HTM with so let me just go to mytemplate folders and let’s see what exactly istheir home in basic. So as you can see here,it was extends headed on HTML and then it will justdisplay this text. That is he Welcome to edu Rica. So this is presentin the ginger logic. Now, if I go to header dot HTML, which it has extracted,so let me just go to Hello dot HTMLand here you’re all HTML is present.So this is my header part where I just displayedwill come to order a car and then I have loadsome static files which are the images now inside that I’ve alsoused some bootstrap which has a link of this. So if you come downyou have a body class which has a div container. So if you guys arefamiliar with HTML, so you will reallycatch up the soon.So inside this the faceof a static file and the text accordingly. So here I have giventhe source of the image. I paid one more folder that is staticand inside static. I have my application. Then you have foldernamed as image and then the name of the image. So if you see here, I have a folderwhich is static then it has the same name as thatof my application. And inside this Ihave already told you that I’ve used some CSS. So this is the bootstrapthat I’ve already downloaded. So it’s up to you if you want to use itor you don’t want to use it. So just torepresent this better. I have just downloaded the bootstrap and thenI’ve just put it over here.So I will just showyou from where you can download the bootstrap. So I’ll go to Googleand I’ll just type in bootstrap. So this is the website from where you candownload a bootstrap. So here it has a lot of things that you can tuck this so hereit says download bootstrap, you know the sourceand many other things are there. Now if you seeat examples you can find a million examples over here. So what I’ve doneI’ve just simply downloaded this bootstrap.So this is a ZIP filethat comes with us. So what I’ve done I’ve justextract this folder and just paste it over here. So this file containsa CSS your phones and your JavaScript. So this already contains a lotof things it has CSS. It has themesand many other things. Now. The one thing that I have addedis the image folder now here if you see I have addedthese six images in the website if you click on that. So this is the first imagethat I’ve added to the website. Let me show you where this image isexactly on the website. So this is the first imagewhich has a name of Life gases. So this is my first imagesimilarly there is second image.And similarly I haveother feature images as well. This is my feature to thisis my picture 3 and this is my feature for so theseare the all the static files that I’ve uploadedto this website. So here in my div tag, I have given the sourceas static my image and the name of my image. Similarly. I have done it forall the images next. I have created a navigation bar, which is therein the left hand side. So this is my navigation bar which contains three tabs thatis home courses and contacts. So this is my homecourses and contacts. So here I have used the list which goes to different URLsat the same time. So if I go to my home, I have a different viewwhich is displayed if I go to courses, I have different Viewand similarly with contact.So this is all about my leftnavigation bar again. I have created one more div tag where I have placedthese static files. Snakes and also createdone more div tag where I have placed slider. So this is a sliderthat I’m talking about. This is this codefor slider and in the end. I just added a photo so input or I have just addedthe hyperlinks to it. So if you click on contacta new URL will open if you click on Facebooka new link will open and similarly with the YouTube. So my my applicationis completed now, let me go to the otherapplication which is courses. So if you go to the URLsof the main project this I have already covered so next letus go to the courses application and just hop into courses that URLs.com socourses I’ll go to URL stir py file. So here I’ve createda URL pattern now here. I’ve already told youthat in courses. I have created a list. So let’s it collectsdifferent objects, which is createdin a admin panel.So here I have writtena query state which says post which is the name of my modeland then we have set. All the object and then wehave ordered by date now – it representsthe descending order and if you wantto place a limit to it, you can place a limit. Let’s say 25. So only 25 coursescan come at one go next. I paid one more templatewhich is courses of HTML and if you need a detaileddescription to it, you have to create another URL which has a PKwhich is a primary key.Now, we will not create a primary key Djangodoes it for you? So here it will representthe first column in the module. So here I have specifythe models my post and here I have displayedone more template which is inside my coursesand excess post dot HTML. So let me go to coursesand post at HTM. So inside my templates, I have two templatesthat is courses and postage label. So this is the HTMLfor my slider. So it’s againextending my main HTML, which is header dot HTMLThe Inheritance is taking place by the keyword that is extinct. Now everything isinside your Ginger logic now here I have started a loopwith says put Post-it List, the object list is the listof all the objects which are there in post now.What is postsupposed is my model. Let me first go to my models. So here I’ve paid one model now, I have created a classwhich is post. I have different feels likecourse description and date. So this course hasthe maximum 140 description. It has a text. We love thisand similarly the date or create one more method which basically returnsyour cell dot course. So once your modelhas been created, let me go back to my coursesat HTML and he replied for Loop which says each objectshould come in the list. So here I have displayedthe post date date should come in this format to displaythe year first then the month followed by the date after that.I’ve just given a hyperlink which says coursesand it will fetch the post ID, which is the workof primary key. Basically, it will justtells which column or which forces it has picked upfrom so this is my slider. Next is a poster HTML. So in this post dot HTML, I Just inherit the sameheader or HTML file. And inside thisI have to display the course description and date. Now if you notice here, I have written postat body safe and line breaks. So if you go to my websiteand if I go to inspect so you can actually see thisin different formats. Let’s see if you want to seethis website in iPhone 6.So this is how my website will looklike an iPhone 6 similarly. You can try for differentdevices as well. Also if I closethese tabs Now similarly if I open my tab andif I squeeze this window, it will not change anything. So this is what these things do. So this was allabout my project. So I hope you geta simple understanding of what exactly all these components and how exactlythese components work.So now moving on towardsthe final topic of this session in which I’m going to be sharing a few very importantDjango interview questions. Now one of the mostcommon question of Django is if it is betterthan flask or not Django and flask both map the URLs or addresses typedin the web browsers to functions in Python flask ismuch simpler compared to Django but flask does not doa lot for you. Meaning you will needto specify the details. Whereas Django does a lot foryou wherein you would not need to do much work Django consistsof pre-written code, which the userwill need to analyze whereas flasks gives the userto create their own code. So now we’ll be goingtowards the next question which is the differencebetween Django pyramid and flask flask is actuallya micro framework guys, which is primarily built for small applications withsimpler requirements in flask. You have to useexternal libraries. However, flask is readyto use pyramid is built for larger applications. It provides flexibility and lets the developeruse the right tools for their product the developer can choose the database URLstructure templating style and more pyramid ishighly configurable Django on the other hand can alsobe used for larger applications just like pyramid and it also includes an orm orm actually stands for objectrelational mapping layer.Now, this layer can be used tointeract with application data from various relational databasesuch as sqlite MySQL Etc. So now moving ontowards the next question, which is theDjango architecture. Like I’ve already told y’all before Django follows an MVCMBT architecture MVC stands for View controller it is usedfor developing web applications where we break the codeinto various segments here. We have three segments namely the module Viewand the controller module is used for storingand maintaining data.It is the back end where your databaseis defined views on the other hand areall about presentation and it is not at all awareof the back end it basically deals with more of HTMLa controller is a business logic which will interactwith the model and the view. So now talking about the MBT architectureof Django mvt stands for model view template in mvt. There is a predefined templatefor user interface.Say for example, you write severalstatic HTML forms, like hello user 1 hellouse with 2 and so on the template youwill be having only one file that prints hello alongwith the variable name. Now this variablewill be substituted in that particular templateusing some ginger logic. That’s the magic of template. You don’t need to rewritethe code again. And again, however in the MVC architectureDjango itself takes care of The controller partso now moving on towards the next question which is how to set upthe database in Django. So I like I’ve already told youall before the sqlite database comes as a default configurationalong with Django if you’re new to databases and you’re just interestedin trying Django, this is the easiest choicesqlite is included in Python.So you don’t needto install anything else to support your database in case you’re workingon some real big project. You will need to usea more robust database like Oracle MySQL Etcnow to connect a project to the database you’ll haveto type the command python manage not py migratethe migrate command. Like I’ve already told you all before we’ll lookat the installed apps settings and creates any necessarydatabase tables according to the database settingsin your settings dot py file. So now moving ontowards the next question, which is given example ofhow you can write a view in Django for an example ofhow to write a view in Django. You can actuallyrefer to the code. I’ve shown youall before so here. What our final view looked likea view basically shows the user what he sees on the website and like I’ve alreadyexplained all this to y’all before it either has a responseor a random method which will return the requireddata to the user on the website.So here is an exampleof you guys. So now let’s move ontowards the next question, which is mention what the Django templatesconsists of the template is a simple text file. It can create any text-basedformat such as XML CSV HTML Etc a template contains variables that get replacedwith the values when the templateis evaluated and the tax that control the logicof the template. So now moving ontowards the next question, which is what isthe use of session in Django framework Djangoprovides a session that lets you store and retrieveon a per site visitor basis Django abstractsthe process of sending and receiving cookiesby placing a session ID cookie on the client side and storing all the related dataon the server side, so The data itself is not storedon the client side.This is actually very nicefrom a security perspective. So now moving ontowards the next question, which is list out. The inheritance tilesin Django in Django. There are basicallythree possible inheritance tiles the abstract base classes. This style is used when you only want the parentclass to hold information that you do not want to type out for each child modelThe multi-table Inheritance The multi-table Inheritanceis used if you are subclasses and existing model and need each model to haveits own database table. The third one is proxy models. You can use this model if you want to modify the pythonlevel behavior of the model, however without changingthe models fields, So now moving on what isthe difference between a project and a nap now manyof us actually get confused between apps and projectsan app is a web application that does something for example in the webblock system a database of public records isa simple app a project is actually a collectionof configurations and apps for a particularwebsite a project can contain multiple apps and app can bein multiple projects.So now moving ontowards the final question of this session, which is what isa Model A model is actually a single definitive sourceof truth about your data. It contains the essential fieldsand behaviors of the data. You’re storing Djangofollows the dry principle or the do not repeatyourself principle. The goal is to Defineyour data model in one place and automatically derivethings from it. This includes the migrations, for example migrationsare entirely derived from your models file and areessentially just a Treat the Django can roll through to updateyour database schema to match your current models. So with this we’ve reachedthe end of the session on Jango full course, make sure to practice as muchas possible and in case you have any doubts or queries, please do let me knowin the comment section and I will revert to youat the earliest good bye and take care. I hope you have enjoyedlistening to this video. Please be kind enough to like it and you can comment anyof your doubts and queries and we will reply them at the earliest do look outfor more videos in our playlist And subscribe to EddieRica channel to learn more.Happy learning..

As found on YouTube

Share this article

Leave a comment