this field is required. error with imagefield and filefield on django

  • Last Update :
  • Techknowledgy :

At first, in your model make your fields empty and nullable:

class campoImagen(models.Model):
   #[...]
imagen = models.ImageField(verbose_name = 'Imagen', upload_to = 'archivos', null = True, blank = True)

Then in your model form alter the required parameter of your field:

class campoImagenForm(forms.ModelForm):
   class Meta:
   model = campoImagen
fields = ('imagen', )

def __init__(self, * args, ** kwargs):
   super(campoImagenForm, self).__init__( * args, ** kwargs)
self.fields['imagen'].required = False

In forms.py

class campoImagenForm(forms.ModelForm):
   imagen = forms.ImageField(verbose_name = 'Imagen', upload_to = 'archivos', required = False)
class Meta:
   model = campoImagen
fields = ('imagen', )

Suggestion : 2

1 day ago Oct 09, 2019  · FileField – Django Models. FileField is a file-upload field. Before uploading files, one needs to specify a lot of settings so that file is securely saved and can be retrieved in a convenient manner. The default form widget for this field is a ClearableFileInput. , 1 week ago Oct 15, 2019  · ImageField – Django Models. ImageField is a FileField with uploads restricted to image formats only. Before uploading files, one needs to specify a lot of settings so that file is securely saved and can be retrieved in a convenient manner. The default form widget for this field is a ClearableFileInput. , FileField – Django Models Last Updated : 12 Feb, 2020 FileField is a file-upload field. Before uploading files, one needs to specify a lot of settings so that file is securely saved and can be retrieved in a convenient manner. , Name of a model field which will be auto-populated with the width of the image each time the model instance is saved. Illustration of ImageField using an Example.


 This field is required.

class campoImagen(models.Model): #[...] imagen = models.ImageField(verbose_name = 'Imagen', upload_to = 'archivos', null = True, blank = True)
 This field is required.
if request.method == 'POST': form = campoImagenForm(request.POST, request.FILES) if form.is_valid(): articulo = form.save(commit = False) articulo.item = item articulo.atributo = atributo articulo.save() return HttpResponseRedirect('/workproject/' + str(project.id))
class campoImagenForm(forms.ModelForm): class Meta: model = campoImagen fields = ('imagen', )
class campoImagen(models.Model): item = models.ForeignKey(ItemBase) atributo = models.ForeignKey(TipoItem) imagen = models.ImageField(verbose_name = 'Imagen', upload_to = 'archivos') version = models.IntegerField()

Suggestion : 3

I want to let my users can change their mugshot without updating their whole profile. When i have a form with only mugshot field, form never pass validaiton. If i add another field to that form it can pass validation now. My model and forms are below. , The reason the form validates in the second example, is because you have two fields specified. In the first one, you only have one. , With that I was able to conclude that it works. It does NOT matter if there's only one (file)field or more. , What I don't get is why you are using the forms.BooleanField in the form that you are inheriting from ModelForm...

class Profile(models.Model):
   ""
"
Profile model

   ""
"

GENDER_CHOICES = (
   ('F', _('Female')),
   ('M', _('Male')),
)

user = models.ForeignKey(User, unique = True, verbose_name = _('user'))

mugshot = models.ImageField(_('mugshot'), upload_to = 'uploads/mugshots', blank = True)
birth_date = models.DateField(_('birth date'), blank = True, null = True)
gender = models.CharField(_('gender'), choices = GENDER_CHOICES, max_length = 1, null = True)
occupation = models.CharField(_('occupation'), max_length = 32, blank = True)
mobile = PhoneNumberField(_('mobile'), blank = True)
class MugshotForm(forms.ModelForm):
   mugshot = forms.ImageField(required = True)

class Meta:
   model = Profile
fields = ['mugshot']
class MugshotForm(forms.ModelForm):
   gender = forms.CharField(widget = forms.HiddenInput())
mugshot = forms.ImageField(required = True)

class Meta:
   model = Profile
fields = ['mugshot', 'gender']

I can not reproduce it either. Here's what I did

class MyModel(models.Model):
   a = models.FileField(upload_to = '.')
b = models.CharField(max_length = 123)

class FileOnlyForm(forms.ModelForm):
   class Meta:
   model = MyModel
fields = ['a']

And a view that uses this modelform

def fileupload(request):
   if request.method == "POST":
   form = FileOnlyForm(request.POST, request.FILES)
print form.is_valid()
else:
   form = FileOnlyForm()
return render_to_response('fileupload.html', locals(),
   context_instance = RequestContext(request))

Suggestion : 4

Last Updated : 12 Feb, 2020

1._
 pip install Pillow

Syntax

field_name = models.ImageField(upload_to = None, height_field = None, width_field = None, max_length = 100, ** options)

ImageField has following optional arguments:

ImageField.upload_to

Name of a model field which will be auto-populated with the height of the image each time the model instance is saved.

ImageField.width_field

Now when we run makemigrations command from the terminal,

Python manage.py makemigrations

Now when we run makemigrations command from the terminal,

Python manage.py makemigrations

Now run,

Python manage.py migrate
9._
Python manage.py createsuperuser
Python manage.py createsuperuser
http: //localhost:8000/admin/

Suggestion : 5

Django comes with two form fields to upload files to the server, FileField and ImageField, the following is an example of using these two fields in our form,Also here you will work with ImageField, so remember in such cases install Pillow library (pip install pillow). Otherwise, you will have such error:,Pillow is a fork of PIL, the Python Imaging Library, which is no longer maintained. Pillow is backwards compatible with PIL., Mapping strings to strings with HStoreField - a PostgreSQL specific field

First of all we need to add MEDIA_ROOT and MEDIA_URL to our settings.py file

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

Also here you will work with ImageField, so remember in such cases install Pillow library (pip install pillow). Otherwise, you will have such error:

ImportError: No module named PIL

forms.py:

from django
import forms

class UploadDocumentForm(forms.Form):
   file = forms.FileField()
image = forms.ImageField()

upload_doc.html:

<html>
    <head>File Uploads</head>
    <body>
        <form enctype="multipart/form-data" action="" method="post"> <!-- Do not forget to add: enctype="multipart/form-data" -->
            {% csrf_token %}
            {{ form }}
            <input type="submit" value="Save">
        </form>
    </body>
</html>