Download a remote image and save it to a Django model

后端 未结 6 920
醉话见心
醉话见心 2020-12-01 01:52

I am writing a Django app which will fetch all images of particular URL and save them in the database.

But I am not getting on how to use ImageField in Django.

6条回答
  •  囚心锁ツ
    2020-12-01 02:32

    As an example of what I think you're asking:

    In forms.py:

    imgfile = forms.ImageField(label = 'Choose your image', help_text = 'The image should be cool.')
    

    In models.py:

    imgfile =   models.ImageField(upload_to='images/%m/%d')
    

    So there will be a POST request from the user (when the user completes the form). That request will contain basically a dictionary of data. The dictionary holds the submitted files. To focus the request on the file from the field (in our case, an ImageField), you would use:

    request.FILES['imgfield']
    

    You would use that when you construct the model object (instantiating your model class):

    newPic = ImageModel(imgfile = request.FILES['imgfile'])
    

    To save that the simple way, you'd just use the save() method bestowed upon your object (because Django is that awesome):

    if form.is_valid():
        newPic = Pic(imgfile = request.FILES['imgfile'])
        newPic.save()
    

    Your image will be stored, by default, to the directory you indicate for MEDIA_ROOT in settings.py.

    Accessing the image in the template:

    
    

    The urls can be tricky, but here's a basic example of a simple url pattern to call the stored images:

    urlpatterns += patterns('',
            url(r'^media/(?P.*)$', 'django.views.static.serve', {
                'document_root': settings.MEDIA_ROOT,
            }),
       )
    

    I hope it helps.

提交回复
热议问题