Problem with docker-compose up for django cookiecutter ->Django Error: relation "users_user" does not exist
Problem with docker-compose up for django cookiecutter ->Django Error: relation "users_user" does not exist
我在我的项目中使用 Django Cookiecutter 模板,当我使用 docker 构建 docker 图像时,一切都很好,但是当我执行
docker-compose -f local.yml up
我得到这个输出
postgres_1 | This user must also own the server process.
postgres_1 |
postgres_1 | The database cluster will be initialized with locale "en_US.utf8".
postgres_1 | The default database encoding has accordingly been set to "UTF8".
postgres_1 | The default text search configuration will be set to "english".
postgres_1 |
postgres_1 | Data page checksums are disabled.
postgres_1 |
postgres_1 | fixing permissions on existing directory /var/lib/postgresql/data ... ok
postgres_1 | creating subdirectories ... ok
postgres_1 | selecting default max_connections ... 100
postgres_1 | selecting default shared_buffers ... 128MB
postgres_1 | selecting default timezone ... Etc/UTC
postgres_1 | selecting dynamic shared memory implementation ... posix
postgres_1 | creating configuration files ... ok
postgres_1 | running bootstrap script ... ok
mailhog_1 | 2020/02/22 16:26:28 Using in-memory storage
mailhog_1 | 2020/02/22 16:26:28 [SMTP] Binding to address: 0.0.0.0:1025
mailhog_1 | 2020/02/22 16:26:28 Serving under http://0.0.0.0:8025/
mailhog_1 | [HTTP] Binding to address: 0.0.0.0:8025
mailhog_1 | Creating API v1 with WebPath:
mailhog_1 | Creating API v2 with WebPath:
django_1 | Waiting for PostgreSQL to become available...
postgres_1 | performing post-bootstrap initialization ... ok
postgres_1 | syncing data to disk ... ok
postgres_1 |
postgres_1 | Success. You can now start the database server using:
postgres_1 |
postgres_1 | pg_ctl -D /var/lib/postgresql/data -l logfile start
postgres_1 |
postgres_1 |
postgres_1 | WARNING: enabling "trust" authentication for local connections
postgres_1 | You can change this by editing pg_hba.conf or using the option -A, or
postgres_1 | --auth-local and --auth-host, the next time you run initdb.
postgres_1 | waiting for server to start....2020-02-22 16:26:29.864 UTC [42] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432"
postgres_1 | 2020-02-22 16:26:29.876 UTC [43] LOG: database system was shut down at 2020-02-22 16:26:29 UTC
postgres_1 | 2020-02-22 16:26:29.880 UTC [42] LOG: database system is ready to accept connections
postgres_1 | done
postgres_1 | server started
django_1 | Waiting for PostgreSQL to become available...
postgres_1 | CREATE DATABASE
postgres_1 |
postgres_1 |
postgres_1 | /usr/local/bin/docker-entrypoint.sh: ignoring /docker-entrypoint-initdb.d/*
postgres_1 |
postgres_1 | 2020-02-22 16:26:30.416 UTC [42] LOG: received fast shutdown request
postgres_1 | waiting for server to shut down....2020-02-22 16:26:30.417 UTC [42] LOG: aborting any active transactions
postgres_1 | 2020-02-22 16:26:30.421 UTC [42] LOG: background worker "logical replication launcher" (PID 49) exited with exit code 1
postgres_1 | 2020-02-22 16:26:30.423 UTC [44] LOG: shutting down
postgres_1 | 2020-02-22 16:26:30.432 UTC [42] LOG: database system is shut down
postgres_1 | done
postgres_1 | server stopped
postgres_1 |
postgres_1 | PostgreSQL init process complete; ready for start up.
postgres_1 |
postgres_1 | 2020-02-22 16:26:30.535 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432
postgres_1 | 2020-02-22 16:26:30.535 UTC [1] LOG: listening on IPv6 address "::", port 5432
postgres_1 | 2020-02-22 16:26:30.537 UTC [1] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432"
postgres_1 | 2020-02-22 16:26:30.548 UTC [60] LOG: database system was shut down at 2020-02-22 16:26:30 UTC
postgres_1 | 2020-02-22 16:26:30.552 UTC [1] LOG: database system is ready to accept connections
django_1 | PostgreSQL is available
postgres_1 | 2020-02-22 16:26:32.030 UTC [68] ERROR: relation "users_user" does not exist at character 34
postgres_1 | 2020-02-22 16:26:32.030 UTC [68] STATEMENT: SELECT "users_user"."email" FROM "users_user" ORDER BY "users_user"."email" ASC
django_1 | Traceback (most recent call last):
django_1 | File "/usr/local/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute
django_1 | return self.cursor.execute(sql, params)
django_1 | psycopg2.errors.UndefinedTable: relation "users_user" does not exist
django_1 | LINE 1: SELECT "users_user"."email" FROM "users_user" ORDER BY "user...
django_1 | ^
django_1 |
django_1 |
django_1 | The above exception was the direct cause of the following exception:
django_1 |
django_1 | Traceback (most recent call last):
django_1 | File "manage.py", line 30, in <module>
django_1 | execute_from_command_line(sys.argv)
django_1 | File "/usr/local/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line
django_1 | utility.execute()
django_1 | File "/usr/local/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute
django_1 | self.fetch_command(subcommand).run_from_argv(self.argv)
django_1 | File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 323, in run_from_argv
django_1 | self.execute(*args, **cmd_options)
django_1 | File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 361, in execute
django_1 | self.check()
django_1 | File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 390, in check
django_1 | include_deployment_checks=include_deployment_checks,
django_1 | File "/usr/local/lib/python3.7/site-packages/django/core/management/commands/migrate.py", line 65, in _run_checks
django_1 | issues.extend(super()._run_checks(**kwargs))
django_1 | File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 377, in _run_checks
django_1 | return checks.run_checks(**kwargs)
django_1 | File "/usr/local/lib/python3.7/site-packages/django/core/checks/registry.py", line 72, in run_checks
django_1 | new_errors = check(app_configs=app_configs)
django_1 | File "/usr/local/lib/python3.7/site-packages/django/core/checks/urls.py", line 40, in check_url_namespaces_unique
django_1 | all_namespaces = _load_all_namespaces(resolver)
django_1 | File "/usr/local/lib/python3.7/site-packages/django/core/checks/urls.py", line 57, in _load_all_namespaces
django_1 | url_patterns = getattr(resolver, 'url_patterns', [])
django_1 | File "/usr/local/lib/python3.7/site-packages/django/utils/functional.py", line 80, in __get__
django_1 | res = instance.__dict__[self.name] = self.func(instance)
django_1 | File "/usr/local/lib/python3.7/site-packages/django/urls/resolvers.py", line 579, in url_patterns
django_1 | patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
django_1 | File "/usr/local/lib/python3.7/site-packages/django/utils/functional.py", line 80, in __get__
django_1 | res = instance.__dict__[self.name] = self.func(instance)
django_1 | File "/usr/local/lib/python3.7/site-packages/django/urls/resolvers.py", line 572, in urlconf_module
django_1 | return import_module(self.urlconf_name)
django_1 | File "/usr/local/lib/python3.7/importlib/__init__.py", line 127, in import_module
django_1 | return _bootstrap._gcd_import(name[level:], package, level)
django_1 | File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
django_1 | File "<frozen importlib._bootstrap>", line 983, in _find_and_load
django_1 | File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
django_1 | File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
django_1 | File "<frozen importlib._bootstrap_external>", line 728, in exec_module
django_1 | File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
django_1 | File "/app/config/urls.py", line 8, in <module>
django_1 | from myapp.users.views import login_view, set_password_view
django_1 | File "/app/myapp/users/views.py", line 24, in <module>
django_1 | from myapp.users.forms import (
django_1 | File "/app/myapp/users/forms.py", line 328, in <module>
django_1 | class InviteForm(forms.Form):
django_1 | File "/app/myapp/users/forms.py", line 331, in InviteForm
django_1 | required=False)
django_1 | File "/usr/local/lib/python3.7/site-packages/django/forms/fields.py", line 767, in __init__
django_1 | self.choices = choices
django_1 | File "/usr/local/lib/python3.7/site-packages/django/forms/fields.py", line 784, in _set_choices
django_1 | value = list(value)
django_1 | File "/usr/local/lib/python3.7/site-packages/django/db/models/query.py", line 274, in __iter__
django_1 | self._fetch_all()
django_1 | File "/usr/local/lib/python3.7/site-packages/django/db/models/query.py", line 1242, in _fetch_all
django_1 | self._result_cache = list(self._iterable_class(self))
django_1 | File "/usr/local/lib/python3.7/site-packages/django/db/models/query.py", line 144, in __iter__
django_1 | return compiler.results_iter(tuple_expected=True, chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)
django_1 | File "/usr/local/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 1052, in results_iter
django_1 | results = self.execute_sql(MULTI, chunked_fetch=chunked_fetch, chunk_size=chunk_size)
django_1 | File "/usr/local/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 1100, in execute_sql
django_1 | cursor.execute(sql, params)
django_1 | File "/usr/local/lib/python3.7/site-packages/django/db/backends/utils.py", line 99, in execute
django_1 | return super().execute(sql, params)
django_1 | File "/usr/local/lib/python3.7/site-packages/django/db/backends/utils.py", line 67, in execute
django_1 | return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
django_1 | File "/usr/local/lib/python3.7/site-packages/django/db/backends/utils.py", line 76, in _execute_with_wrappers
django_1 | return executor(sql, params, many, context)
django_1 | File "/usr/local/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute
django_1 | return self.cursor.execute(sql, params)
django_1 | File "/usr/local/lib/python3.7/site-packages/django/db/utils.py", line 89, in __exit__
django_1 | raise dj_exc_value.with_traceback(traceback) from exc_value
django_1 | File "/usr/local/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute
django_1 | return self.cursor.execute(sql, params)
django_1 | django.db.utils.ProgrammingError: relation "users_user" does not exist
django_1 | LINE 1: SELECT "users_user"."email" FROM "users_user" ORDER BY "user...
django_1 | ^
django_1 |
myapp_django_1 exited with code 1
我也试过了运行
docker-compose -f local.yml run django python manage.py migrate
首先,我得到了同样的 django 错误。
如果您需要其他文件中的代码,请发表评论,然后我会更新此问题内容。
更新
这是可能导致问题的代码片段。
user/forms.py
class EmailListField(forms.MultipleChoiceField):
def validate(self, value):
if self.required and not value:
raise forms.ValidationError(self.error_messages['required'], code=['required'])
email_validator = EmailValidator()
for val in value:
try:
email_validator(val)
except forms.ValidationError:
raise forms.ValidationError(
self.error_messages['invalid_choice'],
code='invalid_choice',
params={'value': val}
)
class InviteForm(forms.Form):
emails = EmailListField(choices=User.objects.all().values_list('email'),
widget=forms.SelectMultiple(),
required=False)
groups = forms.ModelMultipleChoiceField(queryset=Group.objects.none(), required=False)
file = forms.FileField(required=False)
def __init__(self, *args, **kwargs):
from_user = kwargs.pop('from_user')
super().__init__(*args, **kwargs)
self.fields['groups'].queryset = Group.objects.filter(company=from_user.profile.company)
self.from_user = from_user
def clean(self):
if not (self.cleaned_data['emails'] or self.cleaned_data['file']):
raise forms.ValidationError('Wprowadź adresy w polu tekstowy lub prześlij plik')
return self.cleaned_data
您可以尝试使用 ModelMultipleChoiceField
(https://docs.djangoproject.com/en/2.2/ref/forms/fields/#django.forms.ModelMultipleChoiceField) 代替 MultipleChoiceField
,然后在 EmailListField
中将 choices
更改为 queryset
,即
class EmailListField(forms.ModelMultipleChoiceField):
def validate(self, value): (...)
class InviteForm(forms.Form):
emails = EmailListField(queryset=User.objects.all().values_list('email'),
widget=forms.SelectMultiple(),
required=False)
(...)
我在我的项目中使用 Django Cookiecutter 模板,当我使用 docker 构建 docker 图像时,一切都很好,但是当我执行
docker-compose -f local.yml up
我得到这个输出
postgres_1 | This user must also own the server process.
postgres_1 |
postgres_1 | The database cluster will be initialized with locale "en_US.utf8".
postgres_1 | The default database encoding has accordingly been set to "UTF8".
postgres_1 | The default text search configuration will be set to "english".
postgres_1 |
postgres_1 | Data page checksums are disabled.
postgres_1 |
postgres_1 | fixing permissions on existing directory /var/lib/postgresql/data ... ok
postgres_1 | creating subdirectories ... ok
postgres_1 | selecting default max_connections ... 100
postgres_1 | selecting default shared_buffers ... 128MB
postgres_1 | selecting default timezone ... Etc/UTC
postgres_1 | selecting dynamic shared memory implementation ... posix
postgres_1 | creating configuration files ... ok
postgres_1 | running bootstrap script ... ok
mailhog_1 | 2020/02/22 16:26:28 Using in-memory storage
mailhog_1 | 2020/02/22 16:26:28 [SMTP] Binding to address: 0.0.0.0:1025
mailhog_1 | 2020/02/22 16:26:28 Serving under http://0.0.0.0:8025/
mailhog_1 | [HTTP] Binding to address: 0.0.0.0:8025
mailhog_1 | Creating API v1 with WebPath:
mailhog_1 | Creating API v2 with WebPath:
django_1 | Waiting for PostgreSQL to become available...
postgres_1 | performing post-bootstrap initialization ... ok
postgres_1 | syncing data to disk ... ok
postgres_1 |
postgres_1 | Success. You can now start the database server using:
postgres_1 |
postgres_1 | pg_ctl -D /var/lib/postgresql/data -l logfile start
postgres_1 |
postgres_1 |
postgres_1 | WARNING: enabling "trust" authentication for local connections
postgres_1 | You can change this by editing pg_hba.conf or using the option -A, or
postgres_1 | --auth-local and --auth-host, the next time you run initdb.
postgres_1 | waiting for server to start....2020-02-22 16:26:29.864 UTC [42] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432"
postgres_1 | 2020-02-22 16:26:29.876 UTC [43] LOG: database system was shut down at 2020-02-22 16:26:29 UTC
postgres_1 | 2020-02-22 16:26:29.880 UTC [42] LOG: database system is ready to accept connections
postgres_1 | done
postgres_1 | server started
django_1 | Waiting for PostgreSQL to become available...
postgres_1 | CREATE DATABASE
postgres_1 |
postgres_1 |
postgres_1 | /usr/local/bin/docker-entrypoint.sh: ignoring /docker-entrypoint-initdb.d/*
postgres_1 |
postgres_1 | 2020-02-22 16:26:30.416 UTC [42] LOG: received fast shutdown request
postgres_1 | waiting for server to shut down....2020-02-22 16:26:30.417 UTC [42] LOG: aborting any active transactions
postgres_1 | 2020-02-22 16:26:30.421 UTC [42] LOG: background worker "logical replication launcher" (PID 49) exited with exit code 1
postgres_1 | 2020-02-22 16:26:30.423 UTC [44] LOG: shutting down
postgres_1 | 2020-02-22 16:26:30.432 UTC [42] LOG: database system is shut down
postgres_1 | done
postgres_1 | server stopped
postgres_1 |
postgres_1 | PostgreSQL init process complete; ready for start up.
postgres_1 |
postgres_1 | 2020-02-22 16:26:30.535 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432
postgres_1 | 2020-02-22 16:26:30.535 UTC [1] LOG: listening on IPv6 address "::", port 5432
postgres_1 | 2020-02-22 16:26:30.537 UTC [1] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432"
postgres_1 | 2020-02-22 16:26:30.548 UTC [60] LOG: database system was shut down at 2020-02-22 16:26:30 UTC
postgres_1 | 2020-02-22 16:26:30.552 UTC [1] LOG: database system is ready to accept connections
django_1 | PostgreSQL is available
postgres_1 | 2020-02-22 16:26:32.030 UTC [68] ERROR: relation "users_user" does not exist at character 34
postgres_1 | 2020-02-22 16:26:32.030 UTC [68] STATEMENT: SELECT "users_user"."email" FROM "users_user" ORDER BY "users_user"."email" ASC
django_1 | Traceback (most recent call last):
django_1 | File "/usr/local/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute
django_1 | return self.cursor.execute(sql, params)
django_1 | psycopg2.errors.UndefinedTable: relation "users_user" does not exist
django_1 | LINE 1: SELECT "users_user"."email" FROM "users_user" ORDER BY "user...
django_1 | ^
django_1 |
django_1 |
django_1 | The above exception was the direct cause of the following exception:
django_1 |
django_1 | Traceback (most recent call last):
django_1 | File "manage.py", line 30, in <module>
django_1 | execute_from_command_line(sys.argv)
django_1 | File "/usr/local/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line
django_1 | utility.execute()
django_1 | File "/usr/local/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute
django_1 | self.fetch_command(subcommand).run_from_argv(self.argv)
django_1 | File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 323, in run_from_argv
django_1 | self.execute(*args, **cmd_options)
django_1 | File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 361, in execute
django_1 | self.check()
django_1 | File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 390, in check
django_1 | include_deployment_checks=include_deployment_checks,
django_1 | File "/usr/local/lib/python3.7/site-packages/django/core/management/commands/migrate.py", line 65, in _run_checks
django_1 | issues.extend(super()._run_checks(**kwargs))
django_1 | File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 377, in _run_checks
django_1 | return checks.run_checks(**kwargs)
django_1 | File "/usr/local/lib/python3.7/site-packages/django/core/checks/registry.py", line 72, in run_checks
django_1 | new_errors = check(app_configs=app_configs)
django_1 | File "/usr/local/lib/python3.7/site-packages/django/core/checks/urls.py", line 40, in check_url_namespaces_unique
django_1 | all_namespaces = _load_all_namespaces(resolver)
django_1 | File "/usr/local/lib/python3.7/site-packages/django/core/checks/urls.py", line 57, in _load_all_namespaces
django_1 | url_patterns = getattr(resolver, 'url_patterns', [])
django_1 | File "/usr/local/lib/python3.7/site-packages/django/utils/functional.py", line 80, in __get__
django_1 | res = instance.__dict__[self.name] = self.func(instance)
django_1 | File "/usr/local/lib/python3.7/site-packages/django/urls/resolvers.py", line 579, in url_patterns
django_1 | patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
django_1 | File "/usr/local/lib/python3.7/site-packages/django/utils/functional.py", line 80, in __get__
django_1 | res = instance.__dict__[self.name] = self.func(instance)
django_1 | File "/usr/local/lib/python3.7/site-packages/django/urls/resolvers.py", line 572, in urlconf_module
django_1 | return import_module(self.urlconf_name)
django_1 | File "/usr/local/lib/python3.7/importlib/__init__.py", line 127, in import_module
django_1 | return _bootstrap._gcd_import(name[level:], package, level)
django_1 | File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
django_1 | File "<frozen importlib._bootstrap>", line 983, in _find_and_load
django_1 | File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
django_1 | File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
django_1 | File "<frozen importlib._bootstrap_external>", line 728, in exec_module
django_1 | File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
django_1 | File "/app/config/urls.py", line 8, in <module>
django_1 | from myapp.users.views import login_view, set_password_view
django_1 | File "/app/myapp/users/views.py", line 24, in <module>
django_1 | from myapp.users.forms import (
django_1 | File "/app/myapp/users/forms.py", line 328, in <module>
django_1 | class InviteForm(forms.Form):
django_1 | File "/app/myapp/users/forms.py", line 331, in InviteForm
django_1 | required=False)
django_1 | File "/usr/local/lib/python3.7/site-packages/django/forms/fields.py", line 767, in __init__
django_1 | self.choices = choices
django_1 | File "/usr/local/lib/python3.7/site-packages/django/forms/fields.py", line 784, in _set_choices
django_1 | value = list(value)
django_1 | File "/usr/local/lib/python3.7/site-packages/django/db/models/query.py", line 274, in __iter__
django_1 | self._fetch_all()
django_1 | File "/usr/local/lib/python3.7/site-packages/django/db/models/query.py", line 1242, in _fetch_all
django_1 | self._result_cache = list(self._iterable_class(self))
django_1 | File "/usr/local/lib/python3.7/site-packages/django/db/models/query.py", line 144, in __iter__
django_1 | return compiler.results_iter(tuple_expected=True, chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)
django_1 | File "/usr/local/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 1052, in results_iter
django_1 | results = self.execute_sql(MULTI, chunked_fetch=chunked_fetch, chunk_size=chunk_size)
django_1 | File "/usr/local/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 1100, in execute_sql
django_1 | cursor.execute(sql, params)
django_1 | File "/usr/local/lib/python3.7/site-packages/django/db/backends/utils.py", line 99, in execute
django_1 | return super().execute(sql, params)
django_1 | File "/usr/local/lib/python3.7/site-packages/django/db/backends/utils.py", line 67, in execute
django_1 | return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
django_1 | File "/usr/local/lib/python3.7/site-packages/django/db/backends/utils.py", line 76, in _execute_with_wrappers
django_1 | return executor(sql, params, many, context)
django_1 | File "/usr/local/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute
django_1 | return self.cursor.execute(sql, params)
django_1 | File "/usr/local/lib/python3.7/site-packages/django/db/utils.py", line 89, in __exit__
django_1 | raise dj_exc_value.with_traceback(traceback) from exc_value
django_1 | File "/usr/local/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute
django_1 | return self.cursor.execute(sql, params)
django_1 | django.db.utils.ProgrammingError: relation "users_user" does not exist
django_1 | LINE 1: SELECT "users_user"."email" FROM "users_user" ORDER BY "user...
django_1 | ^
django_1 |
myapp_django_1 exited with code 1
我也试过了运行
docker-compose -f local.yml run django python manage.py migrate
首先,我得到了同样的 django 错误。
如果您需要其他文件中的代码,请发表评论,然后我会更新此问题内容。
更新
这是可能导致问题的代码片段。
user/forms.py
class EmailListField(forms.MultipleChoiceField):
def validate(self, value):
if self.required and not value:
raise forms.ValidationError(self.error_messages['required'], code=['required'])
email_validator = EmailValidator()
for val in value:
try:
email_validator(val)
except forms.ValidationError:
raise forms.ValidationError(
self.error_messages['invalid_choice'],
code='invalid_choice',
params={'value': val}
)
class InviteForm(forms.Form):
emails = EmailListField(choices=User.objects.all().values_list('email'),
widget=forms.SelectMultiple(),
required=False)
groups = forms.ModelMultipleChoiceField(queryset=Group.objects.none(), required=False)
file = forms.FileField(required=False)
def __init__(self, *args, **kwargs):
from_user = kwargs.pop('from_user')
super().__init__(*args, **kwargs)
self.fields['groups'].queryset = Group.objects.filter(company=from_user.profile.company)
self.from_user = from_user
def clean(self):
if not (self.cleaned_data['emails'] or self.cleaned_data['file']):
raise forms.ValidationError('Wprowadź adresy w polu tekstowy lub prześlij plik')
return self.cleaned_data
您可以尝试使用 ModelMultipleChoiceField
(https://docs.djangoproject.com/en/2.2/ref/forms/fields/#django.forms.ModelMultipleChoiceField) 代替 MultipleChoiceField
,然后在 EmailListField
中将 choices
更改为 queryset
,即
class EmailListField(forms.ModelMultipleChoiceField):
def validate(self, value): (...)
class InviteForm(forms.Form):
emails = EmailListField(queryset=User.objects.all().values_list('email'),
widget=forms.SelectMultiple(),
required=False)
(...)