,"\"G\", \"H\", \"I\", \"J\"}, autopct ='% 1.1f %%', shadow = True) plt.show() plt.pie(df['Sales'], labels = {\"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\", \"J\"}, autopct ='% 1.1f %%', shadow = True) plt.show() Output : 5. Scatter plot : A scatter chart shows the relationship between two different variables and it can reveal the distribution trends. It should be used when there are many different data points, and you want to highlight similarities in the data set. This is useful when looking for outliers and for understanding the distribution of your data.
# scatter plot between income and age plt.scatter(df['income'], df['age']) plt.show() # scatter plot between income and sales plt.scatter(df['income'], df['sales']) plt.show() # scatter plot between sales and age plt.scatter(df['sales'], df['age']) plt.show() Output :
PRACTICAL 15: IMPLEMENT DJANGO ON PYTHON IN FOLLOWING MODULES: a. Django Forms b. Bootstraps c. URL Pattern & Views d. User Model e. Send Mail f. Templates g. Tests h. Rest API Solution: 1. Django Forms When one creates a Form class, the most important part is defining the fields of the form. Each field has custom validation logic, along with a few other hooks. This article revolves around various fields one can use in a form along with various features and techniques concerned with Django Forms. Forms are basically used for taking input from the user in some manner and using that information for logical operations on databases. For example, Registering a user by taking input as his name, email, password, etc. Django maps the fields defined in Django forms into HTML input fields. Django handles three distinct parts of the work involved in forms: preparing and restructuring data to make it ready for rendering creating HTML forms for the data receiving and processing submitted forms and data from the client
flowChart-1 Syntax : Django Fields work like Django Model Fields and have the syntax :- field_name = forms.FieldType(**options) Example – from django import forms # creating a form class GeeksForm(forms.Form): title = forms.CharField() description = forms.CharField() Using Django Forms To use Django Forms, one needs to have a project and an app working in it. After you start an app you can create form in app/forms.py. Before starting to use a form let’s check how to start a project and implement Django Forms. Creating a Django Form Creating a form in Django is completely similar to creating a model, one needs to specify what fields would exist in the form and of what type. For example, to input, a registration form one might need First Name (CharField), Roll Number (IntegerField) and so on. Syntax from django import forms
class FormName(models.Model): # each field would be mapped as an input field in HTML field_name = models.Field(**options) To create a form, in geeks/forms.py Enter the code, # import the standard Django Forms # from built-in library from django import forms # creating a form class InputForm(forms.Form): first_name = forms.CharField(max_length = 200) last_name = forms.CharField(max_length = 200) roll_number = forms.IntegerField( help_text = \"Enter 6 digit roll number\" ) password = forms.CharField(widget = forms.PasswordInput()) To know more about how to create a Form using Django forms, visit How to create a form using Django Forms? Render Django Forms Django form fields have several built-in methods to ease the work of the developer but
sometimes one needs to implement things manually for customizing User Interface (UI). A form comes with 3 in-built methods that can be used to render Django form fields. {{ form.as_table }} will render them as table cells wrapped in <tr> tags {{ form.as_p }} will render them wrapped in <p> tags {{ form.as_ul }} will render them wrapped in <li> tags To render this form into a view, move to views.py and create a home_view as below. from django.shortcuts import render from .forms import InputForm # Create your views here. def home_view(request): context ={} context['form']= InputForm() return render(request, \"home.html\", context) In view one needs to just create an instance of the form class created above in forms.py. Now let’s edit templates > home.html <form action = \"\" method = \"post\"> {% csrf_token %} {{form }} <input type=\"submit\" value=Submit\"> </form>
Now, visit http://localhost:8000/ Create-django-form. To check how to use the data rendered by Django Forms visit Render Django Form Fields Create Django Form from Models Django ModelForm is a class that is used to directly convert a model into a Django form. If you’re building a database-driven app, chances are you’ll have forms that map closely to Django models. Now when we have our project ready, create a model in geeks/models.py, # import the standard Django Model # from built-in library from django.db import models # declare a new model with a name \"GeeksModel\" class GeeksModel(models.Model): # fields of the model title = models.CharField(max_length = 200) description = models.TextField() last_modified = models.DateTimeField(auto_now_add = True) img = models.ImageField(upload_to = \"images/\") # renames the instances of the model # with their title name def __str__(self):
return self.title To create a form directly for this model, dive into geeks/forms.py and Enter following code, # import form class from django from django import forms # import GeeksModel from models.py from .models import GeeksModel # create a ModelForm class GeeksForm(forms.ModelForm): # specify the name of model to use class Meta: model = GeeksModel fields = \"__all__\" 2. BOOTSTRAP Bootstrap is a CSS framework that makes it easier to create website and web application user interfaces. Bootstrap is especially useful as a base layer of CSS to build sites with responsive web design. Creating a Virtual Environment & Installing Django First, begin by creating a virtual environment for your project using the venv module:
$ python -m venv env Next, activate your environment using source: $ source env/bin/activate Next, install django in your virtual environment using pip: $ python -m pip install django Creating a Django Project & Application After installing Django, you need to create a project using django-admin.py; $ django-admin.py startproject demoproject Next, create an application using manage.py, you can name it accounts: $ cd demoproject $ python manage.py startapp accounts Next, you need to add accounts in the INSTALLED_APPS array inside the settings.py file of your project. Installing & Setting up django-crispy-forms Before adding anything else, let's install the django-crispy-forms application in your virtual environment using pip: $ pip install django-crispy-forms Next, as always, you need to add django-crispy-forms into the INSTALLED_APPS array in
the setting.py file: INSTALLED_APPS = [ # [...] 'crispy_forms' ] Since django-crispy-forms supports multiple styles, you also need to specify the CSS framework you want to use in your forms. You can do that by using the CRISPY_TEMPLATE_PACK setting in the settings.py file: CRISPY_TEMPLATE_PACK = 'bootstrap4' That's all what you need for installing and setting up django-crispy-forms. Adding Bootstrap 4 to your Project Installing the django-crispy-forms application, doesn't add Bootstrap 4 to your Django project. Adding Bootstrap 4 is quite easy, you can either head over to its official website at getbootstrap.com and download the files in your project's folder or you can also use Bootstrap 4 from a CDN. See the docs for more information. Create a templates/accounts/base.html template inside the accounts application and add the following code: <!doctype html> <html lang=\"en\"> <head> <link rel=\"stylesheet\"
href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css\" integrity=\"sha384- Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm\" crossorigin=\"anonymous\"> <title>Django Form Example with Bootstrap 4</title> </head> <body> <div class=\"container d-flex h-100\"> <div class=\"row justify-content-center\"> <div class=\"col-10\"> <h1> Django Form Example with Bootstrap 4 </h1> {% block main %} {% endblock %} </div> </div> </div> </body> </html> You can also add the JavaScript file for Bootstrap 4 if you intend to use the features that require JavaScript. We use the container, row, col-x and justify-content-center classes to create a simple layout with a one row and one column.
Creating the User Model(s) Let's now create a User model. Open the accounts/models.py file and add the following code: from django.db import models class User(models.Model): name = models.CharField(max_length=100) email = models.EmailField(blank=True) password = models.CharField(max_length=50) Next, open the accounts/views.py file and add a view to display the form. We'll be using the CreateView class-based view to quickly create a view that displays and processes a form: from django.views.generic import CreateView from .models import Person class UserCreateView(CreateView): model = User template_name = 'accounts/login.html' fields = ('name', 'email', 'password') If you don't specify the template name, Django will assume you are using a accounts/user_form.html template. Next, create an templates/accounts/login.html template inside the accounts application that extends the base.html template and add the following code:
{% extends 'accounts/base.html' %} {% block main %} <form method=\"post\"> {% csrf_token %} {{ form }} <button type=\"submit\" class=\"btn btn-success\">Login</button> </form> {% endblock %} To be able to see our login page, we need to add a login URL. Open the urls.py file and add: from django.contrib import admin from django.urls import path from accounts.views import UserCreateView urlpatterns = [ path('admin/', admin.site.urls), path('login', UserCreateView.as_view()) ] At this point, this is how our login page looks like: Django Example Form
In order to apply Bootstrap 4 to your form, you simply need to add the following code: {% extends 'accounts/base.html' %} {% load crispy_forms_tags %} {% block main %} <form method=\"post\"> {% csrf_token %} {{ form|crispy }} <button type=\"submit\" class=\"btn btn-success\">Login</button> </form> {% endblock %} Output: 3. URL Pattern & Views using Django In Django, views are Python functions which take a URL request as parameter and return an HTTP response or throw an exception like 404. Each view needs to be mapped to a corresponding URL pattern. This is done via a Python module called URLConf(URL
configuration) Let the project name be myProject. The Python module to be used as URLConf is the value of ROOT_URLCONF in myProject/settings.py. By default this is set to 'myProject.urls'. Every URLConf module must contain a variable urlpatterns which is a set of URL patterns to be matched against the requested URL. These patterns will be checked in sequence, until the first match is found. Then the view corresponding to the first match is invoked. If no URL pattern matches, Django invokes an appropriate error handling view. Including other URLConf modules It is a good practice to have a URLConf module for every app in Django. This module needs to be included in the root URLConf module as follows: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('books.urls')), ] This tells Django to search for URL patterns in the file books/urls.py. URL patterns Here’s a sample code for books/urls.py: from django.urls import path
from. import views urlpatterns = [ path('books/<int:pk>/', views.book_detail), path('books/<str:genre>/', views.books_by_genre), path('books/', views.book_index), ] For example, A URL request to /books/crime/ will match with the second URL pattern. As a result, Django will call the function views.books_by_genre(request, genre = \"crime\"). Similarly, a URL request /books/25/ will match the first URL pattern and Django will call the function views. book_detail (request, pk =25). Here, int and str are path convertors and capture an integer and string value respectively. Path convertors: The following path convertor types are available in Django int – Matches zero or any positive integer. str – Matches any non-empty string, excluding the path separator (‘/’). slug – Matches any slug string, i.e., a string consisting of alphabets, digits, hyphen and under score. path – Matches any non-empty string including the path separator(‘/’) uuid – Matches a UUID(universal unique identifier).
4. USERMODEL The Django’s built-in authentication system is great. For the most part we can use it out-of- the-box, saving a lot of development and testing effort. It fits most of the use cases and is very safe. But sometimes we need to do some fine adjustment so to fit our Web application. Commonly we want to store a few more data related to our User but the next question might be that how should a Django developer reference a User? The official Django docs list three separate ways: User AUTH_USER_MODEL get_user_model() Explanation: Illustration of how to reference user model by an example. Consider a project named mysite having an app name blog. Method 1 – User model Directly : Inside the models.py add the following code: from django.db import models from django.contrib.auth.models import User # Create your models here. class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=50) content= models.TextField()
def __str__(self): return self.title Register this model by adding the following code inside the admin.py. from django.contrib import admin from .models import Post # Register your models here. admin.site.register(Post) Some kinds of projects may have authentication requirements for which Django’s built-in User model is not always appropriate. For instance, on some sites it makes more sense to use an email address as your identification token instead of a username. Django allows you to override the default user model by providing a value for the AUTH_USER_MODEL setting that references a custom model. Method 2 – AUTH_USER_MODEL : AUTH_USER_MODEL is the recommended approach when referring to a user model in a models.py file. For this you need to create custom User Model by either subclassing AbstractUser or AbstractBaseUser. AbstractUser: Use this option if you are happy with the existing fields on the User model and just want to remove the username field. AbstractBaseUser: Use this option if you want to start from scratch by creating your own, completely new User model. Refer Below Article for Creating Custom User model:
Creating Custom User Model If you’ve already created a custom user model say CustomUser in an app called users , you’d reference it in your settings.py file as follows: #settings.py AUTH_USER_MODEL = 'users.CustomUser' Then in blog models.py add the following code: # blog/models.py from django.conf import settings from django.db import models class Post(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) title = models.CharField(max_length=50) content = models.TextField() Register this model by adding the following code inside the admin.py. from django.contrib import admin from .models import Post
# Register your models here. admin.site.register(Post) Method 3 – get_user_model() : If you reference User directly (for example, by referring to it in a foreign key), your code will not work in projects where the AUTH_USER_MODEL setting has been changed to a different user model. The other way to reference the user model is via get_user_model which returns the currently active user model: either a custom user model specificed in AUTH_USER_MODEL or else the default built-in User. Inside the models.py add the following code: from django.db import models from django.contrib.auth import get_user_model User=get_user_model() # Create your models here. class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=50) content= models.TextField() def __str__(self): return self.title Register this model by adding the following code inside the admin.py.
from django.contrib import admin from .models import Post # Register your models here. admin.site.register(Post) Output : 5. Send Mail The email would be, verification email or welcome email, account creation successful email or thanks-regard email, etc. For example, when you create a Google account, the first mail you get would be something like, “Hi Xyz, Welcome to Google. Your new account comes with access to Google products, apps, and services…..” Sending these types of emails from your Django application is quite easy. Although you can refer to the documentation for knowing more about sending emails in Django, but this is remarkably condensed and made easier. How to send simple emails to the registered users of your Django application Illustration of Django emails using an example. Consider a project named geeksforgeeks having an app named geeks. Refer this to create Django project and apps. Now let’s demonstrate this in geeksforgeeks project. In your “geeks” app’s settings.py file, enter the
following, EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST_USER = #sender's email-id EMAIL_HOST_PASSWORD = #password associated with above email-id In the above code, EMAIL_HOST_USER = ‘[email protected]’ and EMAIL_HOST_PASSWORD = ‘xyz123abc@’ are the lines where you need to add the sender’s mail id and password. [email protected] and xyz123abc@ are just examples. Now to use this in our application, move to views.py and add these lines at the top section as below. from django.conf import settings from django.core.mail import send_mail Generally, emails are sent to the users who sign up right? So, in the signup view function, add these lines. subject = 'welcome to GFG world' message = f'Hi {user.username}, thank you for registering in geeksforgeeks.' email_from = settings.EMAIL_HOST_USER recipient_list = [user.email, ]
send_mail( subject, message, email_from, recipient_list ) Now we will understand what exactly is happening. Here, subject refers to the email subject. message refers to the email message, the body of the email. email_from refers to the sender’s details. This takes the EMAIL_HOST_USER from settings.py file, where you added those lines of code earlier. recipient_list is the list of recipients to whom the mail has to be sent that is, whoever registers to your application they receive the email. send_mail is an inbuilt Django function that takes subject, message, email_from, and recipient’s list as arguments, this is responsible to send emails. After these extra lines of code has been added to your project, you can send emails now. But if you are using Gmail, then the first time you make these changes in your project and run, you might get SMTP error. To correct that- 1-Go to the Google account registered with the sender’s mail address and select Manage your account 2-Go to security section at the left nav and scroll down. In Less secure app access, turn on the access. By default, it would be turned off.
Finally run the application. Now, register any user to your application, and they will receive mail from the email account you had mentioned. 6. TEMPLATES Templates are the third and most important part of Django’s MVT Structure. A template in Django is basically written in HTML, CSS and JavaScript in an .html file. Django framework efficiently handles and generates dynamically HTML web pages that are visible to end-user. Django mainly functions with a backend so, in order to provide frontend and provide a layout to our website, we use templates. There are two methods of adding the template to our website depending on our needs. We can use a single template directory which will be spread over the entire project. For each app of our project, we can create a different template directory. For our current project, we will create a single template directory which will be spread over the entire project for simplicity. App-level templates are generally used in big projects or in case we want to provide a different layout to each component of our webpage. Configuration Django Templates can be configured in app_name/settings.py,
TEMPLATES = [ { # Template backend to be used, For example Jinja 'BACKEND': 'django.template.backends.django.DjangoTemplates', # Directories for templates 'DIRS': [], 'APP_DIRS': True, # options to configure 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] Using Django Templates Illustration of How to use templates in Django using an Example Project. Templates not only show static data but also the data form different databases connected to the application through
a context dictionary. Consider a project named geeksforgeeks having an app named geeks. To render a template one needs a view and a url mapped to that view. Let’s begin by creating a view in geeks/views.py, # import Http Response from django from django.shortcuts import render # create a function def geeks_view(request): # create a dictionary to pass # data to the template context ={ \"data\":\"Gfg is the best\", \"list\":[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] } # return response with template and context return render(request, \"geeks.html\", context) Now we need to map a URL to render this view, from django.urls import path # importing views from views.py from .views import geeks_view
urlpatterns = [ path('', geeks_view), ] Finally create a template in templates/geeks.html, <!DOCTYPE html> <html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <meta http-equiv=\"X-UA-Compatible\" content=\"ie=edge\"> <title>Homepage</title> </head> <body> <h1>Welcome to Geeksforgeeks.</h1> <p> Data is {{ data }}</p> <h4>List is </h4> <ul> {% for i in list %} <li>{{ i }}</li> {% endfor %}
</body> </html> Let’s check if it is working, The Django template language This is one of most important facilities provided by Django Templates. A Django template is a text document or a Python string marked-up using the Django template language. Some constructs are recognized and interpreted by the template engine. The main ones are variables and tags. As we used for loop in above example, we used it as a tag. similarly, we can used various other conditions such as if, else, if-else, empty, etc. Main characterisitcs of django Template language are Variables, Tags, Filters and Comments. Variables Variables outputs a value from the context, which is a dict-like object mapping keys to values. The context object we sent from the view can be accesses in template using variables of Django Template. Syntax {{ variable_name }} Example Variables are surrounded by {{ and }} like this:
My first name is {{first_name}}. My last name is {{last_name}}. With a context of {'first_name': 'Naveen', 'last_name': 'Arora'}, this template renders to: My first name is Naveen. My last name is Arora. To know more about Django Template Variables visit – variables – Django Templates Tags Tags provide arbitrary logic in the rendering process. For example, a tag can output content, serve as a control structure e.g. an “if” statement or a “for” loop, grab content from a database, or even enable access to other template tags. Syntax {% tag_name %} Example Tags are surrounded by {% and %} like this: {% csrf_token %} Most tags accept arguments, for example : {% cycle 'odd' 'even' %} Filters Django Template Engine provides filters are used to transform the values of variables and tag arguments. We have already discussed major Django Template Tags. Tags can’t modify value of a variable whereas filters can be used for incrementing value of a variable or modifying it to
one’s own need. Syntax {{ variable_name | filter_name }} Filters can be “chained.” The output of one filter is applied to the next. {{text|escape|linebreaks}} is a common idiom for escaping text contents, then converting line breaks to <p> tags. Example {{ value | length }} If value is [‘a’, ‘b’, ‘c’, ‘d’], the output will be 4. 7. Tests Writing tests¶ Django’s unit tests use a Python standard library module: unittest. This module defines tests using a class-based approach. Here is an example which subclasses from django.test.TestCase, which is a subclass of unittest.TestCase that runs each test inside a transaction to provide isolation: from django.test import TestCase from myapp.models import Animal class AnimalTestCase(TestCase): def setUp(self):
Animal.objects.create(name=\"lion\", sound=\"roar\") Animal.objects.create(name=\"cat\", sound=\"meow\") def test_animals_can_speak(self): \"\"\"Animals that can speak are correctly identified\"\"\" lion = Animal.objects.get(name=\"lion\") cat = Animal.objects.get(name=\"cat\") self.assertEqual(lion.speak(), 'The lion says \"roar\"') self.assertEqual(cat.speak(), 'The cat says \"meow\"') When you run your tests, the default behavior of the test utility is to find all the test cases (that is, subclasses of unittest. TestCase) in any file whose name begins with test, automatically build a test suite out of those test cases, and run that suite. For more details about unittest, see the Python documentation. Where should the tests live? The default startapp template creates a tests.py file in the new application. This might be fine if you only have a few tests, but as your test suite grows you’ll likely want to restructure it into a tests package so you can split your tests into different submodules such as test_models.py, test_views.py, test_forms.py, etc. Feel free to pick whatever organizational scheme you like. See also Using the Django test runner to test reusable applications. Running tests¶ Once you’ve written tests, run them using the test command of your project’s manage.py utility: $ ./manage.py test Test discovery is based on the unittest module’s built-in test discovery. By default, this will
discover tests in any file named “test*.py” under the current working directory. You can specify particular tests to run by supplying any number of “test labels” to ./manage.py test. Each test label can be a full Python dotted path to a package, module, TestCase subclass, or test method. For instance: # Run all the tests in the animals.tests module $ ./manage.py test animals.tests # Run all the tests found within the 'animals' package $ ./manage.py test animals # Run just one test case $ ./manage.py test animals.tests.AnimalTestCase # Run just one test method $ ./manage.py test animals.tests.AnimalTestCase.test_animals_can_speak You can also provide a path to a directory to discover tests below that directory: $ ./manage.py test animals/ You can specify a custom filename pattern match using the -p (or --pattern) option, if your test files are named differently from the test*.py pattern:
$ ./manage.py test --pattern=\"tests_*.py\" he test database¶ Tests that require a database (namely, model tests) will not use your “real” (production) database. Separate, blank databases are created for the tests. Regardless of whether the tests pass or fail, the test databases are destroyed when all the tests have been executed. You can prevent the test databases from being destroyed by using the test --keepdb option. This will preserve the test database between runs. If the database does not exist, it will first be created. Any migrations will also be applied in order to keep it up to date. As described in the previous section, if a test run is forcefully interrupted, the test database may not be destroyed. On the next run, you’ll be asked whether you want to reuse or destroy the database. Use the test --noinput option to suppress that prompt and automatically destroy the database. This can be useful when running tests on a continuous integration server where tests may be interrupted by a timeout, for example. The default test database names are created by prepending test_ to the value of each NAME in DATABASES. When using SQLite, the tests will use an in-memory database by default (i.e., the database will be created in memory, bypassing the filesystem entirely!). The TEST dictionary in DATABASES offers a number of settings to configure your test database. For example, if you want to use a different database name, specify NAME in the TEST dictionary for any given database in DATABASES. On PostgreSQL, USER will also need read access to the built-in postgres database. Aside from using a separate database, the test runner will otherwise use all of the same database settings you have in your settings file: ENGINE, USER, HOST, etc. The test database is created by the user specified by USER, so you’ll need to make sure that the given user account has sufficient privileges to create a new database on the system. For fine-grained control over the character encoding of your test database, use the CHARSET TEST option. If you’re using MySQL, you can also use the COLLATION option to control the particular collation used by the test database. See the settings documentation for details of these and other advanced settings. If using an SQLite in-memory database with SQLite, shared cache is enabled, so you can write
tests with ability to share the database between threads. 8. Rest API RESTful Structure In a RESTful API, endpoints (URLs) define the structure of the API and how end users access data from our application using the HTTP methods: GET, POST, PUT, DELETE. Endpoints should be logically organized around collections and elements, both of which are resources. In our case, we have one single resource, posts, so we will use the following URLS - /posts/ and /posts/<id> for collections and elements, respectively. GET POST PUT DELETE /posts/ Show all posts Add new post Update all posts Delete all posts /posts/<id> Show <id> N/A Update <id> Delete id
Search