Django TypeError in forms.py

Обновить

April 2019

Просмотры

94 раз

1

Я развертывание моего приложения Django на pythonanywhere.com и получить эту ошибку, делая Регистрацию на пользователе TypeError at /registration/ argument 1 must be str, not list.

Я проверяю, если пользователь уже представляет в базе данных, то бросать ошибку проверки в forms.py.

Ошибка подозревается в связи с этим кодом.

forms.py

class SignUpForm(forms.Form):
    email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.')
    name = forms.CharField(max_length=100, required=False, help_text='Required.')
    password = forms.CharField(max_length=1000, required=False, help_text='Required.')
    role = forms.CharField()

    def clean(self):
        cleaned_data = super(SignUpForm, self).clean()
        name = cleaned_data.get("name")
        email = cleaned_data.get("email")
        password = cleaned_data.get("password")
        role = cleaned_data.get("role")
        # validate email
        if role == 'Author':
            user = UserSignup.objects.filter(email=email)
            #error suspected here--
            if user.first() is not None:
                raise forms.ValidationError(
                "Email already registered. Try again.")
        elif role == 'Publisher':
            user = PubSignup.objects.filter(email=email)
            if user.first() is not None:
                raise forms.ValidationError(
                "Email already registered. Try again.")

    class Meta:
        model = UserSignup
        fields = ('email', 'name', 'password')

models.py

class UserSignup(models.Model):
    email = models.CharField(unique=True, max_length=254)
    name = models.CharField(max_length=100)
    password = models.CharField(max_length=1000)
    created_date = datetime.now()

    class Meta:
        app_label = 'UserSignup'

    def __str__(self):
        return self.email


class PubSignup(models.Model):
    email = models.CharField(unique=True, max_length=254)
    name = models.CharField(max_length=100)
    password = models.CharField(max_length=1000)
    created_date = datetime.now()

    class Meta:
        app_label = 'PubSignup'

    def __str__(self):
        return self.email

views.py

if form.is_valid():
        if form.role == "Author":
            p = UserSignup(
                name=form.cleaned_data.get('name'),
                email=form.cleaned_data.get('email'),
                password=form.cleaned_data.get('password')
            )
            p.save()
            success = True
        elif form.role == "Publisher":
            p = PubSignup(
                name=form.cleaned_data.get('name'),
                email=form.cleaned_data.get('email'),
                password=form.cleaned_data.get('password')
            )
            p.save()
            success = True

отслеживающий ошибки

Traceback:

File "/home/zerocod3r/lib/python3.5/site-
packages/django/core/handlers/exception.py" in inner
42.             response = get_response(request)

File "/home/zerocod3r/lib/python3.5/site-
packages/django/core/handlers/base.py" in _get_response
187.  response = self.process_exception_by_middleware(e, 
request)

File "/home/zerocod3r/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
185.  response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/home/zerocod3r/PublicationPlatform/mainapp/views.py" in signup_user
26. if form.is_valid():

File "/home/zerocod3r/lib/python3.5/site-packages/django/forms/forms.py" in is_valid
169. return self.is_bound and not self.errors

File "/home/zerocod3r/lib/python3.5/site-packages/django/forms/forms.py" in errors
161. self.full_clean()

File "/home/zerocod3r/lib/python3.5/site-packages/django/forms/forms.py" in full_clean
371. self._clean_form()

File "/home/zerocod3r/lib/python3.5/site-packages/django/forms/forms.py" in _clean_form
398. cleaned_data = self.clean()

File "/home/zerocod3r/PublicationPlatform/mainapp/forms.py" in clean
27. if user.first() is not None:

File "/home/zerocod3r/lib/python3.5/site-packages/django/db/models/query.py" in first
556. objects = list((self if self.ordered else self.order_by('pk'))[:1])

File "/home/zerocod3r/lib/python3.5/site-packages/django/db/models/query.py" in __iter__
256. self._fetch_all()

File "/home/zerocod3r/lib/python3.5/site-packages/django/db/models/query.py" in _fetch_all
1087. self._result_cache = list(self.iterator())

File "/home/zerocod3r/lib/python3.5/site-packages/django/db/models/query.py" in __iter__
54. results = compiler.execute_sql()

File "/home/zerocod3r/lib/python3.5/site-packages/django/db/models/sql/compiler.py" in execute_sql
833. cursor = self.connection.cursor()

File "/home/zerocod3r/lib/python3.5/site-packages/django/db/backends/base/base.py" in cursor
231. cursor = self.make_debug_cursor(self._cursor())

File "/home/zerocod3r/lib/python3.5/site-packages/django/db/backends/base/base.py" in _cursor
204. self.ensure_connection()

File "/home/zerocod3r/lib/python3.5/site-packages/django/db/backends/base/base.py" in ensure_connection
199. self.connect()

File "/home/zerocod3r/lib/python3.5/site-packages/django/db/backends/base/base.py" in connect
171. self.connection = self.get_new_connection(conn_params)

File "/home/zerocod3r/lib/python3.5/site-packages/django/db/backends/sqlite3/base.py" in get_new_connection
209. conn = Database.connect(**conn_params)

Exception Type: TypeError at /registration/
Exception Value: argument 1 must be str, not list

Мой settings.py

import os

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

SECRET_KEY = 'some-text'
DEBUG = True

ALLOWED_HOSTS = ['zerocod3r.pythonanywhere.com','*']

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'mainapp',
]

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',
]

ROOT_URLCONF = 'PublicationPlatform.urls'

TEMPLATES = [
{
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
    #'DIRS': [os.path.join(BASE_DIR, 'templates')]
    'DIRS': ['/home/zerocod3r/PublicationPlatform/templates/']
    ,
    'APP_DIRS': True,
    'OPTIONS': {
        'context_processors': [
            'django.template.context_processors.debug',
            'django.template.context_processors.request',
            'django.contrib.auth.context_processors.auth',
            'django.contrib.messages.context_processors.messages',
        ],
    },
},
]

WSGI_APPLICATION = 'PublicationPlatform.wsgi.application'

DATABASES = {
'default': {
    'ENGINE': 'django.db.backends.sqlite3',
    'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}

AUTH_PASSWORD_VALIDATORS = [
{
    'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
    'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
    'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
    'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]


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

STATICFILES_DIRS = [
'/home/zerocod3r/PublicationPlatform/mainapp/static/',
]

STATIC_ROOT = os.path.join(BASE_DIR, 'mainapp/static')
STATIC_URL = '/static/'

1 ответы

1

You may re-write your clean() method, may be somewhat like this,

model = None
if role == 'Author':
    model = UserSignup
elif role == 'Publisher':
    model = PubSignup
if model is not None:
    try:
        user = model.objects.get(email=email)
        raise forms.ValidationError(
                "Email already registered. Try again.")
    except:
        pass