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 avatar field to the profile model using ImageField and define an upload path.
  • A model form is created for the avatar field to handle uploads easily.
  • In the view, we pass request.FILES to 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.
Never miss a story on Django.wiki

Subscribe for fresh tutorials, snippets, and updates.

By subscribing you agree to our Privacy Policy.