B
B
baterson2015-08-16 12:32:35
Django
baterson, 2015-08-16 12:32:35

How to display uploaded images in django?

Hi guys, I can't figure out how files work. I want to implement loading an image from the user and displaying images on another
settings page:

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

added to settings.TEMPLATES.context_processors
'django.core.context_processors.media'
Created a model:
class UserProfile(models.Model):

  profile_img = models.ImageField(upload_to='images/', blank=True, null=True)
  profile_text = models.TextField()
  profile_title = models.CharField(max_length=300)
  profile_user = models.ForeignKey(User)

Shape:
class ProfileForm(ModelForm):
  class Meta:
    model = UserProfile
    fields = ['profile_img', 'profile_title']

View:
#Загрузка изображений
def cabinet(request):
  form = ProfileForm(request.POST, request.FILES or None)
  if request.method == 'POST' and form.is_valid():
    obj = UserProfile(profile_img=request.FILES['profile_img'])
    obj = form.save(commit=False)
    obj.profile_user = request.user
    obj.save()
    return redirect(reverse(cabinet))
  return render(request, 'cabinet.html', {'form': form})
#Вывод изображений
def user_page(request):
  profile = UserProfile.objects.all()
  return render(request, 'user_page.html', {'profile':profile})

And the template:
{% for img in profile %}
<img src="{{MEDIA_URL}}{{ img.profile_img }}" />
{% endfor %}

As a result, the images are not loaded, although the link is correct in the browser, please help me figure it out
<img src="/media/images/3N7QtulTgx0.jpg">

Answer the question

In order to leave comments, you need to log in

3 answer(s)
B
baterson, 2015-08-16
@baterson

I managed to solve, the problem was in the url
it was necessary to add this to the main file, and not to the application url

S
sim3x, 2015-08-16
@sim3x

<img src="{{ profile_img.url }}">
what the hell is happening in this view?

def user_page(request):
  profile = UserProfile.objects.all()
  return render(request, 'user_page.html', {'profile':profile})

why show usernames of all users in the profile?
{% for img in profile %}
<img src="{{MEDIA_URL}}{{ img.profile_img }}" />
{% endfor %}

Z
zelsky, 2015-08-16
@zelsky

Paste without {{MEDIA_URL}}

{% for img in profile %}
<img src="{{ img.profile_img }}" />
{% endfor %}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question