Django 02
Django 02
Framework
Merit Ehab
Templates
● A base template is the most basic template that you extend on every page of
your website.
● In your blog/templates/blog/ create an new file base.html.
● Edit base.html and copy everything you have index.html in it.
● Replace whatever after the page-header div in the body with those tags
{% block content %}{% endblock %} and save the file.
● You used the template tag {% block %} to make an area that will have HTML
inserted in it. That HTML will come from another template that extends this
template (base.html).
Templates
● In blog/templates/blog/index.html,
remove everything above and under
<h2>Blog Index!</h2>.
● If you visit your webpage once more you will find that everything works as
expected.
Models
Models
● A model in Django is a special kind of object that is saved in the database.
● We store our models in <app_dir>/models.py => blog/models.py.
● Edit blog/models.py and write the following code.
Models
Models (Field Options)
null Django will store empty values as NULL in the database. Default is False.
db_column The name of the database column to use for this field.
peimary_key If True, this field is the primary key for the model (null=False and unique=True).
verbose_nam A human-readable name for the field. If it isn’t given, Django will automatically create it
e using the field’s attribute name, converting underscores to spaces
title = models.CharField(null=False,blank=False,default=“Untitled”,unique=True)
os = models.CharField(......,verbose_name=_(‘Operating System’))
Models (Field Options)
EmailField A CharField that checks that the value is a valid email address.
auto_now Automatically set the field to now every time the object is saved.
auto_now_add Automatically set the field to now when the object is first created.
Models (Relationships Field)
ForeignKey A many-to-one relationship.
on_delete
to_field
Models (Relationships Field)
Models
● To add the new model to our database, we have to let django know about our
change.
python manage.py makemigrations blog
● To apply the migration file you have just made to your database
python manage.py migrate blog
Django Admin
● Register your Post model in the
blog/admin.py to be able to add, edit,
delete posts through the django
admin.
OR
Django ORM & QuerySets (Select...Where)