unit-4 Django
unit-4 Django
Django takes care of the difficult stuff so that you can concentrate on building
your web applications.
Template
A template is a file where you describe how the result should be
represented.
Templates are often .html files, with HTML code describing the
layout of a web page, but it can also be in other file formats to
present other results, but we will concentrate on .html files.
Django uses standard HTML to describe the layout, but uses Django tags to
add logic:
<h1>My Homepage</h1>
When a user requests a URL, Django decides which view it will send it to.
Django receives the URL, checks the urls.py file, and calls the
view that matches the URL.
python --version
If Python is installed, you will get a result with the version number, like this
Python 3.9.2
If you find that you do not have Python installed on your computer, then you can
download it for free from the following website: https://www.python.org/
PIP
To install Django, you must use a package manager like PIP, which is included in
Python from version 3.4.
To check if your system has PIP installed, run this command in the command
prompt:
pip --version
If PIP is installed, you will get a result with the version number.
It is suggested to have a dedicated virtual environment for each Django project, and one
way to manage a virtual environment is venv, which is included in Python.
With venv, you can create a virtual environment by typing this in the command prompt,
remember to navigate to where you want to create your project:
Windows:
py -m venv myproject
Unix/MacOS:
myproject
Include
Lib
Scripts
pyvenv.cfg
Then you have to activate the environment, by typing this command:
Windows:
myproject\Scripts\activate.bat
Unix/MacOS:
source myproject/bin/activate
Once the environment is activated, you will see this result in the command
prompt:
Windows:
(myproject) ... $
Install Django
Finally, we can install Django.
Windows:
4.0.3
My First Project
Once you have come up with a suitable name for your Django project, like
mine: myworld, navigate to where in the file system you want to store the code
(in the virtual environment), and run this command in the command prompt:
myworld
manage.py
myworld/
__init__.py
asgi.py
settings.py
urls.py
wsgi.py
These are all files and folders with a specific meaning, it is more important to
know that this is the location of your project, and that you can start building
applications in it.
Run the Django Project
Now that you have a Django project, you can run it, and see what it looks like in a browser.
Navigate to the /myworld folder and execute this command in the command prompt:
py manage.py runserver
You have 18 unapplied migration(s). Your project may not work properly until you apply the
migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.
December 02, 2021 - 13:14:51
Django version 3.2.9, using settings 'myworld.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
Open a new browser window and type 127.0.0.1:8000 in the address bar.
The result:
Django Create App
Create App
I will name my app members.
If the server is still running, and you are not able to write commands,
press [CTRL] [BREAK] to stop the server and you should be back in the
virtual environment.
Views are usually put in a file called views.py located on your app's folder.
members/views.py:
members/views.py:
def index(request):
return HttpResponse("Hello world!")
URLs
Create a file named urls.py in the same folder as the
views.py file, and type this code in it:
members/urls.py:
urlpatterns = [
path('', views.index, name='index'),
]
The urls.py file you just created is specific for the members
application. We have to do some routing in the root
directory myworld as well.
There is a file called urls.py on the myworld folder, open that file
and add the include module in the import statement, and also add
a path() function in the urlpatterns[] list, with arguments that will
route users that comes in via 127.0.0.1:8000/members/.
myworld/urls.py:
urlpatterns = [
path('members/', include('members.urls')),
path('admin/', admin.site.urls),
]
In the browser window, type 127.0.0.1:8000/members/ in the address bar.
Create a templates folder inside the members folder, and create a
HTML file named myfirst.html.
myworld
manage.py
myworld/
members/
templates/
myfirst.html
Open the HTML file and insert the following:
members/templates/myfirst.html:
<!DOCTYPE html>
<html>
<body>
<h1>Hello World!</h1>
<p>Welcome to my first Django project!</p>
</body>
</html>
Modify the View
Open the views.py file and replace the index view with this:
members/views.py:
def index(request):
template = loader.get_template('myfirst.html')
return HttpResponse(template.render())
Change Settings
To be able to work with more complicated stuff than "Hello World!", We have to tell
Django that a new app is created.
Look up the INSTALLED_APPS[] list and add the members app like this:
myworld/settings.py:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'members.apps.MembersConfig'
]
Then run this command:
py manage.py migrate
Which will produce this output:
Operations to perform:
Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... OK
Applying admin.0002_logentry_remove_auto_add... OK
Applying admin.0003_logentry_add_action_flag_choices... OK
Applying contenttypes.0002_remove_content_type_name... OK
Applying auth.0002_alter_permission_name_max_length... OK
Applying auth.0003_alter_user_email_max_length... OK
Applying auth.0004_alter_user_username_opts... OK
Applying auth.0005_alter_user_last_login_null... OK
Applying auth.0006_require_contenttypes_0002... OK
Applying auth.0007_alter_validators_add_error_messages... OK
Applying auth.0008_alter_user_username_max_length... OK
Applying auth.0009_alter_user_last_name_max_length... OK
Applying auth.0010_alter_group_name_max_length... OK
Applying auth.0011_update_proxy_permissions... OK
Applying auth.0012_alter_user_first_name_max_length... OK
Applying sessions.0001_initial... OK
(myproject)C:\Users\Your Name\myproject\myworld>
Start the server by navigating to the /myworld folder and execute this command:
py manage.py runserver
In the browser window, type 127.0.0.1:8000/members/ in the address bar.
SQLite Database
When we created the Django project, we got an empty SQLite database. It was
created in the myworld root folder.
In the /members/ folder, open the models.py file. It is almost empty by default,
with only an import statement and a comment:
members/models.py:
members/models.py:
class Members(models.Model):
firstname = models.CharField(max_length=255)
lastname = models.CharField(max_length=255)
The first field, "firstname" is a Text field, and will contain the first name of
the members.
The second field, "lastname" is also a Text field, with the members' last
name.
Next time you run py manage.py migrate Django will create and execute an SQL
statement, based on the content of the new file in the migrations folder.
py manage.py migrate
Which will result in this output:
Operations to perform:
Apply all migrations: admin, auth, contenttypes, members, sessions
Running migrations:
Applying members.0001_initial... OK
py manage.py shell
>>> Members.objects.all().values()
Hopefully, the result will look like this:
members/views.py:
def index(request):
mymembers = Members.objects.all().values()
template = loader.get_template('index.html')
context = {
'mymembers': mymembers,
}
return HttpResponse(template.render(context, request))
Add a new template in the templates folder, named add.html:
members/templates/add.html:
<h1>Add member</h1>
members/templates/index.html:
<h1>Members</h1>
<table border="1">
{% for x in mymembers %}
<tr>
<td>{{ x.id }}</td>
<td>{{ x.firstname }}</td>
<td>{{ x.lastname }}</td>
<td><a href="delete/{{ x.id }}">delete</a></td>
</tr>
{% endfor %}
</table>
<p>
<a href="add/">Add member</a>
</p>