User Avatar Upload
A snippet to add profile picture upload functionality for Django users.
# models.py
from django.db import models
from django.contrib.auth.models import User
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
avatar = models.ImageField(upload_to='avatars/', blank=True, null=True)
def __str__(self):
return self.user.username
# forms.py
from django import forms
from .models import Profile
class AvatarForm(forms.ModelForm):
class Meta:
model = Profile
fields = ['avatar']
# views.py
from django.shortcuts import render, redirect
from .forms import AvatarForm
def avatar_upload_view(request):
profile = request.user.profile
form = AvatarForm(request.POST or None, request.FILES or None, instance=profile)
if form.is_valid():
form.save()
return redirect('profile')
return render(request, 'avatar_upload.html', {'form': form})
# templates/avatar_upload.html
<h2>Upload Avatar</h2>
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Upload</button>
</form>
Explanation:
-
We add an
avatarfield to the profile model usingImageFieldand define an upload path. - A model form is created for the avatar field to handle uploads easily.
-
In the view, we pass
request.FILESto handle image uploads. -
The form requires
enctype="multipart/form-data"to send image data. - After upload, users are redirected to their profile page or dashboard.
- Category Authentication & Authorization
- Total Views 527
- Last Modified 11 November, 2025
- Tags #profile #image upload #auth #forms
Previous snippet
Custom User Model with Email as Username
Next snippet