我是Django的新手。我需要帮助。我想显示图像。在这里,我将图像路径保存到数据库,将图像保存到文件夹。请帮助我显示这些图像。
views.py :
def uploadfile(request):
print('inside upload logic')
if request.method == 'POST':
form = FileUploadForm(request.POST, request.FILES)
if form.is_valid():
# ImageUpload(request.FILES['File_Name'])
myfile = request.FILES['File_Name']
fs = FileSystemStorage()
filename = fs.save(myfile.name, myfile)
uploaded_file_url = fs.url(filename)
newdoc = FileUpload(File_Name=myfile.name, File_path=uploaded_file_url, Description=request.POST['Description'])
newdoc.save()
#return HttpResponse("File uploaded successfuly")
return render(request, 'Login/fileupload.html')
else:
form = FileUploadForm()
return render(request, 'Login/fileupload.html', {
'form': form
})
def dataretrive(request):
newdoc=FileUpload.objects.all()
return render(request,'Login/displayimage.html',{'FileUpload':FileUpload})
我的模型:
class FileUpload(models.Model):
File_Name = models.CharField(max_length=255, blank=True)
File_path = models.FileField(upload_to='')
Description = models.CharField(max_length=255, blank=True)
Upload_Date = models.DateTimeField(auto_now_add=True)
答案 0 :(得分:0)
将此添加到您的模型中:
class FileUpload(models.Model):
File_Name = models.CharField(max_length=255, blank=True)
File_path = models.FileField(upload_to='')
Description = models.CharField(max_length=255, blank=True)
Image = models.ImageField(upload_to=upload_location)
Upload_Date = models.DateTimeField(auto_now_add=True)
def upload_location(instance, filename):
filebase, extension = filename.split(".")
return "%s/%s" % (instance.id, filename)
在您的settings.py文件中,请确保设置MEDIA_URL和MEDIA_ROOT:
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
要访问模板中的MEDIA_URL,必须将django.template.context_processors.media添加到TEMPLATES配置中的context_processeors中。
将此添加到您的模板:
{% if instance.image %}
<img src="{{ instance.image.url }}" class='img-responsive' />
{% endif %}