DEV Community

Phansivang
Phansivang

Posted on

Django User Profile Image

Models.py

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

class profile(models.Model):
    image = models.ImageField(default='default.jpg', upload_to='profile_pics')
    user = models.OneToOneField(User, on_delete=models.CASCADE)

    def save(self, *args, **kwargs):
        super(profile, self).save(*args, **kwargs)

        img = Image.open(self.image.path)

        if img.height > 300 or img.width > 300:
            output_size = (150, 150)
            img.thumbnail(output_size)
            img.save(self.image.path)
Enter fullscreen mode Exit fullscreen mode

Forms.py

from .models import profile
from django import forms
class updateProfile(forms.ModelForm):

    class Meta:
        model = profile
        fields = ['image']
Enter fullscreen mode Exit fullscreen mode

Views.py

from .forms import updateProfile
def profilePage(request):
    if request.method == 'POST':
        form = updateProfile(request.POST, request.FILES, instance=request.user.profile)
        if form.is_valid():
            print('ok')
            form.save()
            return redirect('profile')
    else:
        form =  updateProfile()
        context = {'form':form}
    return render(request, 'app/profile.html',context)
Enter fullscreen mode Exit fullscreen mode

profile.html

<form method="POST" enctype="multipart/form-data">
          {% csrf_token %}
          <fieldset class="form-group">
              <legend class="border-bottom mb-4">Profile Info</legend>
              {{ form }}
          </fieldset>
          <div class="form-group">
              <button class="btn btn-outline-info" type="submit">Update</button>
          </div>
      </form>
Enter fullscreen mode Exit fullscreen mode

Urls.py

urlpatterns = [
    path('profile/',views.profilePage,name='profile'),
]
Enter fullscreen mode Exit fullscreen mode

Create Signals.py

from django.db.models.signals import post_save
from django.contrib.auth.models import User
from django.dispatch import receiver
from .models import profile
from django.core.exceptions import ObjectDoesNotExist

@receiver(post_save, sender=User)
def create_profile(sender, instance, created, **kwargs):
    if created:
        profile.objects.create(user=instance)


@receiver(post_save, sender=User)
def save_profile(sender, instance, **kwargs):
    try:
        instance.profile.save()
    except ObjectDoesNotExist:
        profile.objects.create(user=instance)
Enter fullscreen mode Exit fullscreen mode

Apps.py

from django.apps import AppConfig


class UsersConfig(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'app'

    def ready(self):
        import app.signals
Enter fullscreen mode Exit fullscreen mode

Urls.py in main project

from django.conf import settings
from django.conf.urls.static import static


urlpatterns = [
    path('admin/', admin.site.urls),
    path('',include('app.urls')),

]

if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Enter fullscreen mode Exit fullscreen mode

Setting.py

import os 

MEDIA_ROOT = os.path.join(BASE_DIR,'media')
MEDIA_URL = '/media/'
Enter fullscreen mode Exit fullscreen mode

Make migrations

> Python manage.py makemigrations
> Python manage.py migrate
Enter fullscreen mode Exit fullscreen mode

Enjoy with 100% work well

Top comments (0)