Code Snippets
Find useful code snippets to speed up your development.
Django Form Handling
A snippet to handle forms in Django views.
from django.shortcuts import render
from django.http import HttpResponseRedirect
from .forms import MyForm
def my_view(request):
if request.method == 'POST':
form = MyForm(request.POST)
if form.is_valid():
# process form data
return HttpResponseRedirect('/success/')
else:
form = MyForm()
return render(request, 'my_template.html', {'form': form})
Django QuerySet Filtering
A snippet to filter QuerySets in Django.
from myapp.models import Article
# Get all articles published in 2023
articles_2023 = Article.objects.filter(published_date__year=2023)
Django Custom Template Tags
A snippet to create custom template tags in Django.
from django import template
register = template.Library()
@register.simple_tag
def current_time(format_string):
return datetime.datetime.now().strftime(format_string)