Reputation: 8897
i have a problem with django. I need to display my files in single page
So i create model:
class UserProfile(models.Model):
profile_img = models.ImageField(upload_to='media/images/', blank=True, null=True)
profile_text = models.TextField()
profile_title = models.CharField(max_length=300)
profile_user = models.ForeignKey(User)
and form
class ProfileForm(ModelForm):
class Meta:
model = UserProfile
fields = ['profile_img', 'profile_title']
then 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})
I try use view
def user_page(request):
profile = UserProfile.objects.all()
return render(request, 'user_page.html', {'profile':profile})
and
{% for img in profile %}
{{ img.profile_img }}
{% endfor %}
it is not work Help me plz, i try to read documentation but it doesn't help
Upvotes: 5
Views: 6912
Reputation: 8897
I did it, as you said. Image doesn't display. I inspect element in browser: it should work my settings:
MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
And i have 2 urls, main file for my project:
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^/cabinet', include('comments.urls') ),
url(r'^', include('user_login.urls')),]
and for my app:
urlpatterns = [
url(r'^$', views.cabinet, name='cabinet' ),
url(r'^/user_page/$', views.user_page, name='user_page'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Upvotes: 1
Reputation: 121
Please correct this line
MEDIA_URL = '/media/' MIDIA_ROOT = os.path.join(BASE_DIR, 'media')
to
MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
it should be MEDIA not MIDIA
Upvotes: 0
Reputation: 1
I had the same problem, and i just def a str for my pic field to return the self.pic.url in the model itself, and in the template i just used {{pic}}.
Upvotes: 0
Reputation: 3940
So the code you pasted will only print path to your each profile.profile_img
. And so is the profile_img
attribute, it only stores a path to the image you uploaded, not the image itself. In order to use the media files uploaded to your website you need to specify a MEDIA_ROOT
and MEDIA_URL
in your settings.py
.
Then you need to append it to your urls.py
. You might want to look here also: show images in Django templates
After you have done so, to display an image in template just use HTML
tag
<img src="{{MEDIA_URL}}{{ img.profile_img }}" />
Upvotes: 2