0

I'm trying to display an input type="file" that accepts image files. When i upload the file through Django Admin, everything works (its uploaded to my media folder, and its successfully displayed on html) but when i do it through my html page, it doesnt go to media, and i can't display it. So i'm assuming the problem isnt with django but my settings.py or something with my html

HELP

create.html (to upload image)

<label for="imgpreview" class="imglabel">Choose Image</label>
<input accept="image/*" type='file' id="imgpreview" name="imgpreview" class="image-form" onchange="previewImage(event);"/>

index.html (to display image)

<div class="banner-image"><img id="model-img-display" src="{{item.image.url}}"></div>

views.py (to save model)

def create(request):
    if request.method == 'POST':
        title = request.POST['title']
        image = request.POST['imgpreview']
        category = request.POST['category']
        brand = request.POST['brand']
        color = request.POST['color']

        clothes = Clothes(title=title, image=image, category=category, brand=brand, color=color)
        clothes.save()

    return render(request, "wardrobe/create.html")

models.py

class Clothes(models.Model):
    title = models.CharField(max_length=50)
    image = models.ImageField(default='', upload_to='wardrobe/') #wardrobe= media subfolder
    category = models.CharField(max_length=200, null=True, blank=True)
    brand = models.CharField(max_length=200, null=True, blank=True)
    color = models.CharField(max_length=200, null=True, blank=True)
    deleted = models.BooleanField(default=False)

settings.py

MEDIA_URL='/media/'
MEDIA_ROOT= BASE_DIR/'project5'/'wardrobe'/'media'

urls.py

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('wardrobe.urls')),
] + static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)

EDIT: i changed my views.py following https://simpleisbetterthancomplex.com/tutorial/2016/08/01/how-to-upload-files-with-django.html instructions and now everything works!

maria
  • 42
  • 5
  • 1
    Not a fix but note that the [](https://html.spec.whatwg.org/dev/embedded-content.html#the-input-element) tag does not use and does not need a closing slash and never has in any HTML specification. – Rob Jul 20 '23 at 08:31

1 Answers1

1

You are not processing your input with forms.Form (ModelForm) which is HUGE anti-pattern and one of indirect sources of your problem here.

  1. Define a ModelForm class for your model (admin is using one)
  2. form = ClothesForm(request.POST, request.FILES) # files are not part of POST
  3. Make sure html <form> tag has correct enctype attribute to send binary data or you won't see file being sent.

Process form validation and handling as in good tutorials. DjangoGirls have a good one on forms.

Gin Fuyou
  • 226
  • 1
  • 5