Django sends me the following error: ValueError at / The 'avatar' attribute has no file associated with it.
The message appears just after I log in, even though I uploaded an avatar when I registered a dummy profile.
I can't even find the avatar in the configured path: media/avatars.
Could you help find where I got this wrong please? Bellow is my code.
**models.py: **
from django.db import models
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
(some code)
avatar = models.ImageField(upload_to='avatars/',blank=True, null=True)
**forms.py: **
class RegisterForm(UserCreationForm):
(some code)
avatar = forms.ImageField(
required=False,
widget=forms.ClearableFileInput(
attrs={
"class": "form-control"
}
)
)
class Meta:
model = User
fields = ['username','first_name','last_name','email','avatar','password1','password2','user_type']
**settings.py: **
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_DIR = BASE_DIR / 'media'
STATIC_ROOT = BASE_DIR / 'staticfiles'
MEDIA_ROOT = BASE_DIR / 'media'
I added this in urls.py of the main project directory:
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
And finally, the path of where I want the avatars to be uploaded:
mainProject ├── media │ ├── avatars
Thank you very much for any help
I tried to make all the uploaded avatars go to media/avatars.
I even made conditions where there is a placeholder image in case the user doesn't upload any avatar:
{% if user.avatar %}
<img src="{{ user.avatar.url }}">
{% else %}
<img src="{% static 'images/cat.png' %}">
{% endif %}
There is indeed a 'cat.png' image in static/images/
hope you haven't forgotton to apply makemigration and migrate! do you have github repo of it, i want to have a through look at before commenting.