前提・実現したいこと
django初心者です。
URLのパラメータの値を基準にFormのfieldの表示・非表示を設定したいです。
●models.py
python
1class Company(models.Model): 2 name = models.CharField(verbose_name=u'会社名',max_length=50, blank=True, null=True) 3 address = models.CharField(verbose_name=u'ご住所',max_length=100, blank=True, null=True) 4 email = models.CharField(verbose_name=u'メールアドレス',max_length=50, blank=True, null=True) 5 tel = models.CharField(verbose_name=u'電話番号',max_length=50, blank=True, null=True) 6 service_id = models.ForeignKey(Service,on_delete=models.CASCADE) 7 8class Service(models.Model): 9 service_detail= models.TextField(verbose_name=u'サービス内容',blank=True, null=True)
●forms.py
python
1class CompanyFrom(forms.ModelForm): 2 class Meta: 3 model = Company 4 fields =('name','address','email','tel') 5 6 def __init__(self, *args, **kwargs): 7 self.service_id = kwargs.pop('test_service_id') 8 super(CompanyFrom,self).__init__(*args,**kwargs) 9 if self.service_id == 1: 10 self.fields['email'].widget = forms.HiddenInput()
●views.py
python
1class CompanyCreateView(generic.CreateView): 2 template_name = 'form.html' 3 model = Company 4 form_class = CompanyFrom 5 6 def get_form_kwargs(self): 7 kwargs = super(CompanyCreateView,self).get_form_kwargs() 8 kwargs['test_service_id'] =self.kwargs['sevice_id'] #service_idはパラメータ 9 return kwargs
●urls.py
python
1from django.urls import path 2 3from . import views 4 5app_name = 'company' 6 7urlpatterns = [ 8 path('<int:company_id>/create/<int:sevice_id>', views.CompanyCreateView.as_view(), name='service_create'), 9 ]
●settings.py
python
1""" 2Django settings for config project. 3 4Generated by 'django-admin startproject' using Django 2.2.12. 5 6For more information on this file, see 7https://docs.djangoproject.com/en/2.2/topics/settings/ 8 9For the full list of settings and their values, see 10https://docs.djangoproject.com/en/2.2/ref/settings/ 11""" 12 13import os 14 15# Build paths inside the project like this: os.path.join(BASE_DIR, ...) 16BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 17 18 19# Quick-start development settings - unsuitable for production 20# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ 21 22# SECURITY WARNING: keep the secret key used in production secret! 23SECRET_KEY = 'l_dil%jvy7)9f5%gr8fn(4sl0cx&tuc__o3!kf&1fzi-cw$+!e' 24 25# SECURITY WARNING: don't run with debug turned on in production! 26DEBUG = True 27 28ALLOWED_HOSTS = ['127.0.0.1'] 29 30 31# Application definition 32 33INSTALLED_APPS = [ 34 'company.apps.CompanyConfig', 35 'django.contrib.admin', 36 'django.contrib.auth', 37 'django.contrib.contenttypes', 38 'django.contrib.sessions', 39 'django.contrib.messages', 40 'django.contrib.staticfiles', 41] 42 43MIDDLEWARE = [ 44 'django.middleware.security.SecurityMiddleware', 45 'django.contrib.sessions.middleware.SessionMiddleware', 46 'django.middleware.common.CommonMiddleware', 47 'django.middleware.csrf.CsrfViewMiddleware', 48 'django.contrib.auth.middleware.AuthenticationMiddleware', 49 'django.contrib.messages.middleware.MessageMiddleware', 50 'django.middleware.clickjacking.XFrameOptionsMiddleware', 51] 52 53ROOT_URLCONF = 'config.urls' 54 55TEMPLATES = [ 56 { 57 'BACKEND': 'django.template.backends.django.DjangoTemplates', 58 'DIRS': [os.path.join(BASE_DIR, 'templates')], 59 'APP_DIRS': True, 60 'OPTIONS': { 61 'context_processors': [ 62 'django.template.context_processors.debug', 63 'django.template.context_processors.request', 64 'django.contrib.auth.context_processors.auth', 65 'django.contrib.messages.context_processors.messages', 66 ], 67 }, 68 }, 69] 70 71WSGI_APPLICATION = 'config.wsgi.application' 72 73 74# Database 75# https://docs.djangoproject.com/en/2.2/ref/settings/#databases 76 77DATABASES = { 78 'default': { 79 "ENGINE": "django.db.backends.mysql", 80 "NAME": "dbname", 81 "USER": "user", 82 "PASSWORD": "password", 83 "HOST": "hostname", 84 "PORT": "3306", 85 }, 86 "db2": { 87 "ENGINE": "sql_server.pyodbc", 88 "NAME": "dbname", 89 "USER": "user", 90 "PASSWORD": "password", 91 "HOST": "hostname", 92 "PORT": "", 93 "OPTIONS": { 94 "driver": "ODBC Driver 17 for SQL Server" 95 } 96 } 97} 98 99# Password validation 100# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators 101 102AUTH_PASSWORD_VALIDATORS = [ 103 { 104 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 105 }, 106 { 107 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 108 }, 109 { 110 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', 111 }, 112 { 113 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', 114 }, 115] 116 117 118# Internationalization 119# https://docs.djangoproject.com/en/2.2/topics/i18n/ 120 121LANGUAGE_CODE = 'ja' 122 123TIME_ZONE = 'Asia/Tokyo' 124 125USE_I18N = True 126 127USE_L10N = True 128 129USE_TZ = True 130 131 132# Static files (CSS, JavaScript, Images) 133# https://docs.djangoproject.com/en/2.2/howto/static-files/ 134 135STATIC_URL = '/static/' 136STATICFILES_DIRS = ( 137 os.path.join(BASE_DIR, "static"), 138) 139
●form.html
html
1{% extends 'base.html' %} 2 3{% block content %} 4<div> 5 <h4>企業情報</h4> 6 7 <form method="post"> 8 <table> 9 {% csrf_token %} 10 {{ form.as_p }} 11 </table> 12 <input type="submit" value="保存"> 13 </form> 14 15</div> 16{% endblock %}
ディレクトリ構造
myproject |_company |___pycache__ |_migrations |___init__.py |_admin.py |_forms.py |_models.py |_tests.py |_urls.py |_views.py |_config |___pycache__ |___init__.py |_settings.py |_urls.py |_wsgi.py |_templates |_company |_form.html |_base.html
発生している問題・エラーメッセージ
__init__() got an unexpected keyword argument 'test_service_id'
試したこと
●views.py
python
1class CompanyCreateView(generic.CreateView): 2 template_name = 'form.html' 3 model = Company 4 form_class = CompanyFrom 5 6 def get_form_kwargs(self): 7 kwargs = super(CompanyCreateView,self).get_form_kwargs() 8 kwargs['test_sevice_id'] = 1 # ← パラメータが取れていないのかと思い、1を入れてみる 9 return kwargs
やはり同じエラーが発生しました。
エラー内容から引数の設定の問題かもしれませんが、よくわかりません。
よろしくお願いします。
補足情報(FW/ツールのバージョンなど)
django=2.2
pyhton=3.8
mysql=14.14 Distrib 5.7.31
回答1件
あなたの回答
tips
プレビュー