简体   繁体   English

django上传图片并显示该图片

[英]django upload image and show that image

I have a question,this is my code 我有一个问题,这是我的代码
When uploade image success,It will return all data ( item=Item.objects.all() ) and show on the template 上传图片成功后,将返回所有数据( item=Item.objects.all() )并显示在模板上
What if I only want the picture which is just uploaded by user to show on template(not all images in database),how can I do this? 如果我只希望用户上传的图片显示在模板上(而不是数据库中的所有图像),该怎么办?
Please guide me ! 请指导我!
Thank you very much. 非常感谢你。

views.py 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 models.py

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

templates: 模板:

<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 %}    

You can have the id there when save. 保存时,您可以在那里找到ID。 Just set the id in session. 只需在会话中设置ID。 So when redirecting you can have the id of that photo & user also like ... 因此, 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

Code: 码:

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

It would be better if you add a field that can be used to keep track of your latest uploaded Image. 如果您添加一个可用于跟踪最新上传的图片的字段,那就更好了。

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

Here I have added one more feild named upload_time with parameter 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.

After that you can get the latest object from Item model using latest method. 之后,您可以使用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,})

About latest: 关于最新:

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

So you will be getting single object then it would not be required to iterate it in your template. 因此,您将获得单个对象,则不需要在模板中对其进行迭代。

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

You don't have to use the session and redirect or add any extra field. 您不必使用会话并重定向或添加任何其他字段。 The ModelForm save() method returns the object just saved. ModelForm save()方法返回刚刚保存的对象。 Try this: 尝试这个:

# 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 %}  

I did something slightly different. 我做了些不同的事情。 My view renders a graph figure (an image) dynamically each time so it is not in the database. 我的视图每次都动态地绘制一个图形(图像),因此它不在数据库中。 But to embed a single instance of a graph from my models this is what I did: 但是要在我的模型中嵌入图的单个实例,这就是我所做的:

First, I made a view that renders the graph from my data and created a url that goes to it (selected by using it's id): 首先,我创建了一个视图,该视图从数据中渲染图形,并创建了一个指向该图形的URL(使用其ID选择):

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

no need to show my view, but if i went to that url my view would be called and it would render the graph and only the graph. 无需显示我的视图,但是如果我转到该URL,则将调用我的视图,它将显示图形并且仅显示图形。 Similar to most sites where if you click on the picture you just get a webpage showing only the picture. 与大多数网站类似,如果您单击图片,只会得到一个仅显示图片的网页。

Now working with this url: 现在使用此网址:

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

this view brings up a template with this bad boy: 该视图为这个坏男孩带来了一个模板:

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

the url portion grabs my graphImage url and inputs the graph.id with it. 网址部分抓取了我的graphImage网址,并输入了graph.id。 And then I name it the_graph to keep it simple. 然后我将其命名为the_graph,以使其简单。

then i make an image tag as the src as the _graph. 然后我做一个图像标签作为_graph的src。 Don't worry about alt it just shows the url if it doesnt work for debugging. 不用担心alt,如果调试不起作用,它只会显示url。

So what I did was render a graph on one webpage and just use that as a source for an image tag. 因此,我要做的是在一个网页上绘制图形,然后将其用作图像标签的来源。 Theres a million ways to do this sort of thing, but this was the most obvious with my limited skills and just knowing about html and django. 有上百万种方法可以做这种事情,但这是我最有限的技能,并且只了解html和django是最明显的。

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

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