Django - Create your first project
In this tutorial, we are going to build a simple Django application. The home page and the login page are the only pages on this application. But we can see different concepts in Django.
The first step is to create a project. Use this command to create a new project with the name "webpagerender". This command will create a folder with the same name as the project. Inside this directory, you can see there is a main application with the same name as the project and a manage.py file.
django-admin startproject webpagerender
Inside the project directory, open a terminal and give this command to run your application.
python manage.py runserver
Now the development server is running. You can access the website by entering this URL in your browser.
http://127.0.0.1:8000/
You will get a webpage like this.
Now we need to think about the requirements. We want a login page and a home page. Here is a demo of the login page. We are not going to implement authentication here.
We can start by creating a URL for that page. For that purpose, go to the main application folder called "webpagerender," where there is a urls.py you can find. Create URLs for the pages.
For the creation of URLs, we use the path function. Do you get confused with the second argument of the path function? Dont't worry! It's a function that we are going to create next.
Inside that folder, create a Python file called "views.py." Inside that, create two functions with the names "login" and "home". These functions must take one argument and return a response.
You can access the home page through this URL: http://127.0.0.1:8000/home
You can access the login page through this URL: http://127.0.0.1:8000/login
But this is just an HTTP response. We need to render an HTML document, actually. For that, we need to create a template directory inside the root directory. Then create HTML pages inside the templates directory. Then you need to specify your templates directory inside the settings.py file (line number 59). Also, you need to import the OS library inside the file.
Now check your browser for the changes.
You can access the home page through this URL: http://127.0.0.1:8000/home
You can access the login page through this URL: http://127.0.0.1:8000/login
How its work?
When a client (browser) sends a request to the server, the server checks the incoming URL and compares it with the urls.py file within the main application. If the URL pattern matches, then it will call the corresponding function. The function will render the HTML file and return it back to the client.
Comments
Post a Comment