Reputation: 109
Learning Django, I wanted to build a site where people can upload pictures. The whole account application ( create account, change passward etc. ) is completed, now I have to create a aplication that allows the user to upload images. I am now finding myself writing the final template, but I don't know how to specify the path the the saved picture.
I have created an Image model that saves the image file offered by the user to the /media/images directory like so : image = models.ImageField(upload_to='images')
.
The form that the user has to complete is :
class ImagePost(forms.ModelForm):
class Meta:
model = Image
fields = ('image','description','title')
So, he has to provide the image, a description and the title (description and title are 2 other attributes of the class Image model.
Here is the view that handles the logic part :
@login_required
def image_create(request):
if request.method == 'POST':
# form is sent
form = ImagePost(data=request.POST)
if form.is_valid():
# form data is valid
cd = form.cleaned_data
new_item = cd.save(commit=False)
# assign current user to the item
new_item.user = request.user
new_item.save()
# redirect to new created item detail view
return render(request,
'images/all_images.html',
{'new_item': new_item})
else:
# build form with data provided by the bookmarklet via GET
form = ImagePost(data=request.GET)
return render(request,
'images/image/create.html',
{'section': 'images',
'form': form,
})
Finally the template that handles the form, currently looks like this :
{% extends "base.html" %}
{% block title %}Post an image{% endblock %}
{% block content %}
<h1>Post an image</h1>
<form action="." method="post">
{{ form.as_p }}
{% csrf_token %}
<input type="submit" value="Post it!">
</form>
{% endblock %}
As the user uploads the picture, the name of the file that now is in my media/images directory has the same name that it had on the user's PC.
How can I find out that name so I can specify Django what file to display? Or is there a way to rename the file so it matches with the title introduced by the user ?
<img src="media/images/WHAT_IS_YOUR_NAME" class="image-preview">
Upvotes: 0
Views: 4359