【问题标题】:super().__init__(*args, **kwargs) TypeError: __init__() got an unexpected keyword argument 'label'super().__init__(*args, **kwargs) TypeError: __init__() got an unexpected keyword argument 'label'
【发布时间】:2021-06-11 10:14:47
【问题描述】:

我在 Django 中尝试了一个多选字段项目。根据我的知识,一切都是正确的。但是,尝试进行迁移,它会显示 TypeError。如何解决?

错误

File "D:\My Django Projects\multiselectproject\multiselectapp\forms.py", line 4, in <module>
    class EnquiryForm(forms.Form):
  File "D:\My Django Projects\multiselectproject\multiselectapp\forms.py", line 30, in EnquiryForm
    course = MultiSelectField(label='Select Required Courses:', choices='Courses_Choices')
  File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python39\lib\site-packages\multiselectfield\db\fields.py", line 70, in __init__
    super(MultiSelectField, self).__init__(*args, **kwargs)
  File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\fields\__init__.py", line 986, in __init__
    super().__init__(*args, **kwargs)
TypeError: __init__() got an unexpected keyword argument 'label'

settings.py

"""
Django settings for multiselectproject project.

Generated by 'django-admin startproject' using Django 3.1.2.

For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
import os
from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'n&*#@g^b-%-$-yd1^!iwzhfnttd4s^zf+&$*5!i0_ves1v8s4&'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'multiselectapp.apps.MultiselectappConfig',
]

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 = 'multiselectproject.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, '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 = 'multiselectproject.wsgi.application'


# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'multiselectdb',
        'HOST': '127.0.0.1',
        'PORT': '3306',
        'USER': 'root',
        'PASSWORD': 'root',
    }
}
# DATABASES = {
#     'default': {
#         'ENGINE': 'django.db.backends.sqlite3',
#         'NAME': BASE_DIR / 'db.sqlite3',
#     }
# }


# Password validation
# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators

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


# Internationalization
# https://docs.djangoproject.com/en/3.1/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/

STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]

models.py

from django.db import models
from multiselectfield import MultiSelectField
# Create your models here.

class EnquiryData(models.Model):
    name = models.CharField(max_length=20)
    email = models.EmailField(max_length=20)
    mobile = models.IntegerField()

    Courses_Choices = (('Python', 'Python'), ('Django', 'Django'), ('Flask', 'Flask'), ('Rest API', 'Rest API'), ('UI', 'UI'))
    course = MultiSelectField(max_length=200, choices='Courses_Choices')

    Locations_Choices = (('Hyd', 'Hyderabad'), ('Bang', 'Banglore'), ('Che', 'Chennai'), ('Mum', 'Mumbai'))
    locations = MultiSelectField(max_length=200, choices='Locations_Choices')

    Trainers_Choices = (('Govardhan', 'Govardhan'), ('Manikanta', 'Manikanta'), ('Kartheek', 'Kartheek'))
    trainers = MultiSelectField(max_length=200, choices='Trainers_Choices')

    gender = models.CharField(max_length=20)
    start_date = models.DateField(max_length=50)

forms.py

from django import forms
from multiselectfield import MultiSelectField

class EnquiryForm(forms.Form):
    name = forms.CharField( label = 'Enter your name:', widget = forms.TextInput(
                attrs = {
                            'class':'form-control',
                            'placeholder':'Your name'
                        }
            )
        )

    email = forms.EmailField( label = 'Enter your email:', widget = forms.EmailInput(
                attrs = {
                            'class':'form-control',
                            'placeholder':'Your email'
                        }
            )
        )

    mobile = forms.IntegerField( label = 'Enter your contact number:', widget = forms.NumberInput(
                attrs = {
                            'class':'form-control',
                            'placeholder':'Your contact number'
                        }
            )
        )

    Courses_Choices = (('Python', 'Python'), ('Django', 'Django'), ('Flask', 'Flask'), ('Rest API', 'Rest API'), ('UI', 'UI'))
    course = MultiSelectField(label='Select Required Courses:', choices='Courses_Choices')

    Locations_Choices = (('Hyd', 'Hyderabad'), ('Bang', 'Banglore'), ('Che', 'Chennai'), ('Mum', 'Mumbai'))
    locations = MultiSelectField(label='Select Required Locations', choices='Locations_Choices')

    Trainers_Choices = (('Govardhan', 'Govardhan'), ('Manikanta', 'Manikanta'), ('Kartheek', 'Kartheek'))
    trainers = MultiSelectField(label='Select Required Trainers', choices='Trainers_Choices')

    Gender_Choices = (('Male', 'Male'), ('Female', 'Female'))
    gender = forms.ChoiceField(widget=forms.RadioSelect, choices='Gender_Choices', label='Select your gender')

    start_date = forms.DateField(widget=forms.SelectDateWidget(), label='Select your timings')

views.py

from django.shortcuts import render
from .models import EnquiryData
from .forms import EnquiryForm
# Create your views here.

def enquiry_view(request):
    if request.method == 'POST':
        pass
    else:
        form = EnquiryForm()
        context = {'form':form}
        return render(request, 'enquiry.html', context)

enquiry.html

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
<div class="container">
    <div class="row">
        <div class="offset-md-3 col-md-6">
            <form>
                {% csrf_token %}
                {{ form }}
                <input type="submit" name="submit" value="Save">
                <input type="reset" name="reset" value="Cancel">
            </form>
        </div>
    </div>
</div>
</body>
</html>

urls.py-multiselectapp

from django.urls import path
from multiselectapp import views

urlpatterns = [
    path('', views.enquiry_view, name=''),
]

urls.py

"""multiselectproject URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/3.1/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('multiselectapp.urls')),
]

【问题讨论】:

    标签: django django-models django-views django-forms


    【解决方案1】:

    对于表单字段,您使用MultiSelectFormField,而不是MultiSelectField

    from django import forms
    from multiselectfield.forms.fields import MultiSelectFormField
    
    class EnquiryForm(forms.Form):
        # …
        Courses_Choices = (
          ('Python', 'Python')
        , ('Django', 'Django')
        , ('Flask', 'Flask')
        , ('Rest API', 'Rest API')
        , ('UI', 'UI')
        )
        course = MultiSelectFormField(label='Select Required Courses:', choices='Courses_Choices')
    
        Locations_Choices = (
          ('Hyd', 'Hyderabad')
        , ('Bang', 'Banglore')
        , ('Che', 'Chennai')
        , ('Mum', 'Mumbai')
        )
        locations = MultiSelectFormField(label='Select Required Locations', choices='Locations_Choices')
    
        Trainers_Choices = (
          ('Govardhan', 'Govardhan')
        , ('Manikanta', 'Manikanta')
        , ('Kartheek', 'Kartheek')
        )
        trainers = MultiSelectFormField(label='Select Required Trainers', choices='Trainers_Choices')

    话虽如此,如果您使用ModelForm,Django 已经可以为您完成大部分工作。

    【讨论】:

    • 在models.py 和forms.py 中修改此代码后显示此错误先生。请帮忙。我是 Django 的新手。 中的文件“C:\Users\Lenovo\AppData\Local\Programs\Python\Python39\lib\site-packages\multiselectfield\utils.py”,第 31 行,return len(','.join([string_type (key) for key, label in selection])) ValueError: not enough values to unpack (expected 2, got 1)
    • @KartheekRavula:使用 full 回溯编辑问题。
    • 我以自己的方式解决了这个问题。我将choices='Courses_Choices'中的单引号删除到choices=Courses_Choices。然后问题解决了...
    猜你喜欢
    • 1970-01-01
    • 2018-03-29
    • 2021-01-19
    • 1970-01-01
    • 2012-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-01
    相关资源
    最近更新 更多