我在Django中显示用户图像时遇到了麻烦,似乎主要是工作。当用户提交图片时,它已成功存储它 在右侧文件夹中。但是在我保存后我无法显示图片。
Views.py:
def upload_pic(request):
user = User.objects.get(id=request.user.id)
form = ImageUploadForm(request.POST, request.FILES)
if request.method == 'POST':
if form.is_valid():
form.save()
return render(request, 'tracker/upload_pic.html')
def album(request):
user = User.objects.get(id=request.user.id)
if request.method == "POST":
user.extendedprofile.img = request.FILES['uploaded_image']
user.extendedprofile.save()
#ExtendedProfile.objects.filter(pk=request.user.id).update(extendedprofile__img=request.FILES['uploaded_image'])
return render(request, 'tracker/album.html', {"user": user})
settings.py(相关部分)
STATIC_URL = '/static/'
STATIC_ROOT = '/viraone/tracker/static'
MEDIA_URL = '/tracker/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'tracker/')
models.py
def user_directory_path(instance, filename):
return 'user_images/user_{0}/{1}'.format(instance.user.id, filename)
class ExtendedProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
amount_spent = models.DecimalField(max_digits=6, decimal_places=2, default=0, blank=True)
img = models.ImageField(upload_to=user_directory_path)
forms.py
class ImageUploadForm(forms.ModelForm):
#model to store the information about the pictures
class Meta:
model = ExtendedProfile
exclude = ()
urls.py
from django.conf.urls import url
from . import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [url(r'^profile', views.profile, name='profile'),
url(r'^login', views.login, name='login'),
url(r'^export_info', views.export_info, name='export_info'),
url(r'^product_page', views.product_page, name='product_page'),
url(r'^(?P<object_id>[0-9]+)/$', views.product_details, name='product_details'),
url(r'^upload_pic', views.upload_pic, name='upload_pic'),
url(r'^album', views.album, name='album'),
]
if settings.DEBUG:
urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
模板:
{% load staticfiles %}
<!DOCTYPE html>
<html>
<p> {{ user.extendedprofile.img }} </p>
<img src="{{ user.extendedprofile.img.url }}"
</html>
我认为这是urls.py
的问题,在调试菜单中,它显示正确文件路径的404
错误,但图像没有出现。
答案 0 :(得分:2)
在urls.py
if settings.DEBUG:
urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
到
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
并在模板中
<img src="{{ user.extendedprofile.img.url }}">