0% found this document useful (0 votes)
5 views

Django Question and Answers

Uploaded by

Mitesh Waghe
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Django Question and Answers

Uploaded by

Mitesh Waghe
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

14) What is middleware in Django?

### **Middleware in Django**

Middleware in Django is a layer of processing that sits between the request and
response cycle. It is used to process requests before they reach the view and
modify the response before it is sent to the client.

### **Functions of Middleware:**


- **Request Processing**: Intercept and modify incoming requests (e.g.,
authentication, logging).
- **Response Processing**: Modify outgoing responses (e.g., adding headers,
compressing content).
- **Exception Handling**: Catch errors that occur during request processing and
return custom error pages.

### **Example:**
```python
class SimpleMiddleware:
def __init__(self, get_response):
self.get_response = get_response

def __call__(self, request):


# Code before view is called
print("Request received")
response = self.get_response(request)
# Code after view is called
print("Response sent")
return response
```

### **Types of Middleware**:


- **Request middleware**: Executes before the view function is called.
- **View middleware**: Executes when the view is called.
- **Exception middleware**: Handles errors that occur during request processing.
- **Response middleware**: Executes before the response is sent back to the client.

50) How do you implement Authorization and authentication in django?


In Django, **authentication** (verifying user identity) and **authorization**
(determining user permissions) are implemented using its built-in framework.

### Steps:
1. **Authentication:**
- Use `django.contrib.auth` for user login/logout.
- Example:
```python
from django.contrib.auth import authenticate, login
user = authenticate(username='user', password='pass')
if user:
login(request, user)
```

2. **Authorization:**
- Use `permissions` and `groups` to manage access.
- Example:
```python
if user.has_perm('app_label.permission_name'):
# Allow access
```
3. **Middleware:**
- Use `AuthenticationMiddleware` to associate users with requests.

4. **LoginRequiredMixin:**
- Restrict access to views.
- Example:
```python
from django.contrib.auth.mixins import LoginRequiredMixin
class MyView(LoginRequiredMixin, View):
pass
```

5. **Custom User Models (optional):**


- Extend `AbstractUser` for custom authentication needs.

6. **Third-party Tools:**
- Use `django-allauth` or `djangorestframework` for enhanced functionality like
social login or API token-based authentication.

Authentication and authorization are seamlessly integrated into Django’s request-


response cycle.

You might also like