Answer the question
In order to leave comments, you need to log in
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')
'django.core.context_processors.media'
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)
class ProfileForm(ModelForm):
class Meta:
model = UserProfile
fields = ['profile_img', 'profile_title']
#Загрузка изображений
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})
{% for img in profile %}
<img src="{{MEDIA_URL}}{{ img.profile_img }}" />
{% endfor %}
<img src="/media/images/3N7QtulTgx0.jpg">
Answer the question
In order to leave comments, you need to log in
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
<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})
{% for img in profile %}
<img src="{{MEDIA_URL}}{{ img.profile_img }}" />
{% endfor %}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question