3 votes

Message d'erreur de Django : ["'on' value must be either True or False."]

J'ai actuellement ce message d'erreur sur django : ["'on' value must be either True or False."]

views.py

from django.shortcuts import render, redirect
from .models import Comment
from .forms import sign

def index(request):
    return render(request, 'submits/index.html')

def sign_list(request):
    if request.method == 'POST':
        form = sign(request.POST)

        if form.is_valid():
            new_contact = Comment(email=request.POST['email'], message=request.POST['message'], checkbox=request.POST['checkbox'])
            new_contact.save()
            return redirect('index')
    else:
        form = sign()

    context = {'form' : form}
    return render(request, 'submits/sign.html', context)

forms.py

from django import forms
from .models import Comment

class sign(forms.Form):
    email = forms.CharField(max_length=500,
    widget=forms.TextInput(attrs={ 'type' : 'email',  'class' : 'form-control', 'placeholder' : 'Enter your email', 'aria-describedby' : 'emailHelp'}))
    message = forms.CharField(widget=forms.Textarea(attrs={ 'class' : 'form-control', 'rows' : '3', 'placeholder' : 'Write your proposal'}))
    checkbox = forms.BooleanField(required=False, initial=True)
    checkbox_attributes={'class': 'form-check'}

models.py

from django.db import models

# Create your models here.
class Comment(models.Model):
    email = models.CharField(max_length=500)
    message = models.TextField()
    checkbox = models.BooleanField()
    def __str__(self):
        return 'e-mail: {}, ID: {}'.format(self.email, self.id)

Fournir la trace complète

Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/contact_us/
Django Version: 2.0.3
Python Version: 3.5.2
Installed Applications:
['submits',
 'django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback:
File "/home/joaomjaneiro/django/venv/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner
  35.             response = get_response(request)
File "/home/joaomjaneiro/django/venv/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
  128.                 response = self.process_exception_by_middleware(e, request)
File "/home/joaomjaneiro/django/venv/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
  126.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/media/joaomjaneiro/LEXAR/django projects/love/submits/views.py" in sign_list
  14.             new_contact.save()
File "/home/joaomjaneiro/django/venv/lib/python3.5/site-packages/django/db/models/base.py" in save
  729.                        force_update=force_update, update_fields=update_fields)
File "/home/joaomjaneiro/django/venv/lib/python3.5/site-packages/django/db/models/base.py" in save_base
  759.             updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "/home/joaomjaneiro/django/venv/lib/python3.5/site-packages/django/db/models/base.py" in _save_table
  842.             result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "/home/joaomjaneiro/django/venv/lib/python3.5/site-packages/django/db/models/base.py" in _do_insert
  880.                                using=using, raw=raw)
File "/home/joaomjaneiro/django/venv/lib/python3.5/site-packages/django/db/models/manager.py" in manager_method
  82.                 return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/home/joaomjaneiro/django/venv/lib/python3.5/site-packages/django/db/models/query.py" in _insert
  1125.         return query.get_compiler(using=using).execute_sql(return_id)
File "/home/joaomjaneiro/django/venv/lib/python3.5/site-packages/django/db/models/sql/compiler.py" in execute_sql
  1282.             for sql, params in self.as_sql():
File "/home/joaomjaneiro/django/venv/lib/python3.5/site-packages/django/db/models/sql/compiler.py" in as_sql
  1235.                 for obj in self.query.objs
File "/home/joaomjaneiro/django/venv/lib/python3.5/site-packages/django/db/models/sql/compiler.py" in <listcomp>
  1235.                 for obj in self.query.objs
File "/home/joaomjaneiro/django/venv/lib/python3.5/site-packages/django/db/models/sql/compiler.py" in <listcomp>
  1234.                 [self.prepare_value(field, self.pre_save_val(field, obj)) for field in fields]
File "/home/joaomjaneiro/django/venv/lib/python3.5/site-packages/django/db/models/sql/compiler.py" in prepare_value
  1174.             value = field.get_db_prep_save(value, connection=self.connection)
File "/home/joaomjaneiro/django/venv/lib/python3.5/site-packages/django/db/models/fields/__init__.py" in get_db_prep_save
  767.         return self.get_db_prep_value(value, connection=connection, prepared=False)
File "/home/joaomjaneiro/django/venv/lib/python3.5/site-packages/django/db/models/fields/__init__.py" in get_db_prep_value
  762.             value = self.get_prep_value(value)
File "/home/joaomjaneiro/django/venv/lib/python3.5/site-packages/django/db/models/fields/__init__.py" in get_prep_value
  1024.         return self.to_python(value)
File "/home/joaomjaneiro/django/venv/lib/python3.5/site-packages/django/db/models/fields/__init__.py" in to_python
  1017.             params={'value': value},
Exception Type: ValidationError at /contact_us/
Exception Value: ["'on' value must be either True or False."]

Dans le fichier HTML, j'ai la case à cocher forms.checkbox et non une case codée en dur, je n'arrive pas à comprendre.

Je n'arrive pas à comprendre comment corriger cette erreur.

5voto

Moon Points 2361

Je suis actuellement confronté au même problème lorsque j'enregistre l'objet employé.

J'ai pu résoudre mon problème en utilisant le code ci-dessous.

if is_retired == 'on':
   is_retired = True
else:
   is_retired = False

J'ai constaté que j'ai déclaré is_retired comme un champ booléen, mais dans mon projet, j'attribue une valeur de chaîne soit "on", soit "off", et je demande donc de définir uniquement une valeur booléenne.

Je suis donc parvenu à résoudre le problème en convertissant la valeur d'une chaîne en valeur booléenne.

J'espère que la solution ci-dessus vous conviendra !

Prograide.com

Prograide est une communauté de développeurs qui cherche à élargir la connaissance de la programmation au-delà de l'anglais.
Pour cela nous avons les plus grands doutes résolus en français et vous pouvez aussi poser vos propres questions ou résoudre celles des autres.

Powered by:

X