A complete guide to learning and building projects with Python & Django — the powerful backend framework trusted by developers for creating dynamic, secure, and scalable web applications. From setup to deployment, master Django Models, Views, Templates, REST API, and authentication systems.
Django's static files handling involves serving CSS, JavaScript, images, and other files that do not change dynamically. Proper management of static files is crucial for web applications.
To manage static files in Django, follow these steps:
STATIC_URL
and STATICFILES_DIRS
in your settings.py
.{% load static %}
template tag to include static files in your templates.Here’s how you can set it up:
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'),]
And to include a CSS file in a template:
{% load static %}
Pagination in Django allows you to divide a large set of data into manageable pages. This improves the user experience by preventing information overload.
To implement pagination, follow these steps:
Paginator
and Page
from django.core.paginator
.Paginator
and specify the number of items per page.Here’s an example:
from django.core.paginator import Paginator
def my_view(request):
object_list = MyModel.objects.all()
paginator = Paginator(object_list, 10) # Show 10 items per page
page_number = request.GET.get('page')
page_obj = paginator.get_page(page_number)
return render(request, 'my_template.html', {'page_obj': page_obj})
In your template, you can iterate over page_obj
to display items and add pagination controls.
Django signals are a way to allow decoupled applications to get notified when certain actions occur elsewhere in the application. This is useful for executing actions in response to events.
To use signals, follow these steps:
django.dispatch
.signals.connect()
.Here’s an example of a signal that sends an email when a user is created:
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.contrib.auth.models import User
@receiver(post_save, sender=User)
def send_welcome_email(sender, instance, created, **kwargs):
if created:
# Logic to send email
print(f'Welcome {instance.username}!')
With this setup, the send_welcome_email
function is called automatically whenever a new user is created.