C
C
cyberic-icus2020-04-07 14:38:07
Django
cyberic-icus, 2020-04-07 14:38:07

Images not loading in Django?

Good day, the other day I encountered such a problem: images stopped being transmitted through forms. I have two applications that use ImageField - CustomUser and UserGroup, both extensions of existing Django models (see code below).

As soon as I noticed the problem, I decided to roll back to the moment when everything worked (in this version I only have the CustomUser model), but ... here they stopped being transmitted, although everything should work. Created a new environment, did not help. I searched on the Internet - I added an attribute to the form enctype="multipart/form-data"(before and without it, everything worked fine). It seems to work, however, as for me, this is a so-so solution.

Ask for advice from knowledgeable people.

# models.py

from django.db import models
from django.urls import reverse
from django.contrib.auth.models import AbstractUser

class CustomUser(AbstractUser):
  photo = models.ImageField(upload_to='profile_pics/', defaul='default.jpg')
  
  def __str__(self):
    return self.username
  
  def get_absolute_url(self):
    return reverse('users:users-single', kwargs={'username':self.username})

# =============================================
# forms.py

from django import forms
from django.contrib.auth.forms import UserCreationForm, UserChangeForm

from django.contrib.auth import get_user_model
User = get_user_model()

class CustomUserCreationForm(UserCreationForm):
  class Meta:
    model = User
    fields = (
      'username', 
      'email', 
      'first_name', 
      'last_name', 
      'photo')
    
class CustomUserChangeForm(UserChangeForm):
  password = None
  class Meta:
    model = User
    fields = ('photo',)

# =============================================
# views.py 

class UserRegisterView(CreateView):
  form_class = CustomUserCreationForm
  template_name = 'users/register.html'
  success_url = 'users/login/'
  
  def form_valid(self, form):
    if self.request.recaptcha_is_valid:
      form.save()
      return super().form_valid(form)

class UserUpdateView(UserPassesTestMixin, LoginRequiredMixin, UpdateView):
  fields = ['email', 'first_name', 'last_name', 'photo']
  template_name = 'users/update.html'
  
  def get_success_url(self):
    username_ = self.request.user.username
    return reverse_lazy('users:users-single', kwargs={'username':username_})
  
  def get_object(self):
    username_ = self.kwargs.get('username')
    return get_object_or_404(CustomUser, username=username_)
  
  def test_func(self):
    post = self.get_object()
    if self.request.user.username == self.kwargs.get('username'):
      return True
    return False

# =============================================
# urls.py 

urlpatterns =[ 
...
] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT).

# =============================================
# settings.py

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

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Deleting Account, 2020-04-07
@cyberic-icus

What confused you about enctype="multipart/form-data"? This is the only correct solution as far as I know. Without this attribute, files will not be transferred at all!
So the answer to the question is simple: use the enctype="multipart/form-data" attribute on the form!

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question