简体   繁体   中英

display uploaded files django

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

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 }}" />

I did it, as you said. Image doesn't display. I inspect element in browser: it should work my settings:

MEDIA_URL = '/media/' MIDIA_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)

我遇到了同样的问题,我只是为我的pic字段定义一个str来返回模型本身的self.pic.url,并在我刚刚使用{{pic}}的模板中。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM