Home > database >  getting "This field is required" message. while uploading image
getting "This field is required" message. while uploading image

Time:03-16

i don't have any problem in submiting char fields but when i put an image field i get this message -> "This field is required" while im filling the form .

models.py :

class Home(models.Model):
    image = models.ImageField(upload_to='image')
    titr = models.CharField(max_length=200)
    description = models.TextField()
    created = models.DateField(auto_now_add = True)
    updated = models.DateField(auto_now = True)

    class Meta:
        ordering = ['created']        

    def __str__(self):
        return str(self.titr)

views.py :

 def craethome(request):
    form = HomeForm()
    if request.method == "POST":
        form = HomeForm(request.POST,request.FILES)
        if form.is_valid():
            form.save()
            return redirect("home")
    return render(request, 'home/home_form.html', {"form":form})

forms.py :

    from django.forms import ModelForm
from .models import Home


class HomeForm(ModelForm):
    class Meta():
        model = Home
        fields = "__all__"

my html file:

{% extends 'main.html' %}
{% block content %}

<img src="{{home.image.url}}">
<h1>{{home.titr}}</h1>
<p>{{home.description}}</p>



{% endblock content %}

CodePudding user response:

The form should contain enctype="multipart/form-data" [mdn] to encode the file data such that it can be uploaded to the view:

<form method="POST" enctype="multipart/form-data">
    {% csrf_token %}
    {{ form }}
</form>

CodePudding user response:

You need to add enctype="multipart/form-data" into your form tag in html.

<form method="POST" enctype="multipart/form-data">
    {% csrf_token %}
    {{ form }}
</form>

If you want to submit without an image you can add null, blank, or you can add a default image.

class Home(models.Model):
    image = models.ImageField(upload_to='image', default='pic.png')
    image2 = models.ImageField(upload_to='image', blank=True, null=True)
  • Related