Answer the question
In order to leave comments, you need to log in
How to fix path when loading image from form in django?
Hello.
Now, when uploading an image through a form, the file has a path like:
sitename.ru/media/media/ex_friend.jpg
I.e. goes twice the way media.
Because of the double path, in the end things like: {{ profileinfo.avatar.url }} - do not work.
In the upload_to model itself - empty
Paths:
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.join(BASE_DIR, "static")
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
STATICFILES_DIRS = (
)
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
avatar = models.ImageField(upload_to='', blank=True, null=True, help_text="Идеальный размер 150 на 150 пикселей",
verbose_name="Аватар юзера")
myself = models.TextField(default='Напишите о себе', help_text="Свободное описание юзера", verbose_name="О себе")
myoffer = models.TextField(default='Напишите о ваших уменениях', help_text="Свободное описание юзера",
verbose_name="Что предлагаю")
# Форму для заполнения профиля
class Profile_Form(forms.Form):
avatar = forms.ImageField(label='Загрузить Аватар', required=False)
myself = forms.CharField(widget=forms.Textarea(attrs={'class': 'course_review_form_width'}), label='О себе',
required=False)
myoffer = forms.CharField(widget=forms.Textarea(attrs={'class': 'course_review_form_width'}), label='Что предлагаю',
required=False)
def update_profile(request, add_id):
token = {}
token.update(csrf(request))
if request.user.is_authenticated():
current_user = request.user
useritem = User.objects.get(id=current_user.id)
try:
if useritem.profile is not None:
if request.POST:
form = Profile_Form(request.POST or None, request.FILES or None)
if form.is_valid():
if form.cleaned_data['avatar']:
avatar = form.cleaned_data['avatar']
#Берем изображение из ввода в форму, и с помощью easy_thumbnails - кропим его еще до сохранения в базу
options = {'size': (200, 200), 'crop': True}
thumb_url = get_thumbnailer(avatar, relative_name=str(current_user.id)).get_thumbnail(options).url
useritem.profile.avatar = thumb_url
useritem.profile.save(update_fields=['avatar'])
if form.cleaned_data['myself']:
myself = form.cleaned_data['myself']
useritem.profile.myself = myself
useritem.profile.save(update_fields=['myself'])
if form.cleaned_data['myoffer']:
myoffer = form.cleaned_data['myoffer']
useritem.profile.myoffer = myoffer
useritem.profile.save(update_fields=['myoffer'])
return profile(request, current_user.id)
else:
return redirect('/', token)
else:
return redirect('/', token)
else:
return redirect('/', token)
Answer the question
In order to leave comments, you need to log in
Generally. There is such a setting:
THUMBNAIL_MEDIA_URL = '' - by default it gives the same path as the media root. And if we cut the photo at the upload stage, then the process is going on:
We take the photo from the form + add
the roots We cut the photo into the shortcut + add the roots
As a result, there is a double media root.
If you put like this THUMBNAIL_MEDIA_URL = '/' - then the root is not set a second time, and everything is ok.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question