Django has the built-in form called UserCreatioonForm for creating users. It has some fields like First and Last Name, Email, etc. But is it actually possible to have a field for uploading images which will be used as profile pictures for the user?
I tried to read about additional input fields on djangoproject.com/docs, but it was rather cryptic.
No, Django does not have a field for profile pictures. What you will do is you create a model that has a one to one relation with the User model and then you can use the image to you saved in that model.
from django.contrib.auth.models import User
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
avatar = models.ImageField(upload_to='profile_pics', null=True,
blank=True)
def __str__(self):
return self.user.username
from .models import Profile
from django.shortcuts import render, get_object_or_404
def upload_avatar(request):
profile = get_object_or_404(Profile, user=request.user)
if request.method == 'POST':
profile.avatar = request.FILES.get('avatar')
profile.save()
return redirect(request.META.get('HTTP_REFERER'))
{% if request.user.profile.avatar %}
<img src="{{ request.user.profile.avatar.url }}" alt=" avatar-picture">
{% endif %}