Django 表单包含来自 related_name 的 Many2Many 字段
Django form include Many2Many field from related_name
我有两个模型,有两个更新表单。
现在我想实现两件事:
- 能够编辑证书并设置使用该证书的所有服务器
- 能够更新服务器并设置在该服务器上使用的所有证书。
class Certificate(models.Model):
internal_name = models.CharField(max_length=1024)
pem_representation = models.TextField(unique=True)
servers = models.ManyToManyField(
Server, related_name='certificates', blank=True)
class Server(models.Model):
name = models.CharField(max_length=1024, unique=True)
class CertificateUpdateForm(forms.ModelForm):
class Meta:
model = models.Certificate
fields = ['internal_name', 'pem_representation', 'servers']
class ServerUpdateForm(forms.ModelForm):
class Meta:
model = models.Server
fields = ['name', 'certificates']
如果 ServerUpdateForm 中没有字段“证书”,我不会收到任何错误,但是当通过表单更新时,证书的更改无法识别。
我使用此代码得到的错误消息是:
Exception in thread django-main-thread:
Traceback (most recent call last):
File "/usr/lib64/python3.8/threading.py", line 932, in _bootstrap_inner
self.run()
File "/usr/lib64/python3.8/threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File " venv/lib64/python3.8/site-packages/django/utils/autoreload.py", line 53, in wrapper
fn(*args, **kwargs)
File " venv/lib64/python3.8/site-packages/django/core/management/commands/runserver.py", line 118, in inner_run
self.check(display_num_errors=True)
File " venv/lib64/python3.8/site-packages/django/core/management/base.py", line 392, in check
all_issues = checks.run_checks(
File " venv/lib64/python3.8/site-packages/django/core/checks/registry.py", line 70, in run_checks
new_errors = check(app_configs=app_configs, databases=databases)
File " venv/lib64/python3.8/site-packages/django/core/checks/urls.py", line 13, in check_url_config
return check_resolver(resolver)
File " venv/lib64/python3.8/site-packages/django/core/checks/urls.py", line 23, in check_resolver
return check_method()
File " venv/lib64/python3.8/site-packages/django/urls/resolvers.py", line 408, in check
for pattern in self.url_patterns:
File " venv/lib64/python3.8/site-packages/django/utils/functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File " venv/lib64/python3.8/site-packages/django/urls/resolvers.py", line 589, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File " venv/lib64/python3.8/site-packages/django/utils/functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File " venv/lib64/python3.8/site-packages/django/urls/resolvers.py", line 582, in urlconf_module
return import_module(self.urlconf_name)
File "/usr/lib64/python3.8/importlib/__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
File "<frozen importlib._bootstrap>", line 991, in _find_and_load
File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 783, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File " certmanager/certmanager/urls.py", line 26, in <module>
path('servers/', include('servers.urls')),
File " venv/lib64/python3.8/site-packages/django/urls/conf.py", line 34, in include
urlconf_module = import_module(urlconf_module)
File "/usr/lib64/python3.8/importlib/__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
File "<frozen importlib._bootstrap>", line 991, in _find_and_load
File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 783, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File " certmanager/servers/urls.py", line 3, in <module>
from . import views
File " certmanager/servers/views.py", line 9, in <module>
from . import forms, models
File " certmanager/servers/forms.py", line 12, in <module>
class ServerUpdateForm(forms.ModelForm):
File " venv/lib64/python3.8/site-packages/django/forms/models.py", line 268, in __new__
raise FieldError(message)
django.core.exceptions.FieldError: Unknown field(s) (certificates) specified for Server
如何更新两个对象的 M2M 关系?
所以我问了同样的问题 in a post on the Django forum 并得到了可行的建议。
为了提高可见度:
我覆盖了我使用的 UpdateView 的 post 方法,并在那里管理 Many2Many 关系。我还必须从 UpdateForm 中删除 'certificates' 字段,显然是因为它是一个异常。
这是我使用的完整 UpdateView class:
class ServerUpdate(PermissionRequiredMixin, generic.UpdateView):
model = models.Server
template_name = 'servers/update.html'
form_class = forms.ServerUpdateForm
queryset = models.Server.objects.all()
success_url = reverse_lazy('servers:server-index')
permission_required = ('servers.change_server')
def get_context_data(self, **kwargs):
context = super(ServerUpdate, self).get_context_data(**kwargs)
context['all_certificates'] = Certificate.objects.all()
context['selected_certificates'] = self.object.certificates.all()
return context
def post(self, request, *args, **kwargs):
selected_certificates = request.POST.getlist('certificates')
self.object = self.get_object()
self.object.certificates.set(selected_certificates)
return super().post(request, *args, **kwargs)
我有两个模型,有两个更新表单。 现在我想实现两件事:
- 能够编辑证书并设置使用该证书的所有服务器
- 能够更新服务器并设置在该服务器上使用的所有证书。
class Certificate(models.Model):
internal_name = models.CharField(max_length=1024)
pem_representation = models.TextField(unique=True)
servers = models.ManyToManyField(
Server, related_name='certificates', blank=True)
class Server(models.Model):
name = models.CharField(max_length=1024, unique=True)
class CertificateUpdateForm(forms.ModelForm):
class Meta:
model = models.Certificate
fields = ['internal_name', 'pem_representation', 'servers']
class ServerUpdateForm(forms.ModelForm):
class Meta:
model = models.Server
fields = ['name', 'certificates']
如果 ServerUpdateForm 中没有字段“证书”,我不会收到任何错误,但是当通过表单更新时,证书的更改无法识别。 我使用此代码得到的错误消息是:
Exception in thread django-main-thread:
Traceback (most recent call last):
File "/usr/lib64/python3.8/threading.py", line 932, in _bootstrap_inner
self.run()
File "/usr/lib64/python3.8/threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File " venv/lib64/python3.8/site-packages/django/utils/autoreload.py", line 53, in wrapper
fn(*args, **kwargs)
File " venv/lib64/python3.8/site-packages/django/core/management/commands/runserver.py", line 118, in inner_run
self.check(display_num_errors=True)
File " venv/lib64/python3.8/site-packages/django/core/management/base.py", line 392, in check
all_issues = checks.run_checks(
File " venv/lib64/python3.8/site-packages/django/core/checks/registry.py", line 70, in run_checks
new_errors = check(app_configs=app_configs, databases=databases)
File " venv/lib64/python3.8/site-packages/django/core/checks/urls.py", line 13, in check_url_config
return check_resolver(resolver)
File " venv/lib64/python3.8/site-packages/django/core/checks/urls.py", line 23, in check_resolver
return check_method()
File " venv/lib64/python3.8/site-packages/django/urls/resolvers.py", line 408, in check
for pattern in self.url_patterns:
File " venv/lib64/python3.8/site-packages/django/utils/functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File " venv/lib64/python3.8/site-packages/django/urls/resolvers.py", line 589, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File " venv/lib64/python3.8/site-packages/django/utils/functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File " venv/lib64/python3.8/site-packages/django/urls/resolvers.py", line 582, in urlconf_module
return import_module(self.urlconf_name)
File "/usr/lib64/python3.8/importlib/__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
File "<frozen importlib._bootstrap>", line 991, in _find_and_load
File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 783, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File " certmanager/certmanager/urls.py", line 26, in <module>
path('servers/', include('servers.urls')),
File " venv/lib64/python3.8/site-packages/django/urls/conf.py", line 34, in include
urlconf_module = import_module(urlconf_module)
File "/usr/lib64/python3.8/importlib/__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
File "<frozen importlib._bootstrap>", line 991, in _find_and_load
File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 783, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File " certmanager/servers/urls.py", line 3, in <module>
from . import views
File " certmanager/servers/views.py", line 9, in <module>
from . import forms, models
File " certmanager/servers/forms.py", line 12, in <module>
class ServerUpdateForm(forms.ModelForm):
File " venv/lib64/python3.8/site-packages/django/forms/models.py", line 268, in __new__
raise FieldError(message)
django.core.exceptions.FieldError: Unknown field(s) (certificates) specified for Server
如何更新两个对象的 M2M 关系?
所以我问了同样的问题 in a post on the Django forum 并得到了可行的建议。
为了提高可见度: 我覆盖了我使用的 UpdateView 的 post 方法,并在那里管理 Many2Many 关系。我还必须从 UpdateForm 中删除 'certificates' 字段,显然是因为它是一个异常。 这是我使用的完整 UpdateView class:
class ServerUpdate(PermissionRequiredMixin, generic.UpdateView):
model = models.Server
template_name = 'servers/update.html'
form_class = forms.ServerUpdateForm
queryset = models.Server.objects.all()
success_url = reverse_lazy('servers:server-index')
permission_required = ('servers.change_server')
def get_context_data(self, **kwargs):
context = super(ServerUpdate, self).get_context_data(**kwargs)
context['all_certificates'] = Certificate.objects.all()
context['selected_certificates'] = self.object.certificates.all()
return context
def post(self, request, *args, **kwargs):
selected_certificates = request.POST.getlist('certificates')
self.object = self.get_object()
self.object.certificates.set(selected_certificates)
return super().post(request, *args, **kwargs)