简体   繁体   中英

Can't submit image via forms (django)

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

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM