简体   繁体   中英

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

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

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. Just set the id in session. So when redirecting you can have the id of that photo & user also like ...

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.

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.

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. 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(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. 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. And then I name it the_graph to keep it simple.

then i make an image tag as the src as the _graph. Don't worry about alt it just shows the url if it doesnt work for debugging.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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