How to upload an image and store its link in database

4.6k Views Asked by At

I read some documents in Django site such as: Basic file uploads and FileField.storage. However, I still don't understand how to upload a file (or an image) to server and store its link in database. I would like to write the files to the following directory such as: 'image/%Y/%m/%d'

Please give me a sample code. Thank you so much.

My code follows as:

#models.py
class Image(models.Model):
   imageid = models.AutoField()
   title = models.CharField(max_length=100)
   imagepath = models.ImageField(upload_to='images/%Y/%m/%d/')       

#forms.py
class UploadFileForm(forms.Form):
   title = forms.CharField(max_length=100)
   image = forms.FileField()   

#views.py
def upload_file(request):
   if request.method == 'POST':
      form = UploadFileForm(request.POST, request.FILES)
      if form.is_valid():
         # How to upload file to folder named 'images/%Y/%m/%d/'

         # How to save the link above to database

         return HttpResponseRedirect('/success/url/')
   else:
      form = UploadFileForm()
return render_to_response('upload.html', {'form': form})
1

There are 1 best solutions below

0
On

I believe if you create the upload form as a model form and then just save it in the view, it will have the effect of saving the file to the filesystem and the path to the model. This is a basic example, but I think it should work.

# forms.py
class UploadFileForm(forms.ModelForm):
    class Meta:
        model = models.Image

# views.py
...
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
    form.save()
    return HttpResponseRedirect('/success/url/')