1

I am trying to give my users ability to upload profile pictures to their account. The problem is I am using Django user model, so I don't have my own model where I can add image = models.ImageField()

This is my forms.py

from django import forms
from django.contrib.auth import authenticate, get_user_model,


class UserRegisterForm(forms.ModelForm):
    confirm_email = forms.EmailField()
    password = forms.CharField(widget=forms.PasswordInput)
    confirm_password = forms.CharField(widget=forms.PasswordInput)
    image = forms.ImageField(required=False)

    class Meta:
        model = User
        fields = ['email','confirm_email','username','password']

    def clean_confirm_email(self):
        email = self.cleaned_data.get("email")
        confirm_email = self.cleaned_data.get("confirm_email")
        if email != confirm_email:
            raise forms.ValidationError("Emails do not match")

        email_qs = User.objects.filter(email=email)
        if email_qs.exists():
            raise forms.ValidationError("Email already used")
        return email

    def clean_confirm_password(self):
        password = self.cleaned_data.get("password")
        confirm_password = self.cleaned_data.get("confirm_password")
        if password != confirm_password:
            raise forms.ValidationError("Passwords do not match")

        return password

in my registration page the image button is being displayed, Tho I have no idea how to save the image and link it to the user.

this is my views.py

from django.shortcuts import render, redirect
from django.contrib.auth import (authenticate, get_user_model, login, logout)
from .forms import UserLoginForm, UserRegisterForm

# Create your views here.


def login_view(request):
    login_form = UserLoginForm(request.POST or None)
    if login_form.is_valid():
        username = login_form.cleaned_data.get("username")
        password = login_form.cleaned_data.get("password")
        user = authenticate(username=username,password=password)
        login(request, user)
        return redirect('/')
    context = {
        "login_form": login_form
    }
    return render(request, 'login.html', context)


def register_view(request):
    form = UserRegisterForm(request.POST or None)
    if form.is_valid():
        user = form.save(commit=False)
        password = form.cleaned_data.get("password")
        user.set_password(password)
        user.save()
        new_user = authenticate(username=user.username,password=password)
        login(request, new_user)
        return redirect('/')
    context = {
        'form': form,

    }
    return render(request, 'signup.html', context)


def logout_view(request):
    logout(request)
    return redirect('/')

So as u can see I am using Django User Model, so my models.py and admin.py is empty.

Most of the solutions they were about having my own Model.

aamurad
  • 25
  • 1
  • 7

2 Answers2

1

So for those who might see this later, This is how I solved it.

I created a UserProfile model and linked it with User from

from django.contrib.auth.models import User

using models.OneToOneField(User)

from django.db import models
from django.contrib.auth.models import User 

# Create your models here.


class UserProfile(models.Model):
    user = models.OneToOneField(User)
    avatar = models.ImageField() # or whatever

    def __str__(self):
        return self.user.email

then configuring my url.py with the correct url codes

if settings.DEBUG:
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

and my setting.py

STATIC_URL = '/static/'
MEDIA_URL = '/media/'

STATICFILES_DIRS = (
  os.path.join(BASE_DIR, 'static/'),
)

MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')

admin.py

from django.contrib import admin
from .models import UserProfile
# Register your models here.

admin.site.register(UserProfile)

I was able to use upload images from the admin panel and displaying them in my template using <img src="{{ user.userprofile.avatar.url }}">

I hope I was clear enough, and that I could be of help to someone else :)

aamurad
  • 25
  • 1
  • 7
0

You need to extend User model as Profile . Use below link exame for extend this. Add image/avatar to users in django

Neeraj Kumar
  • 3,851
  • 2
  • 19
  • 41
  • Thank you very much I tried one of the answers provided and with little of research I was able to do it :) – aamurad Jun 17 '17 at 17:34