💾 Archived View for gem.sdf.org › s.kaplan › cheatsheets › libraries-and-frameworks › django.md captured on 2024-05-12 at 15:32:12.
⬅️ Previous capture (2023-09-08)
-=-=-=-=-=-=-
# Django Cheatsheet ## Unique Features - Model-View-Controller (MVC) architecture - Object-Relational Mapping (ORM) - Automatic admin interface - URL routing - Template system - Django Rest Framework ## Models
class ModelName(models.Model):
field_name = models.FieldType()
python manage.py makemigrations
python manage.py migrate
## Views
def view_name(request):
# View body
return HttpResponse("Response")
path('url/', views.view_name, name='view_name'),
## Templates
<!-- Template syntax -->
{% for item in items %}
{{ item.attribute }}
{% endfor %}
## Forms
class FormName(forms.Form):
field_name = forms.FieldType()
def view_name(request):
form = FormName()
return render(request, 'template.html', {'form': form})
def view_name(request):
form = FormName(request.POST)
if form.is_valid():
# Form handling code
## Authentication
def register(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
return redirect('login')
else:
form = UserCreationForm()
return render(request, 'registration/register.html', {'form': form})
def login(request):
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
user = authenticate(request, username=username, password=password)
if user is not None:
auth_login(request, user)
return redirect('home')
else:
messages.error(request, 'Invalid username or password')
return render(request, 'registration/login.html')
def logout(request):
auth_logout(request)
return redirect('login')
## Resources - [Django Documentation](https://docs.djangoproject.com/) - [Django Girls Tutorial](https://tutorial.djangogirls.org/) - [Django for Beginners](https://djangoforbeginners.com/)