我有以下型号:
class Model1(models.Model):
Field1 = models.CharField(max_length=200)
class Model2(models.Model)
Field2 = models.ForeignKey(Model1, on_delete=models.CASCADE)
Field3 = models.ForeignKey(User, on_delete=models.CASCADE)
Email = models.EmailField(null=TRUE)
这是forms.py
:
class Model1Form(ModelForm):
class Meta:
model = Model1
fields = ['Field1']
class Model2Form(ModelForm):
class Meta:
model = Model2
fields = ['email']
Model2Field2Formset = inlineformset_factory(Model1, Model2, form=Model2Form, extra=1)
Model2Field3Formset = inlineformset_factory(User, Model2, form=Model2Form, extra=1)
这是views.py
:
class NewEntry(CreateView):
model = Model1
fields = ['Field1']
success_url = reverse_lazy('voting:index')
def get_context_data(self, **kwargs):
data = super().get_context_data(**kwargs)
if self.request.POST:
data['model2_field2'] = Model2Field2Formset(self.request.POST)
data['model2_field3'] = Model2Field3Formset(self.request.POST)
else:
data['model2_field2'] = Model2Field2Formset()
data['model2_field3'] = Model2Field3Formset()
return data
def form_valid(self, form):
context = self.get_context_data()
model2_field2 = context['model2_field2']
model2_field3 = context['model2_field3']
with transaction.atomic():
self.object = form.save()
if model2_field2.is_valid() and model2_field3.is_valid():
model2_field2.instance = self.object
model2_field2.save()
model2_field3.instance = self.object
model2_field3.save()
return super().form_valid(form)
我正在尝试为Model1
,Field1
创建一个条目。然后,使用inlineformset_factory
在email
中创建多个Model2
条目,每个条目与相同的Field1_id
条目相关联,并且每个条目user_id
email
在表单中。
但我得到"Model2.user" must be a "User" instance
。 model2_field3.save()
代码行上的错误。
如果我注释掉该行没有错误,则条目会按预期保存,但Field3
列仍为NULL
。
这是错误的追溯:
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/polls/newpoll/
Django Version: 2.0.5
Python Version: 3.5.2
Installed Applications:
['secvot',
'accounts.apps.AccountsConfig',
'voting.apps.VotingConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles']
Installed 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']
Traceback:
File "/home/kostis/.virtualenvs/secvote/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner
35. response = get_response(request)
File "/home/kostis/.virtualenvs/secvote/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
128. response = self.process_exception_by_middleware(e, request)
File "/home/kostis/.virtualenvs/secvote/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
126. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/kostis/.virtualenvs/secvote/lib/python3.5/site-packages/django/views/generic/base.py" in view
69. return self.dispatch(request, *args, **kwargs)
File "/home/kostis/.virtualenvs/secvote/lib/python3.5/site-packages/django/views/generic/base.py" in dispatch
89. return handler(request, *args, **kwargs)
File "/home/kostis/.virtualenvs/secvote/lib/python3.5/site-packages/django/views/generic/edit.py" in post
172. return super().post(request, *args, **kwargs)
File "/home/kostis/.virtualenvs/secvote/lib/python3.5/site-packages/django/views/generic/edit.py" in post
142. return self.form_valid(form)
File "/home/kostis/PycharmProjects/secvot/voting/views.py" in form_valid
110. eligible_voters_user.save()
File "/home/kostis/.virtualenvs/secvote/lib/python3.5/site-packages/django/forms/models.py" in save
670. return self.save_existing_objects(commit) + self.save_new_objects(commit)
File "/home/kostis/.virtualenvs/secvote/lib/python3.5/site-packages/django/forms/models.py" in save_new_objects
804. self.new_objects.append(self.save_new(form, commit=commit))
File "/home/kostis/.virtualenvs/secvote/lib/python3.5/site-packages/django/forms/models.py" in save_new
943. setattr(form.instance, self.fk.name, self.instance)
File "/home/kostis/.virtualenvs/secvote/lib/python3.5/site-packages/django/db/models/fields/related_descriptors.py" in __set__
197. self.field.remote_field.model._meta.object_name,
Exception Type: ValueError at /polls/newpoll/
Exception Value: Cannot assign "<Poll: asdefrgrs>": "EligibleVoters.user" must be a "User" instance.
只是旁注,EligibleVoters
模型在我的问题中是相应的Model2
。我重命名并删除了一些字段以使我的问题更简单。
这就是我想要实现的目标:
基本上是一个带有两个外键的模型(两个父模型)。
创建一个Field1
条目,然后使用inlineformset_factory
在与email
条目相关联的Model2
条目中创建多个Field1
条目以及相应的user_id
每个email
。
答案 0 :(得分:1)
在form_valid()
方法中,您将同一self.object
分配给model2_field2
和model2_field3
,这可能不正确,因为它们是不同模型的外键。您很可能尝试将Model1
的实例分配给model2_field3
,您应该在该字段中为User
分配add_filter('loop_shop_columns', 'loop_columns');
if (!function_exists('loop_columns')) {
function loop_columns() {
if ( is_product_category('torres-elevadoras')) { // wanted product category
return 2;
}
}
的实例。