无法使用django显示图像

时间:2018-03-31 19:14:04

标签: python django image-upload

我是使用django的新手。在我的应用程序中,我正在上传存储在媒体文件夹中的图像。现在,我正在尝试提供下载无法正常工作的图像的链接。我也尝试直接显示图像(使用html中的img),这也不起作用。

我的代码如下:

urls.py

from django.conf.urls import url
from . import views
from django.conf import settings
from django.conf.urls.static import static


app_name = 'workers'

urlpatterns = [
url(r'^$', views.index, name= 'index'),
url(r'^enrollment$',views.enroll, name='enroll'),
url(r'^save_enrollment$',views.save_enrollment, name='save_enrollment'),

]

if settings.DEBUG:
urlpatterns = urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

forms.py

from django import forms
from django.forms import ModelForm
from .models import Worker

class Worker_enrollment(forms.ModelForm):
    name = forms.CharField(max_length=250)
    address = forms.CharField(max_length=500)
    phone_number = forms.CharField(max_length=100)
    designation = forms.CharField(max_length=1000)
    docfile = forms.FileField(label='select an image to upload')
    ssn = forms.CharField(max_length=200)

    class Meta:
        model = Worker
        fields = ['name','address','phone_number','designation','docfile','ssn']

models.py: -

from django.db import models

class Worker(models.Model):
    name = models.CharField(max_length=250)
    address = models.CharField(max_length=500)
    phone_number = models.CharField(max_length=100)
    designation = models.CharField(max_length=1000)
    docfile = models.ImageField(upload_to='documents/')
    ssn = models.CharField(max_length=200)
    def __str__(self):
        return (self.name)

views.py: -

from .models import  Worker
from .forms import Worker_enrollment
from django.shortcuts import render, get_object_or_404
from django.conf import settings

def index(request):
    workers_info = Worker.objects.all()
    context = {
    'workers':workers_info
}
return render(request, 'workers/index.html', context)

def enroll(request):
    form = Worker_enrollment(request.POST)
    if form.is_valid():
        return render(request, 'workers/enroll.html', {'form': form})
    else:
        form = Worker_enrollment()
    return render(request, 'workers/enroll.html', {'form': form})

def save_enrollment(request):
    worker_info = Worker()
    if request.method == 'POST':
        form = Worker_enrollment(request.POST,request.FILES)
        if form.is_valid():
            worker_info.name = form.cleaned_data['name']
            worker_info.address = form.cleaned_data['address']
            worker_info.designation = form.cleaned_data['designation']
            worker_info.phone_number = form.cleaned_data['phone_no']
            worker_info.ssn = form.cleaned_data['ssn']
            worker_info.docfile = request.FILES['docfile']
            worker_info.save()
            return render(request,'workers/saves_worker.html',{'worker_info':worker_info})
    else:
        form = Worker_enrollment()
    return render(request, 'workers/saves_worker.html', {'worker_info': worker_info})

enroll.html: -

<form action="save_enrollment" method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_ul }}
<input type="submit" value="Submit" />
</form>

saves_worker.html: -

<h1>Worker has been enrolled</h1>
<br>
<h2>Name - {{worker_info.name}}</h2><br>
<h2>PhoneNo - {{worker_info.phone_number}}</h2><br>
<h2>Designtion - {{worker_info.designation}}</h2><br>
<h2>SSN - {{worker_info.ssn}}</h2>
<h2>Address - {{worker_info.address}}</h2>
<h2><a href="{{ worker_info.docfile.url }}" >worker's image</h2>

settings.py文件中指定了以下内容: -

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
STATIC_URL = '/static/'
STATICFILES_DIRS = (os.path.join(BASE_DIR, "static"),)

3 个答案:

答案 0 :(得分:0)

您确定save_enrollment函数将图像保存在worker_info的docfile字段中。尝试使用:

def save_enrollment(request):
    if request.method == 'POST':
        form = Worker_enrollment(request.POST,request.FILES)
        if form.is_valid():
            worker_info = form.save()
            return render(request,'workers/saves_worker.html',{'worker_info':worker_info})
    else:
        form = Worker_enrollment()
    return render(request, 'workers/saves_worker.html', {'worker_info': worker_info}

答案 1 :(得分:0)

您不需要在模型中再次定义字段。您还在表单中使用FileField而不是ImageField。如果要在表单中添加额外字段,则需要在__init__()表单方法中添加这些字段。 请尝试以下操作:

class Worker_enrollment(forms.ModelForm):

    class Meta:
        model = Worker
        fields = ['name','address','phone_number','designation','docfile','ssn']

额外提示:不要将CharFieldmax_length=1000一起使用。 CharField最多应使用255个字符。如果您需要更长的时间,请使用TextField。您还需要安装Pillow库才能使图像可见。

答案 2 :(得分:-1)

我刚刚通过更改MEDIA_URL解决了我的问题:

MEDIA_URL = 'shield/media/'

我的项目名称是盾牌。