Posts

Showing posts from May, 2021

Internationalization (Language Setting) in Django

If your project want to run in English and a Spanish version edit the settings.py file of your project and add the following LANGUAGES setting to it.  Place it next to the LANGUAGE_CODE setting:                LANGUAGES = (                ('en', 'English'),                ('es', 'Spanish'),              ) The LANGUAGES setting contains two tuples that consist of a language code and a name .  Language codes can be locale-specific , such as en-us or en-gb , or generic , such as en . With this setting, we specified that application will only be available in English and Spanish.  If you don't define a custom LANGUAGES setting, the site will be available in all the languages that Django is translated into. Make your LANGUAGE_CODE setting look as follows:            ...

Django Authentication Framework

Django comes with a built-in authentication framework that can handle user authentication, sessions, permissions, and user groups. The authentication system includes views for common user actions such as log in, log out, password change, and password reset. The authentication framework is located at django.contrib.auth and is used by other Django contrib packages.  When you create a new Django project using the startproject command, the authentication framework is included in the default settings of your project. It consists of the django.contrib.auth application and the following 2 middleware classes found in the MIDDLEWARE setting of your project. AuthenticationMiddleware:  This class associates users with requests using sessions SessionMiddleware:  This class handles the current session across requests Middleware are the classes with methods that are globally executed during the request or response phase.  The authentication framework also includes the follo...

reverse_lazy() Method in Django

Use reverse_lazy() to generate the URL for the link attribute. The reverse() method allows you to build URLs by their name and pass optional parameters. The reverse_lazy() utility function is a lazily evaluated version of reverse(). It allows you to use a URL reversal before the project's URL configuration is loaded.

Messages Framework in Django

The Messages Framework is located at django.contrib.messages and it is included in the default INSTALLED_APPS list of settings.py file when we create new projects using python manage.py startproject.  The messages framework provides a simple way to add messages to users. settings file contains a middleware named django.contrib.messages.middleware. MessageMiddleware in the MIDDLEWARE settings. Messages are stored in a cookie by default, and they are displayed in the next request from the user.  The messages framework in your views by importing the messages module and adding new messages with simple shortcuts, as follows:                from django.contrib import messages                messages.error(request, 'Something Went Wrong Here....!') Create new messages using the add_message() method or any of the following shortcut methods: success(): Success messages to be displayed after an a...

NullBooleanField in Django

Django 2.1 introduced  null=True  for  BooleanField . Using  NullBooleanField  is now obsolete.  So use, boolean_field = BooleanField(null=True) instead of  boolean_field  = NullBooleanField()

Advantages to using URLField() over TextField()

URLField is actually CharField which supports Regex-based URL pattern checking and a online validator which was replaced by a RegEx based validator, where as use TextField if you are not consider length-limitation of URL. Use of CharField or TextField depends on whether you want max-length constraint on the field, and which element type is more suitable for editing like textarea or input.          Ex:           from django.core.validators import URLValidator          url_ field = models.TextField(validators=[URLValidator()])

URLField() in Django

 A URLField is a field of a database table or a form which stores only URLs. This field is generally used for storing webpage links called as URLs.  It is validated by URLValidator .  To store larger text, TextField is used. The default form widget for this field is TextInput .           Syntax:                field_name = models.URLField(max_length=250, **options)

Python Keywords

Below are the Python Key words, which form the basis of the Python language.  You are not allowed to use these words to name your variables, because these are the core commands of Python.  They must be spelled exactly as written here for the interpreter to recognize them as keywords.  The words True, False and None have a special meaning, which will be covered later. False True None and as assert break class continue def del elif else except finally for from global if import in is lambda nonlocal not or pass raise return try while with yield

Sending Emails with Django

Image
Sending Emails with Django is pretty straightforward. 1st, you need to have a local SMTP(Simple Mail Transfer Protocol) server, or you need to define the configuration of an external SMTP server by adding the following settings to the settings.py file of your project: EMAIL_HOST: The SMTP server host; the default is localhost . EMAIL_PORT: The SMTP port; the default is 25 . EMAIL_HOST_USER: The username for the SMTP server. EMAIL_HOST_PASSWORD: The password for the SMTP server. EMAIL_USE_TLS: Whether to use a TLS(Transport Layer Security) secure connection. EMAIL_USE_SSL: Whether to use an implicit TLS secure connection. If we can not use an SMTP server, we can tell Django to write emails to the console by adding the following setting to the settings.py file EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' By using this setting, Django will output all emails to the shell. This is very useful for testing your application without an SMTP server. If we want t...

Creating Model Managers in Django

Model Managers: object is the default manager of every model that retrieves all objects in the database.  We can also define custom managers for your models.  We will create a custom manager to retrieve all posts with the published status. There are 2 ways to add or customize managers for your models: you can add extra manager methods to an existing manager, or create a new manager by modifying the initial QuerySet that the manager returns.  The first method provides you with a QuerySet API such as Posts.objects.my_manager() The 2nd method provides you with Posts.my_manager.all().  The manager will allow you to retrieve posts using Posts.published.all(). Edit the models.py file of your <<xx>> application to add the custom manager: class xxManager(models.Manager):      def get_queryset(self):           return super(xxManager,                      ...

QuerySets Evaluation in Django

Creating a QuerySet does not involve any Database(DB) activity until it is evaluated.  QuerySets usually return another unevaluated QuerySet .  You can concatenate as many filters as you like to a QuerySet, and you will not hit the database until the QuerySet is evaluated.  When a QuerySet is evaluated, it translates into an SQL query to the database. QuerySets are only evaluated in the following scenarios: The first time you iterate over them When you pickle or cache them When you  slice  them, for Ex:, Posts.objects.all()[:5] When you call repr() or len() on them When you explicitly call list() on them When you test them in a statement, such as bool() , or, and , or if

delete() method in Django

If you want to delete an object, you can do it from the object instance using the delete() method. Ex:. post = Posts.objects.get(id=1) post.delete()

order_by() method in Django

Order results by different fields using the order_by() method of the manager. For Ex:, you can retrieve all objects ordered by their post_name, as follows: Posts.objects.order_by('post_name') Ascending order is implied. You can indicate descending order with a negative sign prefix. Posts.objects.order_by('-post_name')

exclude() method in Django

You can exclude certain results from the QuerySet using the exclude() method of the manager. For Ex:, you can retrieve all posts published in 2019 whose titles don't start with xyz: Posts.objects.filter(publish__year=2019).exclude(title__startswith='xyz') 

filter() method in Django

Use the filter() method to filter a  QuerySet . For Ex:, you can retrieve all posts created in the year 2019 using the following QuerySet: >> Posts.objects.filter(publish__year=2019) You can also filter by multiple fields. For Ex:, you can retrieve all posts published in 2019 by the author with the username abcd: >>> Posts.objects.filter(publish__year=2019, author__username='abcd')

Project Settings in Django

There are several settings that Django includes in settings.py file. Below are the few settings which are required: DEBUG:  DEBUG is a Boolean that turns the debug mode of the project on and off. When it is set to True, Django will display detailed error pages when an uncaught exception is thrown by the application. When you move to a production environment, remember that you have to set it to False. Never deploy a site into production with DEBUG turned on because you will expose sensitive project-related data. ALLOWED_HOSTS:  ALLOWED_HOSTS is not applied while debug mode is on or when the tests are run. Once you move your site into production and set DEBUG to False, you will have to add your domain/host to this setting in order to allow it to serve your Django site. INSTALLED_APPS : INSTALLED_APPS is a setting you will have to edit for all projects. This setting tells Django which applications are active for this site. By default, Django includes the following appli...

django-admin startproject myproject

Django provides a command that allows you to create an initial project file structure.  Run the following command from your shell:           django-admin startproject myproject           This will create a Django project with the name myproject.           myproject /                manage.py                myproject/                     __init__.py                     asgi.py                     wsgi.py                     settings.py                     urls.py manage.py:  manage.py is a command-line util...

manage.py Command Line in Django

manage.py: manage.py is a command-line utility used to interact with the project. It is a thin wrapper around the django-admin.py tool. You do not need to edit this file.

apps.get_model Application Registry in Django

apps.get_model(app_label, model_name, require_ready=True) This Application Registry returns the Model with the given app_label and model_name. As a shortcut, this method also accepts a single argument in the form app_label.model_name. model_name is case-insensitive. Raises LookupError if no such application or model exists.  Raises ValueError when called with a single argument that doesn’t contain exactly one dot. Requires the app registry to be fully populated unless the require_ready argument is set to False. Setting require_ready to False allows looking up models while the app registry is being populated, specifically during the second phase where it imports models. Then get_model() has the same effect as importing the model.  The main use case is to configure model classes with settings, such as AUTH_USER_MODEL . When require_ready is False, get_model() returns a model class that may not be fully functional until the app registry is fully populated. For this reason, it is ...

apps.is_installed(app_name) Application Registry in Django

apps.is_installed(app_name):- Checks whether an application with the given name exists in the registry.  app_name is the full name of the app, Ex: 'django.contrib.admin'.

apps.get_app_configs() Application Registry in Django

apps.get_app_configs():- Returns an iterable of AppConfig instances.

apps.ready Application Registry in Django

apps.ready:- Boolean attribute that is set to True after the registry is fully populated and all AppConfig.ready() methods are called.

apps Application Registry in Django

apps:- The application Registry provides the following public API.  Below are the Methods: apps.ready apps.get_app_configs() apps.get_app_config(app_label) apps.is_installed(app_name)

AppConfig.ready() in Django

AppConfig.ready():- This method subclasses can override to perform initialization tasks such as registering signals.  It is called as soon as the registry is fully populated. Although you can not import models at the module-level where AppConfig classes are defined, you can import them in ready(), using either an import statement or get_model(). If you are registering model signals, you can refer to the sender by its string label instead of using the model class itself. Note:  In the usual initialization process, the ready method is only called once by Django . But in some corner cases, particularly in tests which are fiddling with installed applications, ready might be called more than once. In this case, either write idempotent methods, or put a flag on your AppConfig classes to prevent re-running code which should be executed exactly one time..

AppConfig.get_model in Django

AppConfig.get_model: AppConfig.get_model(model_name, require_ready=True) This method returns the Model with the given model_name .  Here model_name is case-insensitive. It raises LookupError if no such model exists in this application. It requires the app registry to be fully populated unless the require_ready argument is set to False. require_ready behaves exactly as in apps.get_model().

AppConfig.get_models() Method in Django

AppConfig.get_models():-  This method returns an iterable of Model classes for the application. Requires the app registry to be fully populated.

AppConfig.models_module in Django

AppConfig.models_module:  This is attribute Module containing the models.      Ex:- <module 'django.contrib.admin.models' from 'django/contrib/admin/models.py'>. It may be None if the application doesn’t contain a models module.            Note:  The database related signals such as pre_migrate and post_migrate are only emitted for                     applications that have a models module.

AppConfig.module in Django

AppConfig.module:  This is the root module for the application.      Ex:- <module 'django.contrib.admin' from 'django/contrib/admin/__init__.py'>.

Forms in Django(bound, unbound, clean, is_valid, errors)

Bound and Unbound Forms: Form Instance is either bound to a set of data, or unbound. If it is bound to a set of data, it is capable of validating that data and rendering the form as HTML with the data displayed in the HTML. If it is unbound , it cannot do validation, because there’s no data to validate, but it can still render the blank form as HTML. To create an unbound Form instance, instantiate the class:          sf  = SampleForm() To bind data to a form, pass the data as a dictionary as the first parameter to your Form class constructor:           data = {'fieldname1': 'ABC', 'fieldname2': 'True, 'fieldname3': '123'}           sf = SampleForm(data) In the above dictionary, the keys are the field names, which correspond to the attributes in your Form class and the values are the data you are trying to validate. These will usually be strings, but there is no requirement that they be strings...