Home > Software engineering >  Can't submit image via forms (django)
Can't submit image via forms (django)

Time:01-06

I'am trying to submit a form and register it on database but imagefield is not working. Everytime i try to upload an image and hit save it just refreshes and tells me that 'This field is required'.

Here is my code:

models.py:

from django.db import models


class Photos(models.Model):
    title = models.CharField(max_length=50)
    description = models.TextField(blank=True, null=True)
    photo = models.ImageField(upload_to='images/')

forms.py:

from django import forms
from .models import Photos


class PhotosForm(forms.ModelForm):
    class Meta:
        model = Photos
        fields = [
            'title',
            'description',
            'photo'
        ]

views.py:

from django.shortcuts import render
from .models import Photos
from .forms import PhotosForm


def photo_create_view(request):
    form = PhotosForm(request.POST, request.FILES or None)
    if form.is_valid():
        form.save()

    context = {
        'form': form,
    }
    return render(request, "photos/photo_create.html", context)

setting.py:

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

template:

{% extends 'home.html'%}

{% block content %}
   <form method="POST"> {% csrf_token %}
       {{ form.as_p }}
       <input type="submit" value="Save" />
   </form>
{% endblock %}





<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>website</title>
</head>
<body bgcolor="pink">
{% block content %}

{% endblock %}
</body>
</html>

also my filetree photo: https://i.stack.imgur.com/dmyDM.png

CodePudding user response:

You should include enctype in your form.

<form method="POST" enctype="multipart/form-data"> {% csrf_token %}
       {{ form.as_p }}
       <input type="submit" value="Save" />
   </form>
  •  Tags:  
  • Related