django_pdftodo_ko1z5byyhxvrnuoszphf1zwm.pdf
Document Details
Uploaded by LeanPrehnite
Tags
Full Transcript
Models and Migrations 2024 7, 12:34 desired name to db_table parameter of the Meta class, to be declared inside the model class....
Models and Migrations 2024 7, 12:34 desired name to db_table parameter of the Meta class, to be declared inside the model class. class Student(CommonInfo): Django fields #... In this reading, you will learn about different field types in a model class. class Meta(CommonInfo.Meta): db_table = 'student_info' Model You should choose the model field type appropriate for the data stored in the mapped field. A model in Django is like any normal Python class. The ORM layer maps this model to a database table in the Django project. The types are defined in django.forms module. The choice of type determines the HTML widget to use when the form field is Each attribute of a model class represents a field in the table. rendered. For example, for a CharField , HTML's text input type will be used. The Django ORM enables storing and retrieving data in tables, not by executing raw SQL queries, but by Django also auto-creates the form based on model definitions (it is called ModelForm ), using field types. invoking the model methods. A model class subclasses the django.models.Model class. A typical definition of a model class is done inside Field properties the app's models.py file. A Field object has common properties in addition to the field-specific properties. from django.db import models primary_key class Person(models.Model): first_name = models.CharField(max_length=20) ○ This parameter is False by default. You can set it to True if you want the mapped field in the table to be used as last_name = models.CharField(max_length=20) its primary key. to hold a unique auto-incrementing number. ○ It's not mandatory for the model to have a field with a primary key. In its absence, Django, on its own, creates an When you migrate this model (you need to include your app in the INSTALLED_APPS setting), the myapp_person table will be IntegerField to hold a unique auto-incrementing number. created as would be done by the CREATE TABLE query: default CREATE TABLE Person ( ○ You can also specify any default in the form of a value or a function that will be called when a new object is created. id INTEGER PRIMARY KEY, first_name VARCHAR (20), class Person(models.Model): last_name VARCHAR (20) name = models.CharField(max_length=50) ) address = models.CharField(max_length=80, default='Mumbai') Note that the first_name and last_name are the class attributes corresponding to the fields in the table. unique Django automatically names the table as appname_modelname , which you can override by assigning the ○ If this parameter in the field definition is set to True, it will ensure that each object will have a unique value for For a longer string, use TextField. this field. IntegerField: tax_code = models.CharField( ○ The field can store an integer between -2147483648 to 2147483647. There are BigIntegerField , SmallIntegerField max_length = 20, and AutoField types as well to store integers of varying lengths. unique = True ) FloatField: Choices ○ It can store a floating-point number. Its variant DecimalField stores a number with fixed digits in the fractional part. ○ If you want to create a drop-down from which the user should select a value for this field, set this parameter to a class Student(Model): list of two-item tuples. grade = models.DecimalField( max_digits = 5, SEMESTER_CHOICES = ( decimal_places = 2 ("", "Civil"), ) ("2", "Electrical"), ("3", "Mechanical"), DateTimeField ("4", "CompSci"), ○ Stores the date and time as an object of Python's datetime.datetime class. The DateField stores ) datetime.date value. # declaring a Student Model class Student(models.Model): EmailField semester = models.CharField( ○ It’s actually a CharField with an in-built EmailValidator max_length = 20, choices = SEMESTER_CHOICES, FileField default = '1' ○ This field is used to save the file uploaded by the user to a designated path specified by the upload_to parameter. ) Field types ImageField The django.models module has many field types to choose from. ○ This is a variant of FileField , having the ability to validate if the uploaded file is an image. CharField: URLField ○ This is the most used field type. It can hold string data of length specified by max_lenth parameter. ○ A CharField having in-built validation for URL. CASCADE Relationship fields ▪ If the on_delete parameter is set to CASCADE , deleting the reference object will also delete the referred object. ○ There can be three types of relationships between database models: ▪ Suppose a vehicle belongs to a customer. When the Customer is deleted, all the vehicles that reference the ○ one-to-one customer will be automatically deleted. ○ one-to-many PROTECT ○ many-to-many ▪ The effect of the PROTECT option is the opposite of CASCADE. ○ The django.models module has the following fields for establishing relationships between models. ▪ It prevents the deletion of a referenced objectif it has an object referencing it in the database. ForeignKey ▪ Suppose a vehicle belongs to a customer. If a customer has vehicles, it cannot be deleted. ○ It is used to establisha one-to-many relationship between two models. It requires two positional arguments - the model ▪ It’s important to know that if you forcefully delete the customer, Django raises the ProtectedError. with which it is related, and the on_delete option to define the behavior of the delete operation. RESTRICT ○ Suppose you have a Customer and Vehicle model with a one-to-many relationship. A customer can have more than one vehicle. ▪ The difference between PROTECT and RESTRICT is that when you delete the referenced object, the on_delete class Customer(models.Model): option raises the RestrictedError. name = models.CharField(max_length=255) ▪ The deletion of the referenced object is allowed if it also references a different object that is being deleted in the same operation, but via a CASCADE relationship. class Vehicle(models.Model): name = models.CharField(max_length=255) MODELS customer = models.ForeignKey( Customer, ○ If you are building a dynamic application using a web framework, data storage, using a database is essential. on_delete=models.CASCADE, ○ Presentation layer is the layer that the user interacts with. related_name='Vehicle' Any data posted from the presentation layer needs to be persisted and also kept for retrieval for later use. ) ○ The on_delete option specifies the behavior in case the associated object in the primary model is deleted. The values are: ○ The solution is to use a model. The object equivalent of a database table used in Django and acts as a single definitive CASCADE: deletes the object containing the ForeignKey source of information about your data. PROTECT: Prevent deletion of the referenced object ○ A model is the single definitive source of information about your data. RESTRICT: Prevent deletion of the referenced object by raising RestrictedError It contains the essential fields and behaviors of the data you're storing. Generally, each model maps to a single ○ Now let’s expand upon these values in more detail: database table. ○ Each model is a Python class that subclasses django.db.models.model. Each attribute of the model represents class Principal(models.Model): a database field. CollegeID = models.OneToOneField( College, Model relationships on_delete=models.CASCADE ) Qualification = models.CharField(max_length=50) Types of Relationships ○ There are three types of relationships that exist: One-to-Many Relationship ○ One-to-One, ○ One-to-Many, and ○ In a One-to-Many relationship, one object of a model can be associated with one or more objects of another model. ○ Many-to-Many. ○ For example, a teacher is qualified to teach a subject, but there can be more than one teacher in a college who teaches the same subject. The subject model is as below: One-to-One relationship class Subject(models.Model): ○ If a primary key is in one model, and only one record exists in the other related model, the two models are said to have a Subjectcode = models.IntegerField(primary_key = True) one-to-one relationship. name = models.CharField(max_length=30) ○ Let's use an example of a college model and a principal model. A college can have only one principal or it can be similarly phrased as one person can be a principal of only one college. ○ The teacher model has its own primary key. It has a Foreignkey relating this model with the subject model. The college model can be described as follows: class Teacher(models.Model): class college(Model): TeacherID = models.ItegerField(primary_key=True) CollegeID = models.IntegerField(primary_key = True) subjectcode=models.ForeignKey( name = models.CharField(max_length=50) Subject, on_delete=models.CASCADE ○ In the principal model, you must provide the CollegeID field as the foreign key. ) The on_delete option specifies the behavior in case the associated object in the primary model is deleted. Qualification = models.CharField(max_length=50) The values are: email = models.EmailField(max_length=50) ○ CASCADE: deletes the object containing the ForeignKey ○ PROTECT: Prevent deletion of the referenced object. Many-to-Many Relationship ○ RESTRICT: Prevent deletion of the referenced object by raising RestrictedError ○ In a Many-to-Many relationship, multiple objects of one model can be associated with multiple objects of another model. ○ The principal model has the following field structure: ○ Let's redefine the relationship between the subject and teacher models in the above example. detects the changes, a script with its name and version number is created. ○ If more than one teacher can teach the same subject, a single teacher can teach more than one subject. ○ To implement the changes according to the migration script, you need to run the migrate command. ○ So, there is a Many-to-Many relationship between the two. Django implements this with a Many-to-Many Field type. sqlmigrate Command Let’s use it in the subject model. The teacher model is straightforward. Lastly, the sqlmigratecommand shows the SQL query or queries executed when a certain migration script is run. class Teacher(models.Model): python manage.py sqlmigrate myapp 0001_initial TeacherID = models.ItegerField(primary_key=True) Qualification = models.CharField(max_length=50) Adding a model object email = models.EmailField(max_length=50) ○ The Customer.objects gives the Manager of the model. It handles all the CRUD operations on the database table. For example, ○ The design of the Subject model class reflects the Many-to-Many relationship. an object can also be created with the create() method as follows: Cust1 = Customer.objects.create(name="Hameed") class Subject(models.Model): Subjectcode = models.IntegerField(primary_key = True) ○ The create() method actually performs the INSERT operation of SQL. name = models.CharField(max_length=30) credits = model.IntegerField() Fetch model objects teacher = model.ManyToManyField(Teacher) ○ A QuerySet represents a collection of objects from your database. It represents a SELECT query. How to use migrations To fetch all the objects, use the all() method of the Manager. ○ Django translates the models into respective database tables in the backend database with a mechanism known as migration. model.objects.all() ○ It also propagates any changes in the model structure such as adding, modifying or removing a field attribute of a model class to the mapped table. ○ The all() method returns a list of objects. You can iterate over it with the usual for loop or list comprehension technique. Django’s migration system has the following commands: >> lst=Customer.objects.all() ○ makemigrations ○ migrate >>> [c.name for c in lst] ○ Sqlmigrate ['Henry', 'Hameed'] ▪ Showmigrations ○ You can apply filters to the data fetched from the model. This is used to fetch objects satisfying the given criteria. ○ Django’s migration is a version control system. ○ In SQL terms, a QuerySet equates to a SELECT statement, it is like applying a WHERE clause. ○ Whenever you add a new model or effect changes in an existing model, you need to run the makemigrations command. model.objects.filter(criteria) ○ It creates a script for making changes in the mapped table. Every time you run the makemigrations command and Django ○ For example, use the following statement to retrieve all the customers with names starting with ' H'. mydata = Customer.objects.filter(name__startswith='H') Updating and removing a model object ○ To update an object, such as changing the Customer's name from Henry to Helen, assign a new value to the name attribute and save. >>> c=Customer.objects.get(name="Henry") >>> c.name="Helen" >>> c.save() ○ Similarly, the delete() method of the model manager physically removes the corresponding row in the model's mapped table. >>> c=Customer.objects.get(pk=4) >>> c.delete() (1, {'demoapp.Customer': 1}) ○ This way, you can perform the CRUD operations on a database table using the QuerySet API instead of executing raw SQL queries. Regular expressions ○ Regular expressions are RegEx, are a set of characters that specify a pattern and are used to search for or find patterns in a string. ○ They are a powerful tool that developers use to perform extraction and validation, advanced searching, group searches, and find and replace operations. ○ In django, developers use regular expressions to define, extract and validate dynamic URL paths before they are sent to the associated view function. Django Form Tuesday, June 13, 2023 7:27 AM Django framework includes a Form class, its attributes, and methods in the django.forms module. This class is used as a base for a user-defined form design. Generic Views from django import forms Thursday, June 29, 2023 7:28 PM class ApplicationForm(forms.Form): pass The attributes of the form are Field class objects. The forms module has a collection of Field types. These fields correspond to the HTML elements they eventually render on the user’s browser. For example, the forms.CharField is translated to HTML’s text input type. Sub-classing Generic Views Similarly, the ChoiceField is equivalent to SELECT in HTML. The Django form class representing the above Application form would be: from django import forms In this reading, you’ll learn about the class_based generic views. class ApplicationForm(forms.Form): name = forms.CharField(label='Name of Applicant', max_length=50) address = forms.CharField(label='Address', max_length=100) You can implement the view layer with function or class-based views in a Django application. posts = (('Manager', 'Manager'),('Cashier', 'Cashier'),('Operator', 'Operator')) You declare a class by extending the django.views.View class and define get() and post() methods inside field = forms.ChoiceField(choices=posts) By convention, the user-defined form classes are stored in a forms.py file in the app’s package folder. it to handle the HTTP requests. So, if you have a Django app called myapp , the above code is kept in myapp/forms.py. Django Form Fields Out of the many available form field types, some of the most frequently used are as follows: The URL pattern connects the path to the class with the as_view() method of the View class. A quick example of class view: CharField : Translates to input type=text HTML form element. If you want to accept a longer multiline text, set its widget property to forms.Textarea forms.CharField(label="Enter first name",max_length=50) from django.views import View IntegerField : Similar to a CharField but customized to accept only integer numbers. You can limit the value entered by setting min_value and max_value parameters. age = forms.IntegerField(min_value=20, max_value=60) class NewView(View): FloatField : A text input field that validates if the input is a valid float number. Its variant DecimalField accepts a float number of specified decimal places. price = forms.FloatField() def get(self, request): FileField : Presents an input type=file element on the HTML form. upload = forms.FileField(upload_to ='uploads/') # View logic will place here ImageField : Similar to FileField with added validation to check if the uploaded file is an image. The pillow library must be installed for this field type to be used. return HttpResponse('response') EmailField : A CharField that can validate if the text entered is a valid email ID. email = forms.EmailField(max_length = 254) ChoiceField : Emulates the HTML’s SELECT element. The URL pattern in urls.py is updated as below: Populates the drop-down list with a choice parameter whose value should be a sequence of two item tuples. gender = forms.CharField(max_length=1, choices=GENDER_CHOICES) The instance of the Form class translates to the HTML script of a form. from myapp.views import NewView When returned to the browser, the form is rendered. Let there be a following view in the app’s views.py file which renders the forms.html template and sends the ApplicationForm object as a context. urlpatterns = [ from.forms import ApplicationForm def index(request): path('about/', NewView.as_view()), form = ApplicationForm() return render(request, 'form.html', {'form': form}) ] Inside the template, the form can be rendered in different ways. Instead of a tabular presentation of the form elements you can use the following variations: Django provides class-based generic views to make the development process much easier and faster. In this reading, you’ll {{ form.as_table }} will render them as table cells wrapped in tags. The form is rendered as a table by default. {{ form.as_p }} will render them wrapped in tags. discover how the generic views are implemented. {{ form.as_ul }} will render them wrapped in tags. {{ form.as_div }} will render them wrapped in tags. Reading Form Contents The most frequently used generic views are: Note that the form’s action attribute is set to "/form" path. So, you’ll provide a form() view mapped to this URL. This function fetches the data submitted by the user. It may be used to add a new row in the database table, or for any other processing. TemplateView Inside the view, populate the form object with the POST data and check it is valid. CreateView The Form class provides is_valid() method. It runs validation on each field and returns True if all field validations are passed. ListView from.forms import ApplicationForm DetailView def index(request): UpdateView if request.method == 'POST': DeleteView form = ApplicationForm(request.POST) LoginView if form.is_valid(): # process the data name = form.cleaned_data['name'] add = form.cleaned_data['address'] post = form.cleaned_data['posts'] Advantage of function-based views return HttpResponse('Form successfully submitted') Once the Form instance is validated, you can now access the data in individual field via the cleaned_data attribute. It ensures that the field contains the output in consistent form. Simple to implement. In our example, the three values in the three input elements are parsed to Python variables like this: Easy to read. Explicit code flow. Straightforward usage of decorators. good for one-off or specialized functionality. Disadvantages of function-based views Hard to extend and reuse the code. Handling of HTTP methods via conditional branching. Advantages of Class-based views Code reusability. {% csrf_token %} DRY — Using CBVs help to reduce code duplication. Code can be extended to include more functionalities. class with different methods for each http request instead of conditional branching statements inside a single function-based view. {{ form.as_table }} Built-in generic class-based views. Disadvantages of Class-based views Harder to read. Implicit code flow. Use of view decorators require extra import or method override. The URL path is updated by mapping the "create/" path to the as_view() method of this class: from.views import EmployeeCreate GENERIC VIEWS urlpatterns = [... path('create/', EmployeeCreate.as_view(), name = 'EmployeeCreate') , Requirements of a generic view ] If the view needs a model to be processed, it should be set as the value of model property of the view. When the client visits this URL, they are presented with the form. The user fills and submits the employee details, which are saved in the Employee table. Each type of view looks for a template name with modelname suffixed by the type of generic view. For example, for a list view processing employee model, Django tries to find employee_list.html. ListView The generic view is mapped with the URL with as_view() method of the View class. Let's now build a subclass for each of the respective generic view classes to perform CRUD operations Django's django.views.generic.list module contains the definition of ListView class. on the Employee model: Write its sub-class to render the list of model objects. The EmployeeList class is similar to the CreateView sub-class except its base class. class Employee(models.Model): name = models.CharField(max_length=100) from django.views.generic.list import ListView email = models.EmailField() class EmployeeList(ListView): contact = models.CharField(max_length=15) model = Employee success_url = "/employees/success/" class Meta: db_table = "Employee" The template required for this view must be named employee_list.html. Django sends the model object in its context. Using the DTL loop syntax, you can display the list of employees: CreateView The CreateView class automates the creation of a new instance of the model. To provide a create view, use the {% for object in object_list %} sub-class of CreateView : Name: {{ object.name }} Email: {{ object.email }} from django.views.generic.edit import CreateView contact: {{ object.contact }} class EmployeeCreate(CreateView): model = Employee {% endfor %} fields = '__all__' success_url = "/employees/success/" If the user visits http://localhost:/8000/employees/list, the browser lists all the rows in the employee table. A model form based on the model structure is created by this view and passed to the employeeCreate.html template: DetailView The generic DetailView is found in the django.views.generic.detail module. Now, create its sub-class, EmployeeDetail (much the same way as EmployeeList ). class EmployeeDelete(DeleteView): Note that this view shows the details of an object whose primary key is passed as an argument in the URL. model = Employee So, add the following path in the app's URL pattern: success_url = "/employees/success/" You need to pass the primary key of the Employee model to this. So, the URL path is set as: path('show/', EmployeeDetail.as_view(), name = 'EmployeeDetail') path('', EmployeeDelete.as_view(), name = 'EmployeeDelete') Again, the View object fetches the model instance and passes it as a context to the employee_detail.html template, The employee_confirm_delete.html template asks for confirmation from the user before removing the model instance. which displays its attributes with template syntax as follows: Name : {{object.name}} {% csrf_token %} Email : {{ object.email }} Contact : {{ object.contact }} Are you sure you want to delete "{{ object }}"? Assuming the URL visited is /employees/1 , the Employee record with primary key=1 will be displayed. UpdateView This is another generic view, defined in django.views.generic.edit module. It renders a form in which the new values of the model attributes can be submitted. Set the fields attribute to '__all__' or to a list of updatable fields. from django.views.generic.edit import UpdateView class EmployeeUpdate(UpdateView): model = Employee fields = '__all__' success_url = "/employees/success/" Since this view is intended to update the data of a given model instance, its URL path must be configured accordingly: 1 path('update/', EmployeeUpdate.as_view(), name = 'EmployeeUpdate') The example URL that invokes this view is /employees/1. The UpdateView class renders the template with its name having update_form as suffix: {% csrf_token %} {{ form.as_table }} DeleteView Lastly, the generic view performs thedelete operation on a model's given instance. It is present when editing the sub-module of django.views.generic module: from django.views.generic.edit import DeleteView Admin Interface Thursday, June 29, 2023 7:28 PM For developers, building such an administrative site for each project can be tedious work. Django solves the problem by automatically creating a unified admin interface for site administrators to add, edit and delete content, such as users, permissions and database entries. This process is automated as the admin interface directly links to the models in the project once registered. The admin interface is usually a part of a large web application to help the administrator perform certain administrative tasks. The tasks such as creating and managing users, controlling access permission, and forming user groups. Django reads the models declared in the project and from the metadata of models declared in a project, it quickly builds an easy-to-use interface. One can add users through the interface, which is straightforward. It’s as easy as following the onscreen instructions. A user without permission to perform any task is virtually useless. In addition to the interface, another powerful feature of Django is that it provides a ready-to-use admin interface named Django admin. To create a user to access the admin interface for the first time run the command Different permissions can be granted to the user individually or by creating a group with a set of permissions. Users can be added to the group so that a set of users with common permissions is created. python3 manage.py createsuperuser. If a user’s is_staff property is set to True, it can log in to the admin interface. Managing users in Django Admin Django admin’s user management system is very efficient, yet it can be tricky. Unless you grant the permissions to the users very judiciously, the system might be put at considerable risk. Django’s authorization and authentication system are provided by django.contrib.admin app, which is installed by default. Even though Django’s admin site provides a very easy-to-use interface to add and modify users and groups, there are no It can be seen in the INSTALLED_APPS in the project’s settings.py file. real restrictions as the User admin. A super user has the privilege to add or modify users and groups. As you log in as a super user, the admin interface appears as below: For example, a user with a staff status can manage the other users. But they can also edit their own permissions, which is not warranted. A staff user can also allocate superuser rights. The out-of-box implementation of the admin site doesn’t prevent this. So, what do you do to resolve this? Let’s assume that the Django site has a superuser named Admin and a user named test123 with staff status enabled. To customize the User Admin, first, unregister the existing user profile and register a new one. from django.contrib, import admin # Register your models here. from django.contrib.auth.models, import User # Unregister the provided model admin: admin.site.unregister(User) To register our own admin, use @admin.register() decorator. Give the user a model as the argument. @admin.register(User) Decorate a sub-class of UserAdmin class. class NewAdmin(UserAdmin): def get_form(self, request, obj=None, **kwargs): from django.contrib.auth.admin import UserAdmin form = super().get_form(request, obj, **kwargs) @admin.register(User) is_superuser = request.user.is_superuser class NewAdmin(UserAdmin): if not is_superuser: pass form.base_fields['username'].disabled = True You can now add some customizations to how the User Admin functions. At this point, though, if you log in return form with the super user credentials, there’s no change in the interface. Next, you’ll explore how to prevent any admin user from changing the content of one or more fields of a model. The UserAdmin class has a property called readonly_fields. You can specify a list of fields that you want the user (or a super user) to be prevented from modifying. The user model has a field date_joined. Suppose you want that its value given at the time of creating a new user should never be changed. So, keep this field in the readonly_fields list. Modify the app’s admin.py by changing the NewAdmin class as follows. Include this at the end of admin.py. from django.contrib.auth.admin import UserAdmin @admin.register(User) class NewAdmin(UserAdmin): readonly_fields = [ 'date_joined', ] Django Admin’s change form will show date_joined field as disabled, thereby, it will not be editable. Instead of restricting all the staff users from changing the value of a certain field, it is possible to allow it for some users and prevent others. For example, the user model has a username field. If any user accidentally modifies the username field of the other user, it may create many problems. Like the other user may not be able to log in. The ideal solution for this situation is to rest this privilege only with the super user and nobody else. Now, explore how this is done: The UserAdmin class (the base class for NewAdmin class that you have registered in the admin site) has a method known as get_form(). You need to override it to disable the username field in it. from django.contrib.auth.admin import UserAdmin Use a command directly inside the Django shell. When prompted, a password is assigned to this super user, Permissions Thursday, June 29, 2023 7:28 PM followed by an authentication. Go to the admin interface and view the list of users. The new user appears in the list. As you create models in your Django application, Django automatically creates, add, change, and delete and view PERMISSIONS permissions. Permissions are named using the app action model pattern. App is the name of the Django app. Action is add, The Django framework has an in-built system for handling permissions. This authentication system has change, delete or view and model is the name of the model in lowercase. features for both authentication and authorization, coupled for ease of use. Example app: myapp, For a user to perform a certain action, they need to have the relevant permission granted to them. model: MyModel Before you explore permissions, it is important to note that a user in Django can be one of three classifications, ² The permissions on this model will be as follows. namely a superuser, a staff user, or a user. Much like other components of Django, users in Django are Python objects. ○ Myapp.add_my model, The specific type of user is characterized by special attributes that are set inside the user object. ○ myapp.change_mymodel, ² A super user is a top level user or administrator of the system. ○ myapp.delete_mymodel ○ This type of user possesses permission to add, change, or delete other users, as well as perform operations on ○ myapp.view_mymodel. all the data in the project. In Python code, it is possible to check if a user has a certain type or permission enabled on it. To do this, you can ² A staff type user is allowed to access Django admin interface. Use the has_perm function, which returns true or false. ○ However, a staff user doesn't automatically get the permission to create, read, update, and delete data in the Django admin, it must be given explicitly. GROUPS ○ Note that a super user is a staff user by default. Everyone else is irregular user by default, a user is not Assigning permissions to each user individually is a tedious task, especially if you have large numbers of users. authorized to use the admin site. Fortunately, Django has a solution. You can manage permissions to sets of users in Django groups. That proves ² Users are marked as active by default. A user may be marked as inactive if it's authentication fails or has been to be very useful. Now what is a group? In Django, a group is a list of permissions that can be assigned to one banned for some reason. While you can create the user through the admin interface, it can also be done or more users. through the Django shell. A user can belong to any number of groups. To go back to the restaurant example, you might have a group for kitchen The permission mechanism is handled by the django.contrib.auth app. You can use the create user function to staff and another group for waiters. When you create or modify a user, simply choose the desired group. create a new user object. Once the user is created, you can grant a certain status to a user to become a staff member. To grant the staff status, set the user is staff property to true. All the permissions listed in the group will be automatically assigned to the user. It is important to note that you can still manually add permissions to users, even if they belong to a group. How do you create a superuser? In this video, you learned about the user permissions and model permissions in Django. Database Options Web frameworks often need to generate dynamic content to render on web pages. And because Django is a web framework, Thursday, June 29, 2023 7:28 PM it provides a convenient way to generate HTML dynamically. Dynamic content is any data that changes according to context, user behavior, and preferences. DATABASE OPTIONS Developers can use dynamic content and rendering to produce static HTML code. The most common approach for developers is to use templates. When creating a Django project, the default configuration uses an SQLite database. It is automatically set inside the file, settings.py file. This means that you can directly start working with the Templates are text-based documents or Python strings marked up using the Django template language, or DTL for short. database immediately. Templates consist mainly of two types of content. SQLite is known as a user-friendly zero configuration database. And there are many advantages to using it. The first is static. You don't need to install anything to support the database as it doesn't run as a server process. This is the HTML that does not change on the web page. This means the database does not need to be started or stopped, or require additional configuration files. The second is template language. This is the syntax that allows you to insert dynamic data. As a result, this type of database is suitable for small projects or rapid prototyping. While you use template language to render dynamic content, the concept of a template is what makes up the Suppose you are developing projects that need a quick test environment. In that case, SQLite is a solid option presentation layer of the MVT architecture. This helps in the separation of logic because templates handle the user as it doesn't require running a separate server. There may be occasions when a more scalable robust database is needed. interface logic of a web page. For example, when moving from a development to a production environment. z It's important to know that the dynamic content inside the static HTML is written so Django can understand the syntax Django supports the use of many databases with minimal configuration. These include and formatting. Python is a dynamic object-oriented programming language, while HTML is a static markup language. PostgreSQL To bridge this gap, Django makes use of the MariaDB Django template engine. And the Django template language, or DTL, is the language used for adding dynamic content. MySQL DTL can contain embedded dynamic content, such as Python code and variables that the template engine processes. Oracle and SQLite. DTL consists of constructs such as variables, tags, filters, and comments. Each construct has a specific syntax that helps Django understand the code logic. Among these PostgreSQL and MySQL are most commonly used. Additionally, Django also provides an API for loading and rendering templates. You define the configuration settings for Django has features to support each database that make it easy to connect and work with. It provides a generic way the template engine inside settings.pi under the project directory. It's important to note that the app directory to access the different types of databases and a connection to a database is established by knowing the type of database. setting must be set to true. You can also add specific locations inside the directory setting for Django to search Connecting to MySQL database for directories inside the DIRS option. In addition to the Django template engine provided by Django, you can also extend the functionalityby using one or more template engines. For example, Jinja2 is a popular template engine To connect to a MySQL database, you need to provide the address where the database is running, the port number and used in Python and you can configure the settings for adding these extensions inside the settings.pi file. the database name you wish to connect to. Django helps in code reuse by using templates with the help of something called template inheritance. You also need a database driver which is responsible for mapping all the models and translating Python queries into Template inheritance allows developers to build a base template containing the expected HTML elements of your site SQL instructions via the model. To use MySQL, the driver or connector, MySQL client needs to be installed. and defines blocks that child templates can override. Once defined, all pages of the website can inherit the base template. When you connect to a database, the connection opens on each request and is kept open for a specific time. This code reusability helps in saving developers time and effort and follows the principle of dry. The connection is controlled by the CONN_MAX_AGE parameter and represents a certain time before the connection is automatically closed. To establish a connection, you must configure parameters under the databases option of the Configuring MySQL Connection settings.py file. By default, Django uses the SQLite database for storage and retrieval of the app data, as Python has built-in support for it. #Settings.py However, you can use any of the following databases supported by Django: DATABASES = { PostgreSQL 'default': { MariaDB 'ENGINE': 'django.db.backends.mysql', MySQL 'NAME': 'mydatabase', Oracle 'USER': 'root', SQLite 'PASSWORD': '', In this Reading, you’ll learn the steps to enable a MySQL connection with a Django application. 'HOST': '127.0.0.1', 'PORT': '3306', Advantage of MySQL 'OPTIONS': { 'init_command': "SET sql_mode='STRICT_TRANS_TABLES'" The SQLite database has a lot of limitations. It is serverless and doesn't have a user management system. } It is useful for smaller applications and for the development of a prototype to be upgraded eventually for databases } that are scalable and support client-server architecture. } MySQL is an open-source database and has a lot of advantages over SQLite, such as scalability and authentication. The other optional parameters include: Install MySQL sql_mode : The session SQL mode will be set to the given string. It defaults to 'STATIC_TRANS_TABLES' to prevent invalid To install the MySQL server, download the installer appropriate for your operating system from or missing values from being stored in the database. https://www.mysql.com/downloads/. For Windows, use the mysql-installer-web-community-8.0.30.0.msi and follow default-character-set : The character set to be used. Default is utf8. the wizard-based installation steps. read_default_file : MySQL configuration file to read. init_command : Initial command to issue to the server upon connection. Start the MySQL command line client with the following command: 1 mysql -u root -p You will be prompted to enter the password set at the time of installation. In the command terminal, you will get the MySQL prompt. You can now enter any SQL statement in it. Install MySQL DB API Driver To interface a Python program with MySQL, ensure you have a DB API-compliant driver. There are a number of Python drivers for MySQL available. Django recommends mysqlclient to be used. Install it with pip installer. 1 Pip3 install mysqlclient Enable MySQL To be able to use MySQL, the DATABASES variable in the Django project’s settings file must be properly configured. By default, it is set to the connection parameters for SQLite. Remove those statements. You have to add MySQL-specific settings in their place. You must configure at least one database in the DATABASES variable. For the configuration of the first database, its name should be ‘default’. The settings include the database engine , name of the database, username, and password, along with the host IP address. This defaults to the localhost 127.0.0.10 and the port defaults to 3306. Templates Thursday, June 29, 2023 7:28 PM TEMPLATES Web frameworks often need to generate dynamic content to render on web pages. And because Django is a web framework, it provides a convenient way to generate HTML dynamically. Dynamic content is any data that changes according to context, user behavior, and preferences. Developers can use dynamic content and rendering to produce static HTML code. The most common approach for developers is to use templates. Templates are text-based documents or Python strings marked up using the Django template language, or DTL for short. Templates consist mainly of two types of content. The first is static. - This is the HTML that does not change on the web page. The second is template language. - This is the syntax that allows you to insert dynamic data. While you use template language to render dynamic content, the concept of a template is what makes up the presentation layer of the MVT architecture. This helps in the separation of logic because templates handle the user interface logic of a web page. It's important to know that the dynamic content inside the static HTML is written so Django can understand the syntax and formatting. Python is a dynamic object-oriented programming language, while HTML is a static markup language. To bridge this gap, Django makes use of the Django template engine. And the Django template language, or DTL, is the language used for adding dynamic content. DTL can contain embedded dynamic content, such as Python code and variables that the template engine processes. DTL consists of constructs such as variables, tags, filters, and comments. Each construct has a specific syntax that helps Django understand the code logic. Additionally, Django also provides an API for loading and rendering templates. You define the configuration settings for the template engine inside settings.pi under the project directory. It's important to note that the app directory setting must be set to true. You can also add specific locations inside the directory setting for Django to search for directories inside the DIRS option. In addition to the Django template engine provided by Django, you can also extend the functionality by using one or more template engines. For example, Jinja2 is a popular template engine used in Python and you can configure the settings for adding these extensions inside the settings.pi file. Django helps in code reuse by using templates with the help of something called template inheritance. Template inheritance allows developers to build a base template containing the expected HTML elements of your site and defines blocks that child templates can override. Once defined, all pages of the website can inherit the base template. This code reusability helps in saving developers time and effort and follows the principle of dry. Filters Another important part of Django Template Language is the filters. While tags may be considered similar to keywords in a programming language, the filters merely represent the temporarily modified value of a template variable. The filter is applied to a variable by the|(known as Pipe) symbol, such as: {{ variable_name | filter_name }} Here are some filters in action. The index() view in the above examples receives a name parameter, and it is rendered in the template with the {{ name }} expression tag. If you apply the upper filter to it, the name will be rendered in uppercase. {{ name | upper }} Likewise, the lower filter converts the string to its lowercase, the title filter renders a string so that the first letter of each word in a multi-word string appears in uppercase. Therefore, the string “simple is better than complex” becomes “Simple Is Better Than Complex”. The length filter works with a list and returns the number of items in it. The view passes a list as a context to the template: nums=[1,2,3,4] The template filter {{ nums | length }} outputs 4 The wordcount filter is similar. It tells you how many words are present in the template variable that has to be a string. For example: String = 'Simple is better than complex' is passed a context, {{ string | wordcount }} returns 4. The slice filter resembles Python’s slice operator, which separates a part of the given list object. So, if: nums = [1,2,3,4,5,6,7,8] Is passed in the context, {{ nums | slice[1:2] }} It returns [2,3] and then you can iterate over it. The first and last filters return the first and last item in the list. Enforcing Permissions The Django Admin interface makes it possible to grant and enforce permissions to access the model data. By default, all users get the Add, Change, View and Delete permissions on all models. If a model requires a user to gain access through special permissions, this can be granted through Django Admin. Model Permissions in Admin Interface Let’s assume that there is a Product model in a Django app named myapp. Here, Template inheritance a custom permission called change_category has been defined. Inheritance in Django Template Language class Product(models.Model): ProductID: models.IntegerField() The term inheritance is associated with the principle of object-oriented programming. It refers to name : models.TextField() the mechanism of a child class inheriting the properties of its parent class, and if required, category : models.TextField extending or overriding them. class Meta: The question is how is the term inheritance used in relation to the template language? permissions = [('can_change_category', 'Can change category')] There are many view functions defined in a Django application. Each view renders a different template (or the same with a different context). Ideally, you want all the web pages to look This name of permission will be visible in the list of available user permissions consistent. For example, elements such as the header, footer, and the navigation bar, must when a new user is added or an existing group is edited. appear similar across all page However, outside of the admin environment, the Django models by themselves don't have a mechanism to enforce permissions because it is {% block %} tag Template inheritance helps to implement this structure and it’s similar to the one in object- unaware of the user identity that is performing the action. oriented programming. It is a very powerful, yet equally complex feature of Django Template The Django app receives user information through the request context. Language. Template inheritance is implemented with the {% block %} and {% endblock %} tags. Often, permissions are enforced at the view layer. However, you can do so from inside templates , URLs and function-based and class-based views. {% block name %}... Enforcing permissions at the view level {% endblock %} The block is identified by the given name to be overridden in the child template. If a user has logged in and has been authenticated, its details are available First, identify the components that are required because these will be used across all the web to the view function in the form of request.user object. If not, the value of pages. Include those that show variable content on each page. Use the block tags to mark the request.user is an instance of AnonymousUser. In that case, the permission code blocks with variable content as a dummy block or with no contents. to call a view can be denied as follows: from django.core.exceptions import PermissionDenied def myview(request): Child templates if request.user.is_anonymous(): raise PermissionDenied() Writing the templates for the views is straightforward because the structure is already defined in the base.html. The {% extends %} tag imports the base template components in the child Alternatively, you can decorate the view with a login_required decorator. It template. Create a new file named home.html in the templates folder and add the following line. only allows access for logged users. {% extends "base.html" %} from django.http import HttpResponse from django.contrib.auth.decorators import login_required We intend to keep the same header, the sidebar, and the footer defined in the base template @login_required and put the relevant code inside the contents block. Now, add the following lines in home.html def myview(request): return HttpResponse("Hello World") and save it. {% block contents %} Another way of restricting access to a view is by using the This is Home page @user_passes_test() decorator. It takes one mandatory argument, which is {% endblock %} a function returning True or False. If True is returned, the decorated view function defined below it is invoked. Let’s define a function testpermission(). It returns True if the user is authenticated and has a change_category permission. Static files def testpermission(user): if user.is_authenticated() and In addition to the dynamic content, a web application needs to serve certain static content to the user.has_perm("myapp.change_category"): client. It may be in the form of images, JavaScript code, or style sheets. Django’s default project return True template includes django.contrib.staticfiles in INSTALLED_APPS. else: The project’s settings file (settings.py ) has a static_url property set to 'static/'. All the static assets return False must be placed in the myapp/static/myapp folder as the static_url refers to it. While rendering an image from this static folder, load it with the {% static %} tag. HTML provides This function is then used as an argument to the @user_passes_test() the tag. Instead of giving the physical URL of the image to be rendered, use the path decorator. The view function defined below it will be invoked if the that is relative to the defined static_URL. testpermission() function returns True. {% load static %} from django.contrib.auth.decorators import user_passes_test @user_passes_test(testpermission) def change_ctg(request): # Logic for making change to category of product instance The user_passes_test() can be given an additional argument – login_url. Template tags The user will be redirected to this URL if the testpermission() function returns False. Typically, it is mapped to a view that renders a login page. Another method to enforce permission at the view level is with the @permission_required() decorator. Unless the user possesses the permission mentioned as an argument, the view function won’t be called. from django.contrib.auth.decorators import permission_required @permission_required("myapp.change_category") def store_creator(request): Thursday, June