上传图片并在模板上显示 - Django 2.0

时间:2018-05-20 03:49:03

标签: python django jinja2

我的模板上有这个代码:

{% extends "base.html" %}
{% block content %}
<div style="padding:40px;margin:40px;border:1px solid #ccc">
    <h1>picture</h1>
    <form action="" method="post" enctype="multipart/form-data"> <!--{% url 'imageupload' %}-->
        {% csrf_token %} {{form}} 
        <input type="submit" value="Upload" />
    </form>
{% for img in images %}
    {{forloop.counter}}.<a href="{{ img.pic.url }}">{{ img.pic.name }}</a>
    ({{img.upload_date}})<hr />
{% endfor %}
</div>
{% endblock content %}

虽然我对form action有疑问,但无论如何。

问题是当我点击submit按钮时,它会将我带到一个空白页面,没有实际上传图像的弹出窗口,没有。

我应该遵循一些例子来实现这个目标吗?

此外,这只是一个验证测试,但我想知道它是否真的需要一个模型和/或表单?

修改

好的,通过修改此input这样的<input type="file" name='input_name' />行,它实际上会打开文件弹出窗口,但显然它不会上传任何内容,它需要像submit一样按钮或其他东西,所以,现在它看起来像这样:

{% extends "base.html" %}
{% block content %}
<div style="padding:40px;margin:40px;border:1px solid #ccc">
    <h1>picture</h1>
    <form action="" method="post" enctype="multipart/form-data"> <!--{% url 'imageupload' %} -->
        {% csrf_token %} {{form}} 
        <input type="file" name='input_name' />
        <input type="submit" value="Upload" />
    </form>
{% for img in images %}
    {{forloop.counter}}.<a href="{{ img.pic.url }}">{{ img.pic.name }}</a>
    ({{img.upload_date}})<hr />
{% endfor %}

   {%endblock content%}

但是当我点击提交时,它会一直向我发送一个空白页面,因此,提交时的值Upload来自此模型:

from django.db import models
from django.forms import ModelForm

class Upload(models.Model):
    pic = models.FileField(upload_to="static/")    
    upload_date=models.DateTimeField(auto_now_add =True)

class UploadForm(ModelForm):
    class Meta:
        model = Upload
        fields = ('pic',)

在我的views.py上:

from django.shortcuts import render
from uploader.models import UploadForm,Upload
from django.http import HttpResponseRedirect
from django.urls import reverse

def home(request):
    if request.method=="POST":
        img = UploadForm(request.POST, request.FILES)       
        if img.is_valid():
            img.save()  
            return HttpResponseRedirect(reverse('imageupload'))
    else:
        img=UploadForm()
    images=Upload.objects.all()
    return render(request,'image_upload.html',{'form':img,'images':images})

在我的urls.py中:

from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.views.generic import TemplateView
from django.views import defaults as default_views
from uploader import views as uploader_views

urlpatterns = [...
    some patterns...
    url(r'^image_upload/', uploader_views.home, name='imageupload'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

0 个答案:

没有答案