draft
Django Folder Structure
Django Naming Convention
Boilerplate & Scaffold
Python
Python
# To run a Django server on a different port
$ python manage.py runserver <port_number>
$ python manage.py runserver 8001
# To bind to a specific IP address
$ python manage.py runserver <ip_address>:<port_number>
$ python manage.py runserver 0.0.0.0:8001
# This will make your Django server accessible on all network interfaces on port 8001.
django best practices
2002, Can't connect to local MySQL server through socket
Q. django.db.utils.OperationalError: (2002, "Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)")
Django MVT Architecture
In the context of the Django web framework, a "view" is not just a "view" in the traditional Model-View-Controller (MVC) sense. Instead, it is more aligned with the "controller" part of MVC. Django follows a slightly different design pattern known as Model-View-Template (MVT), where the view acts more like a controller.
Here's a breakdown of the responsibilities in Django's MVT pattern:
-
Model:
The model represents the data structure of your application. It typically consists of Python classes that define the fields and behavior of your data, including interactions with the database.
-
View:
In Django, a view is a Python function or class that receives HTTP requests and returns HTTP responses. It's responsible for processing requests, fetching data from the database (via QuerySets), and passing that data to templates for rendering.
-
Template:
Templates are HTML files containing placeholders and template tags. They are responsible for rendering the data received from the view into a user-readable format. Templates can include dynamic content using template tags and filters.
In Django's MVT pattern
, the view acts as a controller that handles the business logic, database interactions, and data manipulation. It receives input from the user (HTTP requests), processes that input, interacts with the database through models and QuerySets, and passes the processed data to templates for rendering.
So, while the view in Django is similar to the controller in traditional MVC architectures, it also incorporates some aspects of the "view" in terms of rendering data to the user. However, the primary responsibility of the view in Django is to handle request processing and data manipulation, making it more akin to the controller in MVC.
Registering Models with the Admin
We have to register out app's model
such as MyEvent, MyUser with the admin
.
from django.contrib import admin
from .models import MyEvent, MyUser
admin.site.register(MyEvent)
admin.site.register(MyUser)
Q. Why do we need to register a model in Djano?
When you register a model with the admin, you can use the admin to add
, edit
and delete
model records.
Making Fields Optional
I have set the blank
field to True
. The default is False
, which makes the field required.
Advanced models
Django QuertSet API provides a comprehensive array of methods and function for working with data.
A Django QuerySet
is a collection of database queries used to fetch data from the database and perform various operations on it. It represents a collection of objects retrieved from your database, typically filtered, ordered, and limited. QuerySets allow you to interact with your database in a Pythonic way, providing a powerful and expressive API for retrieving, manipulating, and querying data.
## Basic Example
from myapp.models import Book
# Retrieve all books
all_books = Book.objects.all()
# Filter books by a certain condition
recent_books = Book.objects.filter(published_date__year=2022)
# Order books by a certain field
sorted_books = Book.objects.order_by('title')
# Retrieve a single book
book = Book.objects.get(title='Example Book')
# Count the number of books
num_books = Book.objects.count()
Advanced Example:
Suppose you have two models, Author
and Book
, where Book
has a foreign key relationship with Author
. Here's how you can use QuerySets for more complex operations:
from myapp.models import Author, Book
# Retrieve all books by a specific author
author = Author.objects.get(name='John Doe')
books_by_author = Book.objects.filter(author=author)
# Perform a join operation to get books published in a specific year by authors with a certain nationality
books_published_in_2022 = Book.objects.filter(published_date__year=2022, author__nationality='American')
# Retrieve the number of books written by each author
from django.db.models import Count
books_per_author = Author.objects.annotate(num_books=Count('book'))
# Perform a complex query combining multiple conditions
complex_query = Book.objects.filter(published_date__year=2022).exclude(author__nationality='British').order_by('-published_date')[:5]
uWSGI (Web Server Gateway Interface
)
Installation
project-level urls vs
app-level urls
In Django, URL patterns can be defined at both the project level and the app level. Here's a brief explanation of each:
-
Project-level URLs:
These are defined in the urls.py file at the project's root level. This file typically resides in the same directory as your settings.py file. Project-level URLs define the main URLs for your entire Django project. They are often used to include URLs from various apps within the project.
-
App-level URLs:
These are defined in the urls.py file within individual Django apps. Each app can have its own set of URLs, which are specific to the functionality provided by that app. App-level URLs are useful for organizing and encapsulating related views and functionality within the app.
Whether you should use both project-level and app-level URLs depends on the structure and complexity of your Django project:
Small projects: For small projects with a limited number of apps and URLs, you might choose to define all URLs in the project-level urls.py file. This keeps the URL configuration simple and centralized.
Medium to large projects: In larger projects with multiple apps and complex URL configurations, it's often beneficial to use both project-level and app-level URLs. Project-level URLs can serve as an entry point, including URLs from various apps, while each app can define its own URLs for its specific functionality.
Here's an example of how you might structure your URLs in a Django project:
project_name/
|-- manage.py
|-- project_name/
| |-- __init__.py
| |-- settings.py
| |-- urls.py # Project-level URLs
| |-- wsgi.py
|-- app1/
| |-- __init__.py
| |-- models.py
| |-- urls.py # App-level URLs for app1
| |-- views.py
|-- app2/
| |-- __init__.py
| |-- models.py
| |-- urls.py # App-level URLs for app2
| |-- views.py
In this structure, the project-level urls.py file might include URLs from app1.urls
and app2.urls
, while each app (app1 and app2) has its own urls.py file defining URLs specific to that app's functionality. This approach allows for better organization and separation of concerns in larger projects.
Programming
JS Functional Programming
The idea is not to throw away everything you’ve learned and use and adopt a 100% functional way; rather, the guiding idea is evolution, not revolution.
It’s easy to apply a given function from some package or the other, but by coding everything out (vanilla FP
, if you wish), it’s my belief that you get to understand things more deeply.
OO design patterns
Functional design patterns
What Is DevOps?
The term DevOps
is derived from the combination of two words
: developer and operations.
DevOps
is used to define a movement born of the need for reducing barriers between the development and operations teams of a company. The goal of DevOps is to reduce time to market. This means adopting DevOps practices, to reduce the time needed, from the identification of a new requirement to the time it goes live for customers.
The DevOps
journey introduces such practices as continuous integration and continuous
delivery, which help to reduce time to market and produce better quality software.
Common menus on websites often include:
- Home: The homepage of the website, typically linked to the logo in the header.
- About: Information about the company, organization, or website.
- Products/Services: If applicable, a menu item leading to a page showcasing the products or services offered.
- Blog/News: A section for articles, updates, or news related to the website's topic or industry.
- Contact: Contact information or a contact form for users to reach out.
- Portfolio/Projects: For showcasing past work or projects, often seen on agency or freelancer websites.
- FAQ: Frequently Asked Questions, if applicable.
- Testimonials: Customer testimonials or reviews, typically found on business websites.
- Events/Calendar: For listing upcoming events, conferences, or important dates.
- Resources: Links to downloadable resources, documents, or helpful tools.
- Search: A search bar to help users find specific content on the website.
- Login/Register: If the website requires user authentication, links to login or register for an account.
- Terms of Service/Privacy Policy: Legal pages outlining terms of use and privacy policies.
- Sitemap: A structured layout of the website's content, helpful for navigation and SEO.
- Social Media Links: Icons linking to the website's social media profiles.
The specific menu items will vary depending on the purpose and content of the website. It's important to consider the needs of your audience and the goals of your website when determining which menu items to include. Additionally, the menu structure should be intuitive and easy to navigate for users.
Django DEBUG
value
It looks like you're setting the DEBUG value to False in your .env file and then trying to retrieve it in your settings.py file using os.environ.get('DEBUG')
. The code you've shown seems correct in terms of retrieving the DEBUG
value from the environment variables.
However, the issue might arise if the DEBUG value is not being retrieved correctly or if it's not being interpreted as a boolean value. Here are a few things you can check:
-
Ensure
.env
file is loaded: Make sure your.env
file is being loaded properly by your application. Sometimes, this requires additional configuration, especially if you're using a framework like Django or Flask. -
Check DEBUG value: Verify that the DEBUG value in your
.env
file is set to either 'True' or 'False', and not any other string. It's case-sensitive, so 'True' and 'False' should be all uppercase. -
Convert DEBUG value to boolean: Since DEBUG is typically a boolean value in Django (True or False), you might want to explicitly convert it to a boolean in your
settings.py
file:This code will set
DEBUG
to True if the DEBUG environment variable is set toTrue
(case insensitive), andFalse
otherwise. -
Fallback value: Provide a fallback value in case the DEBUG environment variable is not set in your .env file. For example:
This will default
DEBUG
toFalse
if theDEBUG
environment variable is not set. -
Check for typos: Ensure there are no typos in your code or in your .env file. Even a small typo can cause issues.
-
Restart your server: After making changes to your
.env
file or your settings.py file, make sure to restart your server to apply the changes.
If you've checked all of the above and are still facing issues, please provide more details or error messages for further assistance.
Programming Jokes
Blogs
1. Using decorator in Class-Based-Views Django
method_decorator is a function provided by Django's django.utils.decorators
module. It serves as a bridge between function decorators and class-based views in Django. While decorators are typically used with functions, method_decorator
enables their usage with class methods.
How does it work?
Consider a scenario where you have a class-based view in Django. Each method within the class corresponds to an HTTP request method (e.g., get, post, put). Sometimes, you might want to apply a decorator to one of these methods. This is where method_decorator
comes into play.
By decorating a method with method_decorator
, you can apply any decorator to that method, just as you would with a regular function. This allows for cleaner, more modular code, as decorators can be applied directly to the methods they are intended to modify.
When to use
method_decorator
?
-
DRY Principle:
When you find yourself repeating the same decorator across multiple view methods,
method_decorator
can help you adhere to the Don't Repeat Yourself (DRY) principle by applying the decorator directly to the methods. -
Granular Control:
method_decorator
provides granular control over which methods within a class-based view are decorated. This can be particularly useful when you need different decorators for different methods. -
Keeping Views Clean:
Using
method_decorator
helps keep your views clean and focused on business logic by separating concerns related to request handling (e.g.,authentication
,caching
) into decorators.
from django.views.generic import View
from django.http import HttpResponse
from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import login_required
class MyView(View):
@method_decorator(login_required)
def get(self, request):
# Your view logic for handling GET requests
return HttpResponse("This view requires authentication.")
In this example, the login_required
decorator is applied directly to the get method of the MyView class using method_decorator. This ensures that the view requires authentication for GET requests.
Conclusion:
method_decorator
is a valuable tool in Django for applying decorators to class-based view methods. By leveraging this utility, developers can write cleaner, more modular code while maintaining granular control over the behavior of their views. Whether it's enforcing authentication, caching responses, or handling other cross-cutting concerns, method_decorator
empowers developers to enhance the functionality and security of their Django applications with ease.
2. Most used decorators in django
In Django, decorators play a crucial role in modifying the behavior of views, including class-based views (CBVs). Some of the most commonly used decorators in class-based views are:
-
@method_decorator:
This is a utility provided by Django that allows decorators to be applied to class-based view methods. It's not a decorator itself but a tool for applying decorators to methods within a class-based view.
-
@login_required:
Ensures that the user must be authenticated to access the view. If the user is not authenticated, they are redirected to the login page.
-
@permission_required:
Requires that the user has specific permissions to access the view. If the user lacks the required permissions, they are redirected to a specified page.
-
@csrf_exempt:
Exempts the view from CSRF (Cross-Site Request Forgery) protection. This is useful for views that handle external POST requests or APIs.
-
@cache_page:
Caches the output of the view for a specified amount of time, improving performance by serving cached responses for subsequent requests.
-
@transaction.atomic:
Ensures that the database operations within the view are executed within a single transaction. Changes are rolled back if an exception occurs.
-
@require_http_methods:
Restricts the HTTP methods allowed for accessing the view. It ensures that only specific HTTP methods (e.g., GET, POST) are supported.
-
@cache_control:
Sets HTTP caching headers for the view response, controlling caching behavior in the client's browser or intermediary caches.
-
@gzip_page:
Compresses the response content using gzip compression, reducing bandwidth usage and improving page load times.
-
@vary_on_headers:
Specifies which request headers should be considered when caching responses, allowing for more granular cache control based on specific headers.
from django.views.generic import View
from django.http import HttpResponse
from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import login_required
from django.views.decorators.csrf import csrf_exempt
# Define a class-based view
class MyView(View):
# Apply the login_required decorator to the dispatch method
@method_decorator(login_required)
def dispatch(self, *args, **kwargs):
return super().dispatch(*args, **kwargs)
# Apply the csrf_exempt decorator to the post method
@method_decorator(csrf_exempt)
def post(self, request):
# Handle POST request
return HttpResponse("This is a POST request.")
def get(self, request):
# Handle GET request
return HttpResponse("This is a GET request.")
These decorators provide a wide range of functionality for controlling access, performance, and behavior within class-based views in Django applications. Depending on your application's requirements, you can use these decorators to enforce security measures, optimize performance, and customize the behavior of your views.
3. dispatch method in Class-Based-Views django
In Django, dispatch
is a method provided by the View
class, which is the base class for all class-based views
(CBVs). The dispatch method is responsible for routing incoming requests to the appropriate HTTP method handlers (get
, post
, put
, etc.) based on the request's HTTP method.
Overall, dispatch
serves as the entry point for request handling in class-based views
, providing a centralized mechanism for routing requests to the appropriate method handlers and enabling extensibility and integration with Django's middleware architecture.
When to use dispatch
You should use the dispatch
method in Django when you are working with class-based views
(CBVs) and need to customize or extend the default request-handling behavior.
Here are some scenarios where you might use dispatch
:
-
Authentication and Authorization:
You might use
dispatch
to enforce authentication and authorization requirements for your views. For example, you could override dispatch to check whether the user is authenticated and redirect them to a login page if not. -
Custom Request Processing:
If you need to perform custom processing on incoming requests before they are handled by the view's methods (
get
,post
, etc.), you can overridedispatch
to add this logic. This could include validation, parsing request data, or logging. -
Error Handling:
dispatch
can be used to implement custom error handling logic for specific types of errors that occur during request processing. For example, you could override dispatch to catch certain exceptions and return a custom error response. -
Middleware Integration:
If you're working with Django middleware and need to interact with requests at an early stage of processing, you can override
dispatch
to integrate middleware functionality. Middleware can intercept requests before they reach the view methods. -
Request Routing:
While Django's default dispatch implementation routes requests based on the HTTP method (
GET
,POST
, etc.), you might need to implement custom request routing logic for specialized use cases. Overriding dispatch allows you to customize how requests are routed within your view.
from django.views import View
from django.http import HttpResponse
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
class ProtectedView(View):
@method_decorator(login_required)
def dispatch(self, *args, **kwargs):
return super().dispatch(*args, **kwargs)
def get(self, request):
return HttpResponse("This is a protected GET request.")
def post(self, request):
return HttpResponse("This is a protected POST request.")
In summary, you should use the dispatch method whenever you need to customize or extend the default request-handling behavior of class-based views in Django. It provides a centralized hook for implementing various request-processing features, making it a powerful tool for building flexible and feature-rich web applications.
Ajax with Django
TESTING active link ajax
To remove the active
class from the previously clicked link before adding it to the currently clicked link
, you can store a reference to the previously clicked link and remove the active class from it before adding it to the currently clicked link.
$(document).ready(function(){
var previousClickedLink = null; // Reference to the previously clicked link
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie !== '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i].trim();
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
var csrftoken = getCookie('csrftoken');
$('.business-item-link').click(function(event) {
event.preventDefault();
var slug = $(this).data('slug');
var clickedLink = $(this); // Reference to the clicked link
// Remove active class from the previously clicked link
if (previousClickedLink !== null) {
previousClickedLink.removeClass('active');
}
// AJAX GET request to fetch data
$.ajax({
url: '/business/' + slug + '/ajax/',
type: 'GET',
beforeSend: function(xhr, settings) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
},
success: function(response){
if (response.hasOwnProperty('title')) {
$('.bt__bussiness--title').text(response.title);
}
console.log("Response content: ", response.content);
if (response.hasOwnProperty('content')) {
$('.business-item-content').html(response.content);
}
// Add active class to the clicked link
clickedLink.addClass('active');
// Store a reference to the currently clicked link as the previous clicked link
previousClickedLink = clickedLink;
},
error: function(xhr, errmsg, err){
console.error('Error fetching data:', errmsg);
}
});
});
});
class BusinessItemView(TemplateView):
template_name = 'business/business-item.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
slug = kwargs['slug']
business_item = get_object_or_404(BusinessItem, slug=slug)
context['business_item'] = business_item
business_inner = BusinessInner.objects.first()
context['business_inner'] = business_inner
return context
def get_ajax_data(self, request, *args, **kwargs):
slug = kwargs['slug']
business_item = get_object_or_404(BusinessItem, slug=slug)
# Construct data to send in JSON response
print("business_item: ", business_item)
# Check if this is the active link
absolute_url = business_item.get_absolute_url()
is_active = True if request.path == absolute_url else False
print('absolute_url: ', absolute_url)
print('is_active: ', is_active)
data = {
'title': business_item.title,
'content': business_item.content,
'is_active': is_active
# Add more data as needed
}
return JsonResponse(data)
def dispatch(self, request, *args, **kwargs):
# Check if it's an AJAX request
# if request.is_ajax(): is depreciated
if request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest':
# If yes, call the get_ajax_data method
return self.get_ajax_data(request, *args, **kwargs)
else:
# If not, call the parent dispatch method to handle the regular view
return super().dispatch(request, *args, **kwargs)
class BusinessItem(models.Model):
CHOICES = (
('1', 'Product & Services'),
('2', 'Business Consulting'),
('3', 'IT Services'),
)
title = models.CharField(max_length=120)
category = models.CharField(max_length=20, choices=CHOICES)
content = HTMLField(null=True, blank=True)
slug = AutoSlugField(populate_from='title', unique=True, blank=True, default=None, editable=True)
def get_absolute_url(self):
return reverse('business:item_ajax', kwargs={'slug': self.slug})
def __str__(self):
return self.title
class Meta:
db_table = "ispl_business_item"
verbose_name = 'Business Item'
verbose_name_plural = 'Business Items'
Conditonally display Team Image
$(document).ready(function() {
// Assuming `slug` and `csrftoken` are defined elsewhere
$.ajax({
url: '/about/' + slug + '/ajax/',
type: 'GET',
beforeSend: function(xhr, settings) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
},
success: function(response) {
console.log('console response', response);
if (response.hasOwnProperty('title')) {
$('.bt__bussiness--title').text(response.title);
}
if (response.hasOwnProperty('content')) {
$('.business-item-content').html(response.content);
}
if (slug === 'message') {
if (response.hasOwnProperty('team_item')) {
var teamItems = JSON.parse(response.team_item);
$('.team-img').empty();
teamItems.forEach(function(teamItem) {
var itemHtml = `
<div class="team-item">
<img src="/media/${teamItem.fields.image}" alt="${teamItem.fields.name}">
<h3>${teamItem.fields.name}</h3>
<h4>${teamItem.fields.position}</h4>
${teamItem.fields.content}
</div>
`;
$('.team-img').append(itemHtml);
});
} else {
// If `team_item` does not exist, ensure the `.team-img` is empty
$('.team-img').empty();
}
} else {
// If `slug` is not 'message', ensure the `.team-img` is empty
$('.team-img').empty();
}
clickedLink.addClass('active');
previousClickedLink = clickedLink;
},
error: function(xhr, errmsg, err) {
console.error('Error fetching data:', errmsg);
}
});
});
from django.shortcuts import render, get_object_or_404
from django.views.generic import TemplateView, DetailView
from django.http import JsonResponse
from django.core.serializers import serialize
from .models import About, AboutInner, AboutItem
from teams.models import TeamItem
class AboutItemView(DetailView):
model = AboutItem
template_name = "about_us/item.html"
context_object_name = "about_items"
slug_field = 'slug'
def get_ajax_data(self, request, *args, **kwargs):
slug = kwargs['slug']
about_item = self.get_object()
absolute_url = about_item.get_absolute_url()
is_active = True if request.path == absolute_url else False
team_item = TeamItem.objects.all()
team_item_serailize = serialize('json', team_item)
data = {
'title': about_item.title,
'content': about_item.content,
'is_active': is_active,
'team_item': team_item_serailize
}
return JsonResponse(data)
def dispatch(self, request, *args, **kwargs):
# Check if it's an AJAX request
if request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest':
# If yes, call the get_ajax_data method
return self.get_ajax_data(request, *args, **kwargs)
else:
# If not, call the parent dispatch method to handle the regular view
return super().dispatch(request, *args, **kwargs)
DJANGO AJAX VIEW
The {% if not request.is_ajax %}
line in a Django template is used to conditionally render content based on whether the request is an AJAX request or not. However, this syntax is not directly supported in Django templates out of the box. Instead, you typically handle AJAX requests in your views and use different templates or partial templates based on the request type.
Understanding AJAX in Django Views
To render different content based on whether the request is an AJAX request, you need to handle this logic in your Django view. Here's how you can achieve this:
-
Detecting AJAX Requests in the View:
You can check if the request is an AJAX request in your view using request.is_ajax(). This method was deprecated in Django 3.1 and removed in Django 4.0. Instead, you should check the HTTP_X_REQUESTED_WITH header directly.
-
Handling AJAX and Non-AJAX Requests:
Based on the request type, you can render different templates or return JSON responses.
Example Implementation
First, create a view that handles both AJAX and non-AJAX requests.
Django Viewfrom django.http import JsonResponse from django.core.serializers import serialize from django.views.generic.detail import DetailView from teams.models import TeamItem from about.models import AboutItem # Adjust according to your actual model import class AboutItemView(DetailView): model = AboutItem template_name = "about_us/item.html" context_object_name = "about_items" slug_field = 'slug' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['team_items'] = TeamItem.objects.all() return context def get_ajax_data(self, request, *args, **kwargs): about_item = self.get_object() team_items = TeamItem.objects.all() team_items_serialized = serialize('json', team_items) data = { 'title': about_item.title, 'content': about_item.content, 'team_item': team_items_serialized, } return JsonResponse(data) def dispatch(self, request, *args, **kwargs): if request.headers.get('x-requested-with') == 'XMLHttpRequest': return self.get_ajax_data(request, *args, **kwargs) return super().dispatch(request, *args, **kwargs)
In your template, you do not need to use
{% if not request.is_ajax %}
. Instead, you prepare the template to display the data properly. Here’s an example:<div class="col-md-9"> <h5 class="bt__bussiness--title bt-sec-title">{{ about_items.title }}</h5> <div class="business-item-content">{{ about_items.content | safe }}</div> <div class="team-img"> {% for team_item in team_items %} <div class="team-item"> <img src="{{ team_item.image.url }}" alt="{{ team_item.name }}"> <h3>{{ team_item.name }}</h3> <h4>{{ team_item.position }}</h4> {{ team_item.content | safe }} </div> {% endfor %} </div> </div>
Ensure your JavaScript handles the AJAX request correctly and updates the DOM if the request is an AJAX request.
$(document).ready(function() { $.ajax({ url: '/about/' + slug + '/ajax/', type: 'GET', beforeSend: function(xhr, settings) { xhr.setRequestHeader("X-CSRFToken", csrftoken); }, success: function(response) { if (response.hasOwnProperty('title')) { $('.bt__bussiness--title').text(response.title); } if (response.hasOwnProperty('content')) { $('.business-item-content').html(response.content); } if (slug === 'message' && response.hasOwnProperty('team_item')) { var teamItems = JSON.parse(response.team_item); $('.team-img').empty(); teamItems.forEach(function(teamItem) { var itemHtml = ` <div class="team-item"> <img src="/media/${teamItem.fields.image}" alt="${teamItem.fields.name}"> <h3>${teamItem.fields.name}</h3> <h4>${teamItem.fields.position}</h4> ${teamItem.fields.content} </div> `; $('.team-img').append(itemHtml); }); } else { $('.team-img').empty(); } }, error: function(xhr, errmsg, err) { console.error('Error fetching data:', errmsg); } }); });
Summary
- View: Handles both AJAX and non-AJAX requests, returning JSON for AJAX requests and rendering the full template for non-AJAX requests.
- Template: Designed to display the necessary data without conditional AJAX checks.
- JavaScript: Properly handles the AJAX request and updates the DOM based on the response.
By structuring your view and template this way, you can cleanly separate the handling of AJAX and non-AJAX requests.
Plugins UI
JS
How to see the JavaScrit methods in the console.
Tips
console.log(obj)
: Logs the entire object to the console, showing properties and methods.Object.keys(obj)
: Returns an array of enumerable properties directly on the object.Object.getOwnPropertyNames(obj)
: Returns an array of all properties directly on the object.for...in loop
: Iterates over all enumerable properties, including inherited ones.Reflect.ownKeys(obj)
: Returns an array of all property keys on the object.Object.getOwnPropertyNames(Object.getPrototypeOf(obj))
: Returns an array of properties on the object's prototype, which includes methods.
IDEAS
Django Project
- Multi Mullingual Database (MMDB)
Translating our static content
To translate strings that are used in templates, Django provides us with a trans template tag.
Daintree
– an E-commerce Site
A basic e-commerce
site has one main purpose: to help users find and buy products from the online store. Django alone can be used to build an e-commerce site quickly, using database queries to allow searches across product range, but this doesn't scale well. Databases are designed to quickly save and retrieve rows of data, but they are not optimized to search across the entire dataset (or a subset). Once the traffic of your site starts to increase, you'll see the search speed go down very quickly. On top of that, there are some features that are very difficult to build with a database.
Instead, we will use a search server. A search server is very much like a database.You give it some data to store and then you can retrieve it later. It also has features specifically built to help you add searching to your applications. You might wonder that if a search server can store our data like a database, then can we not just get rid of the database? We can, but usually it's not recommended. Why? Well, because the search server is designed for a different use case. While it can store your data, a database provides a lot of guarantees about the storage that a search server usually doesn't. For example, a good database (such as MySQL or PostgreSQL) gives you a guarantee that if you try to save something and the database returns a successful response, your data will not be lost in case of a crash or power outage or some other problem. This is called durability. A search server does not provide this guarantee because that's not what they are designed for. It is usually a good idea to keep our data in a database and use the search server just to search across our data.
For the application that we will develop in this chapter, we will be using Elasticsearch, one of the most popular and perhaps easy-to-use search servers available. It's also open source and available for free. So let's get started. This is going to be an exciting chapter!
To load the test data, run the following command after the migrate
command:
This should fill your database with a thousand sample products and give us enough data to play around with.
Searching from Python
The library that we will be using here is elasticsearch_dsl
.
> python manage.py shell
> from elasticsearch_dsl import Search
> from elasticsearch_dsl.connections import connections
> connections.create_connection(hosts=['localhost:9200'])
<Elasticsearch([{u'host': u'localhost', u'port': 9200}])>
> Search(index='daintree').query('match', name='django').execute().
to_dict()
{
u'_shards': {u'failed': 0, u'successful': 5, u'total': 5},
u'hits': {u'hits': [{u'_id': u'1',
u'_index': u'daintree',
u'_score': 0.19178301,
u'_source': {u'category': u'Book',
u'name': u'Django Blueprints',
u'price': 50,
u'tags': [u'django', u'python', u'web applications']},
u'_type': u'products'}],
u'max_score': 0.19178301,
u'total': 1},
u'timed_out': False,
u'took': 2
}
Let's take a look at each line. The first two lines simply import the library. The third line is important. It uses the create_connection method to define a default connection. This is the connection that will be used whenever we try to do a search using this library with the default settings.
Elasticsearch Django
watch this blog How to Use ElasticSearch With Django: medium
- Elasticsearch DSL: readthedocs
- elasticsearch-dsl 0.0.2 : pypi
- How to Use Elasticsearch with Django?
- How to Use ElasticSearch With Django: medium
Signals
Introduction
There are 3 types of signals:
- pre_save/post_save: This signal works before/after the method
save()
. - pre_delete/post_delete: This signal works before after deleting a model’s instance (method
delete()
) this signal is thrown. - pre_init/post_init: This signal is thrown before/after instantiating a model (
__init__()
method).
Example
Sure! Let’s walk through a simple example of using Django signals to automatically update a user profile's post_count
field whenever a new BlogPost
is created. This will demonstrate how to use Django signals in a real-world scenario.
Step-by-Step Guide
-
Define the Models
Create BlogPost and UserProfile models in your models.py file:
# models.py from django.db import models from django.contrib.auth.models import User class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) post_count = models.PositiveIntegerField(default=0) def __str__(self): return self.user.username class BlogPost(models.Model): title = models.CharField(max_length=100) content = models.TextField() author = models.ForeignKey(User, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title
-
Create the Signal Handler
Create a
signals.py
file in your app directory and define the signal handler to update thepost_count
:# signals.py from django.db.models.signals import post_save from django.dispatch import receiver from .models import BlogPost, UserProfile @receiver(post_save, sender=BlogPost) def update_post_count(sender, instance, created, **kwargs): if created: profile = UserProfile.objects.get(user=instance.author) profile.post_count = BlogPost.objects.filter(author=instance.author).count() profile.save()
-
Connect the Signal
Ensure that the signal handler is connected by modifying the
apps.py
file of your app to import the signal handlers when the app is ready: -
Ensure UserProfile is Created
Make sure that a
UserProfile
is created whenever a newUser
is created. You can do this by using another signal:# signals.py (add this to the existing file) from django.db.models.signals import post_save from django.contrib.auth.models import User from django.dispatch import receiver from .models import UserProfile @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: UserProfile.objects.create(user=instance)
-
Migrate Your Database
Run the migrations to apply the changes to your database:
-
Create and Save a Blog Post
Now, create a new BlogPost instance and see the post_count update automatically:
# Use the Django shell to test python manage.py shell >>> from django.contrib.auth.models import User >>> from your_app.models import BlogPost, UserProfile # Create a user and profile >>> user = User.objects.create_user(username='testuser', password='password') >>> user_profile = UserProfile.objects.get(user=user) # Create a new blog post >>> new_post = BlogPost.objects.create(title='My First Post', content='This is the content of my first post.', author=user) # Check the updated post count >>> user_profile.refresh_from_db() >>> user_profile.post_count 1
Summary
- Models: Define BlogPost and UserProfile models in models.py.
- Signal Handler: Create signal handlers in signals.py to update the post count and create user profiles.
- App Configuration: Connect the signal in apps.py.
- Database Migrations: Run migrations to apply model changes.
- Usage: Create a BlogPost instance and observe the automatic update to the post_count.
This example demonstrates how to use Django signals to perform an action (updating a profile’s post count) in response to an event (creating a new blog post).
Django widgets
Tip
Django widgets have several attributes and methods that can be utilized for customization and functionality
Common Attributes:
-
attrs: A dictionary containing HTML attributes to be rendered with the widget, such as
{'class': 'form-control', 'placeholder': 'Enter your name'}
. -
template_name: Specifies the template used to render the widget. It allows you to customize the HTML markup of the widget.
-
is_hidden: A boolean attribute indicating whether the widget should be rendered as hidden or not.
-
choices: For choice-based widgets (like Select), it specifies the choices available for selection.
-
required: Specifies whether the field is required or not.
Common Methods:
-
render: Renders the HTML markup of the widget. This method is called automatically when the widget is rendered in a template.
-
value_from_datadict(data, files, name): Retrieves the value of the widget from the data dictionary.
-
format_value(value): Formats the value of the widget before rendering.
-
get_context(name, value, attrs): Returns a dictionary containing the context data used for rendering the widget template.
-
id_for_label(id_): Returns the ID to be used for the
-
use_required_attribute(initial): Determines whether the widget should use the HTML required attribute based on the initial value.
-
build_attrs(base_attrs, extra_attrs=None): Combines the base attributes with any extra attributes specified and returns a dictionary of HTML attributes.