B.
Wakim
Outline
Upload files
➢ Simple File Upload
➢ Upload File With Model Forms
Generic views
➢ List view
➢ Detail view
➢ Create / Update / Delete view
User authentication
➢ Class user fields and methods
➢ Login / Logout
19/03/2025 Django Upload files 2
19/03/2025 Django Upload files 3
Uploaded files¶
During file uploads, the actual file data is stored in [Link].
Each entry in this dictionary is an UploadedFile object.
Some useful attributes of UploadedFile:
[Link]: The name of the uploaded file (e.g. my_file.txt).
[Link]: The size, in bytes, of the uploaded file.
When you upload a file, it is uploaded into your infosite folders by
default.
If you want to use a specific folder for your uploaded files, you will need
to set MEDIA_URL and MEDIA_ROOT in your project’s [Link].
MEDIA_URL = '/media/'
MEDIA_ROOT = [Link](BASE_DIR, 'media')
19/03/2025 Django Upload files 4
Simple File Upload - simple_upload.html
{% extends '[Link]' %}
{% load static %}
{% block content %}
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" name="myfile">
<button type="submit">Upload</button>
</form>
{% if uploaded_file_url %}
<p>File uploaded at: <a href="{{ uploaded_file_url }}">{{ uploaded_file_url }}</a></p>
{% endif %}
{% endblock %}
19/03/2025 Django Upload files 5
Simple File Upload – [Link]
from [Link] import render
from [Link] import settings
from [Link] import FileSystemStorage
def simple_upload(request):
if [Link] == 'POST‘ :
myfile = [Link]['myfile']
fs = FileSystemStorage()
filename = [Link]([Link], myfile)
uploaded_file_url = [Link](filename)
return render(request, 'simple_upload.html', {
'uploaded_file_url': uploaded_file_url
})
return render(request, 'simple_upload.html')
19/03/2025 Django Upload files 6
Basics of File Upload With Django
When files are submitted to the server, the file data ends up placed in
[Link].
It is mandatory for the HTML form to have the attribute enctype="multipart/form-
data" set correctly. Otherwise the [Link] will be empty.
The form must be submitted using the POST method.
Django have proper model fields to handle uploaded files: FileField and ImageField.
The files uploaded to FileField or ImageField are not stored in the database but in
the filesystem.
FileField and ImageField are created as a string field in the database (usually
VARCHAR), containing the reference to the actual file.
The [Link] is a dictionary-like object. Each key in [Link] is the name
from the <input type="file" name="" />.
Each value in [Link] is an UploadedFile instance.
19/03/2025 Django Upload files 7
File storage
The FileSystemStorage class implements basic file storage on a local file system.
It inherits from class Storage.
class Storage: provides a standardized API for storing files, along with a set of
default behaviours that all other storage systems can inherit or override as
necessary.
delete(name): Deletes the file referenced by name.
exists(name): Returns True if a file referenced by the given name already exists in the
storage system, or False if the name is available for a new file.
get_accessed_time(name): returns a datetime of the last accessed time of the file.
get_created_time(name): returns a datetime of the creation time of the file.
get_modified_time(name): returns a datetime of the last modified time of the file.
path(name): The local filesystem path where the file can be opened.
save(name, content, max_length=None): Saves a new file using the storage system,
preferably with the name specified.
size(name): Returns the total size, in bytes, of the file referenced by name.
url(name): Returns the URL where the contents of the file referenced by name can be
accessed.
19/03/2025 Django Upload files 8
Uploaded files¶
During file uploads, the actual file data is stored in [Link]. Each entry
in this dictionary is an UploadedFile object.
You’ll usually use one of these methods to access the uploaded content:
[Link](num_bytes=None): Read the entire uploaded data from
the file.
UploadedFile.multiple_chunks(): returns True if the uploaded file is big
enough to require reading in multiple chunks.
[Link](chunk_size=None): A generator returning chunks of
the file. If multiple_chunks() is True, you should use this method in a loop
instead of read().
19/03/2025 Django Upload files 9
19/03/2025 Django Upload files 10
File Upload With Model Forms
[Link]
from [Link] import models
class Document([Link]):
description = [Link](max_length=255, blank=True)
document = [Link](upload_to='documents/')
uploaded_at = [Link](auto_now_add=True)
N.B: don’t forget to register your Document model in [Link] and to migrate your new
model.
[Link]
from django import forms
from [Link] import Document
class DocumentForm([Link]):
class Meta:
model = Document
fields = ('description', 'document', )
19/03/2025 Django Upload files 11
File Upload With Model Forms – [Link]
from [Link] import render, redirect
from [Link] import settings
from [Link] import FileSystemStorage
from [Link] import HttpResponse
from [Link] import DocumentForm
def model_form_upload(request):
if [Link] == 'POST':
form = DocumentForm([Link], [Link])
if form.is_valid():
[Link]()
return redirect(‘index')
else:
form = DocumentForm()
return render(request, 'model_form_upload.html', {
'form': form
})
19/03/2025 Django Upload files 12
File Upload With Model Forms - html
model_form_upload.html
{% block content %}
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Upload</button>
</form>
<p><a href="{% url ‘index' %}">Return to home</a></p>
{% endblock %}
19/03/2025 Django Upload files 13
19/03/2025 Django Upload files 14
Generic views
Generic views: let you quickly provide common views of an
object without actually needing to write any Python code.
Django ships with generic views to do the following:
Display list and detail pages for a single object.
Create, Update, Delete view
19/03/2025 Django Upload files 15
Generic views application
Create a new application: infogeneric (startapp)
Add this application in [Link] in your site
Install pillow for image field:
python -m pip install Pillow
Once you define your models, makemigrations and migrate
Create your [Link] and [Link]
Include your urls into the site urls
19/03/2025 Django Upload files 16
Generic views – [Link]
from [Link] import models class Author([Link]):
salutation = [Link](max_length=10)
class Publisher([Link]): name = [Link](max_length=200)
name = [Link](max_length=30) email = [Link]()
address = [Link](max_length=50) headshot =
city = [Link](max_length=60) [Link](upload_to='author_headshots'
state_province = )
[Link](max_length=30)
country = [Link](max_length=50) def __str__(self):
website = [Link]() return [Link]
class Meta: class Book([Link]):
ordering = ["-name"] title = [Link](max_length=100)
authors = [Link]('Author')
def __str__(self): publisher = [Link](Publisher,
return [Link] on_delete=[Link])
publication_date = [Link]()
Model Meta is basically used to change the behavior of your model fields like changing
order options,verbose_name, and a lot of other options.
19/03/2025 Django Upload files 17
Generic views – List view
[Link]
from [Link] import ListView
from [Link] import Publisher, Book, Author
class AuthorListView(ListView):
model = Author
context_object_name = 'author_list' # name for the list as a template variable
queryset = [Link]() # List all authors
template_name = 'author_list.html' # Specify your own template name/location
Link your view to urls: [Link]
from [Link] import path
from infogeneric import views
urlpatterns = [
path('authors/', [Link].as_view()),
]
19/03/2025 Django Upload files 18
Generic views – List view - template_list.html
Author_list.html
{% block content %}
<h2>Authors</h2>
<ul>
{% for author in author_list %}
<li>{{ [Link] }}</li>
{% endfor %}
</ul>
{% endblock %}
19/03/2025 Django Upload files 19
Generic views – Detail view
[Link]
from [Link] import ListView, DetailView
from [Link] import Publisher, Book, Author
class AuthorDetailView(DetailView):
model = Author
context_object_name = ‘author_detail'
template_name = ‘author_detail.html‘
Link your view to urls: [Link]
from [Link] import path
from infogeneric import views
urlpatterns = [
path(‘author/<int:pk>', [Link].as_view(),name=‘author_detail'),
]
19/03/2025 Django Upload files 20
Generic views – template_detail.html
author_detail.html
<h1>{{ [Link] }}</h1>
<p>Name: {{ [Link] }}</p>
<p>Email: {{ [Link] }}</p>
19/03/2025 Django Upload files 21
Generic views – Create/Update/Delete
[Link]
from [Link] import CreateView, DeleteView, UpdateView, Deleteview
from [Link] import Publisher, Book, Author
from [Link] import reverse_lazy
class AuthorCreateView(CreateView):
model = Author
fields = ['name', 'email']
template_name = 'author_form.html'
class AuthorUpdateView(UpdateView):
model = Author
fields = ['name', 'email']
template_name = 'author_form.html'
class AuthorDeleteView(DeleteView):
model = Author
template_name = 'author_confirm_delete.html'
success_url = reverse_lazy('author_list')
19/03/2025 Django Upload files 22
Generic views - Create/Update/Delete
[Link]
from [Link] import path
from infogeneric import views
urlpatterns = [
path('author/', [Link].as_view(),name='author_list'),
path('author/<int:pk>', [Link].as_view(),name='author_detail'),
path('author/add/', [Link].as_view(), name='author_add'),
path('author/update/<int:pk>', [Link].as_view(), name='author_update'),
path('author/delete/<int:pk>', [Link].as_view(), name='author_delete'),
]
19/03/2025 Django Upload files 23
Generic views – Create / Update / Delete
author_form.html:
<form method="POST" enctype="multipart/form-data">
<!-- Security token -->
{% csrf_token %}
<!-- Using the formset -->
{{ form.as_p }}
<input type="submit" value="Submit">
</form>
author_confirm_delete.html:
<form method="post">{% csrf_token %}
<p>Are you sure you want to delete "{{ object }}"?</p>
<input type="submit" value="Confirm">
</form>
19/03/2025 Django Upload files 24
19/03/2025 Django Upload files 25
Authentication system
The authentication system consists of:
Users
Permissions: Binary (yes/no) flags designating whether a user may perform
a certain task.
Groups: A generic way of applying labels and permissions to more than one
user.
19/03/2025 Django Upload files 26
Authentication system
Installation, in [Link]:
By default, the required configuration is already included in the [Link] generated
by django-admin startproject, these consist of two items listed in your INSTALLED_APPS
setting:
'[Link]' contains the core of the authentication framework, and its
default models.
'[Link]' is the Django content type system, which allows
permissions to be associated with models you create.
and these items in your MIDDLEWARE setting:
SessionMiddleware manages sessions across requests.
AuthenticationMiddleware associates users with requests using sessions.
With these settings in place, running the command [Link] migrate creates the
necessary database tables for auth related models and permissions for any models
defined in your installed apps.
If Not:
Put '[Link]' and '[Link]' in your
INSTALLED_APPS setting.
Run the command [Link] syncdb.
19/03/2025 Django Upload files 27
Class Users
Class [Link] has fields:
username
first_name
last_name
email
password
is_staff
is_active
is_superuser
last_login
date_joined
19/03/2025 Django Upload files 28
User methods
Creating users: create_user()
>>> from [Link] import User
>>> user = [Link].create_user('john', 'lennon@[Link]', 'johnpassword')
Creating superusers: createsuperuser command:
$ python [Link] createsuperuser --username=joe --email=joe@[Link]
Changing password: set_password()
from [Link] import User
>>> u = [Link](username='john')
>>> u.set_password('new password')
>>> [Link]()
19/03/2025 Django Upload files 29
Login a user
If you have an authenticated user you want to attach to the current session -
this is done with a login() function: login(request, user, backend=None)
When a user logs in, the user’s ID and the backend that was used for
authentication are saved in the user’s session.
from [Link] import authenticate, login
def my_view(request):
username = [Link]['username']
password = [Link]['password']
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
# Redirect to a success page.
else:
# Return an 'invalid login' error message.
...
19/03/2025 Django Upload files 30
Logout a user
To log out a user who has been logged in via [Link](), use
[Link]() within your view. It takes an HttpRequest object
and has no return value.
from [Link] import logout
def logout_view(request):
logout(request)
# Redirect to a success page
19/03/2025 Django Upload files 31
Login required
Limiting access – login_required decorator:
decorators.login_required([redirect_field_name=REDIRECT_FIELD_NAME,l
ogin_url=None])
redirect_field_name by default is = “next”
login_url by defaults is = settings.LOGIN_URL (in [Link])
[Link]
from [Link] import login_required
@login_required(login_url='/accounts/login/')
def my_view(request):
...
[Link]
from [Link] import views as auth_views
path('accounts/login/', auth_views.LoginView.as_view()),
19/03/2025 Django Upload files 32
Ressources
File Uploads:
[Link]
Storage API:
[Link]
Managing Files:
[Link]
Generic Views:
[Link]
views/generic-display/
User authentication in Django:
[Link]
19/03/2025 Django Upload files 33