簡體   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