A step-by-step guide for beginners
Welcome to this Django project tutorial! In this tutorial, we will walk you through the process of creating your first Django project.
Create a virtual environment and install Django:
python -m venv myenv
source myenv/bin/activate
pip install django
Create a new Django project by running:
django-admin startproject myproject
Set up your model, form, view, and template to handle file uploads:
1. Set up your model with a FileField:
from django.db import models
class Document(models.Model):
title = models.CharField(max_length=100)
uploaded_file = models.FileField(upload_to='documents/')
2. Create a form for file upload:
from django import forms
from .models import Document
class DocumentForm(forms.ModelForm):
class Meta:
model = Document
fields = ('title', 'uploaded_file')
3. Set up your view to handle the form:
from django.shortcuts import render, redirect
from .forms import DocumentForm
def upload_file(request):
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return redirect('success')
else:
form = DocumentForm()
return render(request, 'upload.html', {'form': form})
4. Create a template for the upload form:
<!-- upload.html -->
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Upload</button>
</form>
One common problem in Django is handling user authentication. Here's a solution to set up user authentication in Django.
Create a custom user model if you need to extend the default user model:
from django.contrib.auth.models import AbstractUser
from django.db import models
class CustomUser(AbstractUser):
age = models.PositiveIntegerField(null=True, blank=True)
Update your settings to use the custom user model:
AUTH_USER_MODEL = 'yourapp.CustomUser'
Create a form for user registration:
from django import forms
from django.contrib.auth.forms import UserCreationForm
from .models import CustomUser
class CustomUserCreationForm(UserCreationForm):
class Meta:
model = CustomUser
fields = ('username', 'email', 'age')
Create a view to handle user registration:
from django.shortcuts import render, redirect
from django.contrib.auth import login
from .forms import CustomUserCreationForm
def register(request):
if request.method == 'POST':
form = CustomUserCreationForm(request.POST)
if form.is_valid():
user = form.save()
login(request, user)
return redirect('home')
else:
form = CustomUserCreationForm()
return render(request, 'register.html', {'form': form})
Create a template for user registration:
<!-- register.html -->
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Register</button>
</form>
Congratulations! You have successfully set up your first Django project, handled file uploads, and implemented user authentication. Continue exploring the Django documentation and experiment with different features to deepen your understanding.