UNC BACS 350

Web Apps with Python/Django

Logo

Lesson 33 - Image Upload

LEARN

Office Hours

Today

How To Video

by John Elder

This is the fastest way to build an image upload utility.

Code For Image Upload

Django model ImageField is used to upload images

book/models.py

python class Image(models.Model): image = models.ImageField(null=True, blank=True, upload_to="images/") title = models.CharField(max_length=200)

Settings for Storage

Set upload directory and URL

python MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR / "media"

Generate Code for Image

Form For Image Upload

Django model ImageField is used to upload images

templates/image_add.html

```html

{% csrf_token %} {{ form.media }} {{ form.as_p }}

```

Views For Image Upload

Add and list but no edit view

book/views_image.py

```python class ImageListView(ListView): template_name = 'image_list.html' model = Image

class ImageCreateView(LoginRequiredMixin, CreateView): template_name = "image_add.html" model = Image fields = ['image', 'title']

class ImageDeleteView(LoginRequiredMixin, DeleteView): model = Image template_name = 'image_delete.html' success_url = reverse_lazy('image_list') ```

URLs For Image Upload

Django model ImageField is used to upload images

book/urls.py

python path('image/', ImageListView.as_view(), name='image_list'), path('image/add', ImageCreateView.as_view(), name='image_add'), path('image/<int:pk>/delete', ImageDeleteView.as_view(), name='image_delete'),

Views For Image Display

Django model ImageField is used to upload images

templates/image_list.html

```html

{% for image in object_list %} {% endfor %}
{{ image.title }} {{ image.image.url }} Delete

```

BUILD

Demo Code

Final Project

New Features