繁体   English   中英

django上传图片并显示该图片

[英]django upload image and show that image

我有一个问题,这是我的代码
上传图片成功后,将返回所有数据( item=Item.objects.all() )并显示在模板上
如果我只希望用户上传的图片显示在模板上(而不是数据库中的所有图像),该怎么办?
请指导我!
非常感谢你。

views.py

def background(request):
    if request.method=="POST":
        img = ItemForm(request.POST, request.FILES)
        if img.is_valid():
            img.save()
            return HttpResponseRedirect(reverse('imageupload:background'))    
        img=ItemForm()
    item=Item.objects.all()
    return render(request,'uploader/background.html',{'form':img,'item':item,})

models.py

from sorl.thumbnail import ImageField
class Item(models.Model):
    image = ImageField(upload_to='thumb/')
class ItemForm(forms.ModelForm):
    class Meta:
        model = Item

模板:

<form action="#" method="post" enctype="multipart/form-data">
{% csrf_token %}
    {{form}} <input type="submit" value="Upload" />
</form>

{% for i in item%} 
    {{i.image}}
        {% thumbnail i.image "1024" crop="center" format="PNG"  as im %}
            <img src="{{ im.url }}" width="{{ im.width }}" height="{{ im.height }}">
        {% endthumbnail %}
{% endfor %}    

保存时,您可以在那里找到ID。 只需在会话中设置ID。 因此, redirecting您可以拥有该photouser的ID,例如...

photoId = request.session['photoId']
userId = request.session['_auth_user_id']
item=Item.objects.get(pk=photoId) #you can also use filter by userId

码:

if img.is_valid():
    img.save()
    request.session['photoId'] = img.id
    return HttpResponseRedirect(reverse('imageupload:background')) 

如果您添加一个可用于跟踪最新上传的图片的字段,那就更好了。

class Item(models.Model):
    image = ImageField(upload_to='thumb/')
    upload_time = models.DateTimeField(auto_now=False, auto_now_add=True)

在这里,我添加了另外一个名为auto_now_add=True. upload_time auto_now_add=True.

DateField.auto_now_add

Automatically set the field to now when the object is first created. 
Useful for creation of timestamps. Note that the current date is always used; 
it’s not just a default value that you can override.

之后,您可以使用latest方法从Item模型中获取最新对象。

def background(request):
    if request.method=="POST":
        img = ItemForm(request.POST, request.FILES)
        if img.is_valid():
            img.save()
            return HttpResponseRedirect(reverse('imageupload:background'))    
    img=ItemForm()
    item=Item.objects.latest('upload_time')
    return render(request,'uploader/background.html',{'form':img,'item':item,})

关于最新:

latest(field_name=None)
Returns the latest object in the table, by date, using the field_name provided as the date field.

因此,您将获得单个对象,则不需要在模板中对其进行迭代。

{{item.image}}
{% thumbnail item.image "1024" crop="center" format="PNG"  as im %}
    <img src="{{ im.url }}" width="{{ im.width }}" height="{{ im.height }}">
{% endthumbnail %}

您不必使用会话并重定向或添加任何其他字段。 ModelForm save()方法返回刚刚保存的对象。 尝试这个:

# views.py
def background(request):
    form = ItemForm(request.POST or None, request.FILES or None)
    item = None
    if request.method=="POST" and form.is_valid():    
        item = form.save()
    return render(request,'uploader/background.html',{'form': form,'item': item,})


# template
<form action="#" method="post" enctype="multipart/form-data">
{% csrf_token %}
    {{form}} <input type="submit" value="Upload" />
</form>

{% if item %} 
    {{ item.image }}
        {% thumbnail item.image "1024" crop="center" format="PNG"  as im %}
            <img src="{{ im.url }}" width="{{ im.width }}" height="{{ im.height }}">
        {% endthumbnail %}
{% endif %}  

我做了些不同的事情。 我的视图每次都动态地绘制一个图形(图像),因此它不在数据库中。 但是要在我的模型中嵌入图的单个实例,这就是我所做的:

首先,我创建了一个视图,该视图从数据中渲染图形,并创建了一个指向该图形的URL(使用其ID选择):

    url(r'^graphs/graphImage/(?P<graph_id>\d+?)/$', 'hydro.views.render_graph', name='graphImage'),

无需显示我的视图,但是如果我转到该URL,则将调用我的视图,它将显示图形并且仅显示图形。 与大多数网站类似,如果您单击图片,只会得到一个仅显示图片的网页。

现在使用此网址:

    url(r'^graphs/(?P<graph_id>\d+?)/$', 'hydro.views.single_graph', name='graph_detail'),

该视图为这个坏男孩带来了一个模板:

   {% url 'graphImage' graph.id as the_graph %}
        <img src="{{the_graph}}" alt="{{the_graph}}"/>

网址部分抓取了我的graphImage网址,并输入了graph.id。 然后我将其命名为the_graph,以使其简单。

然后我做一个图像标签作为_graph的src。 不用担心alt,如果调试不起作用,它只会显示url。

因此,我要做的是在一个网页上绘制图形,然后将其用作图像标签的来源。 有上百万种方法可以做这种事情,但这是我最有限的技能,并且只了解html和django是最明显的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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