0 Comments

Explain user authentication in Django?

Django comes with a built-in user authentication system, which handles objects like users, groups, user-permissions, and a few cookie-based user sessions. Django User authentication not only authenticates the user but also authorizes him. The system consists and operates on these objects: Users, Permissions, Groups, Password Hashing System, Forms Validation, A pluggable backend system.

Static Files

How to configure static files?

Ensure that django.contrib.staticfiles is added to your INSTALLED_APPS. In your settings file, define STATIC_URL for example STATIC_URL = ‘/static/’. In your Django templates, use the static template tag to create the URL for the given relative path using the configured STATICFILES_STORAGE. {% load static %} ABC image. Store your static files in a folder called static in your app. For example my_sample/static/my_sample/abcxy.jpg.

Render Function

What is django.shortcuts.render function?

When a view function returns a webpage as HttpResponse instead of a simple string, we use render(). Render function is a shortcut function that lets the developer easily pass the data dictionary with the template. This function then combines the template with a data dictionary via templating engine. Finally, this render() returns as HttpResponse with the rendered text, which is the data returned by models. Thus, Django render() bypasses most of the developer’s work and lets him use different template engines. The basic syntax: render(request, template_name, context=None, content_type=None, status=None, using=None). The request is the parameter that generates the response. The template name is the HTML template used, whereas the context is a dict of the data passed on the page from the python. You can also specify the content type, the status of the data you passed, and the render you are returning.

Settings File

What’s the significance of the settings.py file?

As the name suggests, this file stores the configurations or settings of our Django project, like database configuration, backend engines, middlewares, installed applications, main URL configurations, static file addresses, templating engines, main URL configurations, security keys, allowed hosts, and much more.

Model Queries

How to view all items in the Model?

ModelName.objects.all()

How to filter items in the Model?

ModelName.objects.filter(field_name=”term”)

File-Based Sessions

How to use file-based sessions?

To use file-based sessions, set the SESSION_ENGINE setting to “django.contrib.sessions.backends.file”.

Mixins

What is a mixin?

A mixin is a type of multiple inheritance in which you can combine behaviors and attributes of more than one parent class. It provides a way to reuse code from multiple classes. However, using mixins can make it difficult to analyze a class’s behavior and which methods to override if the code is scattered across multiple classes.

Django Field Class

What is Django Field Class?

The Django Field class refers to an abstract class that represents a column in a database table. It is a subclass of RegisterLookupMixin. Fields are used to create database tables (db_types()) and map Python types to the database using get_prep_value() and from_db_value() methods. They are fundamental pieces in various Django APIs such as models and querysets.

Permanent Redirection

Why is permanent redirection not a good option?

Permanent redirection should only be used when you don’t want to lead visitors to the old URLs. However, the response of permanent redirections is cached by the browser. This can cause issues if you try to redirect to something else later, as the browser may still cache the old redirection.

Django Fields

Difference between Django OneToOneField and ForeignKey Field?

Both OneToOneField and ForeignKey fields are common types of fields used in Django. The main difference is that a ForeignKey field includes an on_delete option along with a model’s class because it’s used for many-to-one relationships. On the other hand, the OneToOneField only establishes a one-to-one relationship and requires only the model’s class.

QuerySets

How can you combine multiple QuerySets in a View?

To combine multiple QuerySets in a view, you can use the chain() function from the itertools module. This function allows you to concatenate multiple iterables (such as QuerySets) into a single iterable. Alternatively, you can use list comprehensions or other methods to merge or concatenate QuerySets as needed.

Difference between select_related and prefetch_related?

Though both the functions are used to fetch the related fields on a model but their functioning is bit different from each other. In simple words, select_related uses a foreign key relationship, i.e. using join on the query itself while on the prefetch_related there is a separate lookup and the joining on the python side.


from django.db import models
class Country(models.Model):
    country_name = models.CharField(max_length=5)
class State(models.Model):
    state_name = models.CharField(max_length=5)
    country = model.ForeignKey(Country)
>> states = State.objects.select_related('country').all()
>> for state in states:
…   print(state.state_name)  
Query Executed

Edit
Copy code
SELECT state_id, state_name, country_name FROM State INNER JOIN Country ON (State.country_id = Country.id)
country = Country.objects.prefetch_related('state').get(id=1) for state in country.state.all(): … print(state.state_name)

Edit
Copy code
Query Executed
SELECT id, country_name FROM country WHERE id=1; SELECT state_id, state_name WHERE State WHERE country_id IN (1);

Edit
Copy code

Querying with Q Objects

Explain Q objects in Django ORM?

Q objects are used to write complex queries, as in filter() functions just `AND` the conditions while if you want to `OR` the conditions you can use Q objects.


from django.db import models
from django.db.models import Q
>> objects = Models.objects.get(
   Q(tag__startswith='Human'),
   Q(category='Eyes') | Q(category='Nose')
)
Query Executed

Edit
Copy code
SELECT * FROM Model WHERE tag LIKE ‘Human%’ AND (category=’Eyes’ OR category

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Posts