保存表单时,我遇到以下错误:“”需要为字段“surveythread”设置一个值,然后才能使用此多对多关系。
模型。py:
class SurveyResult(models.Model):
stay = models.OneToOneField(Stay, related_name='survey')
created = models.DateTimeField(default=datetime.now)
vote = models.BooleanField(default=False)
vote_service = models.BooleanField(default=False)
comment = models.TextField(blank=True, null=True)
def getThreads(self):
return SurveyThread.objects.filter(parent_survey = self)
threads = property(getThreads)
def __unicode__(self):
return self.vote and 'Good' or 'Bad'
class Meta:
get_latest_by = '-created'
class SurveyThread(models.Model):
survey = models.ManyToManyField(SurveyResult, related_name='parent_survey')
email = models.EmailField(max_length=200)
comment = models.TextField(blank=True, null=True)
views.py:
survey_list = SurveyResult.objects.filter(stay__guest__user=request.user) \
.select_related('stay', 'stay__guest')
forms = {}
for survey in survey_list:
forms[survey] = SurveyThreadForm(data=request.POST or None, survey=survey)
if forms[survey].is_valid():
instance = forms[survey].save()
return redirect('.')
forms.py
class SurveyThreadForm(forms.Form):
comment = forms.CharField(required=False, widget=forms.Textarea)
def __init__(self, *args, **kwargs):
self.survey = kwargs.pop('survey', None)
if not self.survey:
raise NotImplementedError("SurveyResult object is required at this moment")
super(SurveyThreadForm, self).__init__(*args, **kwargs)
self.fields['comment'].label = "Message to send to guest:"
def save(self, commit=True):
s = SurveyThread()
s.survey = self.survey
s.email = "test@test.com"
s.comment = self.cleaned_data['comment']
if commit:
s.save()
return s
错误消息:
ValueError at /
"<SurveyThread: SurveyThread object>" needs to have a value for field "surveythread" before this many-to-many relationship can be used.
Request Method: POST
Request URL: http://127.0.0.1:8000/
Django Version: 1.5.1
Exception Type: ValueError
Exception Value:
"<SurveyThread: SurveyThread object>" needs to have a value for field "surveythread" before this many-to-many relationship can be used.
Exception Location: /Users/tlovett1/.virtualenvs/guestretain/lib/python2.7/site-packages/django/db/models/fields/related.py in __init__, line 586
Python Executable: /Users/tlovett1/.virtualenvs/guestretain/bin/python
Python Version: 2.7.2
Python Path:
['/Users/tlovett1/guestretain',
'/Users/tlovett1/.virtualenvs/guestretain/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg',
'/Users/tlovett1/.virtualenvs/guestretain/lib/python2.7/site-packages/pip-1.3.1-py2.7.egg',
'/Users/tlovett1/.virtualenvs/guestretain/lib/python27.zip',
'/Users/tlovett1/.virtualenvs/guestretain/lib/python2.7',
'/Users/tlovett1/.virtualenvs/guestretain/lib/python2.7/plat-darwin',
'/Users/tlovett1/.virtualenvs/guestretain/lib/python2.7/plat-mac',
'/Users/tlovett1/.virtualenvs/guestretain/lib/python2.7/plat-mac/lib-scriptpackages',
'/Users/tlovett1/.virtualenvs/guestretain/Extras/lib/python',
'/Users/tlovett1/.virtualenvs/guestretain/lib/python2.7/lib-tk',
'/Users/tlovett1/.virtualenvs/guestretain/lib/python2.7/lib-old',
'/Users/tlovett1/.virtualenvs/guestretain/lib/python2.7/lib-dynload',
'/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7',
'/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin',
'/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk',
'/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac',
'/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages',
'/Users/tlovett1/.virtualenvs/guestretain/lib/python2.7/site-packages',
'/Users/tlovett1/.virtualenvs/guestretain/lib/python2.7/site-packages/PIL']
Server time: Sun, 7 Jul 2013 10:22:55 -0500
回溯:
Traceback Switch to copy-and-paste view
/Users/tlovett1/.virtualenvs/guestretain/lib/python2.7/site-packages/django/core/handlers/base.py in get_response
response = callback(request, *callback_args, **callback_kwargs) ...
▶ Local vars
/Users/tlovett1/guestretain/retain/apps/profiles/utils.py in _wrapped_view
return view_func(request, *args, **kwargs) ...
▶ Local vars
/Users/tlovett1/.virtualenvs/guestretain/lib/python2.7/site-packages/endless_pagination/decorators.py in decorated
return view(request, *args, **kwargs) ...
▶ Local vars
/Users/tlovett1/guestretain/retain/apps/dashboard/views.py in dashboard
instance = forms[survey].save() ...
▶ Local vars
/Users/tlovett1/guestretain/retain/apps/surveys/forms.py in save
s.survey = self.survey ...
▶ Local vars
/Users/tlovett1/.virtualenvs/guestretain/lib/python2.7/site-packages/django/db/models/fields/related.py in __set__
manager = self.__get__(instance) ...
▶ Local vars
/Users/tlovett1/.virtualenvs/guestretain/lib/python2.7/site-packages/django/db/models/fields/related.py in __get__
through=self.field.rel.through, ...
▶ Local vars
/Users/tlovett1/.virtualenvs/guestretain/lib/python2.7/site-packages/django/db/models/fields/related.py in __init__
(instance, source_field_name)) ...
▶ Local vars
我是Django和Python的新手。如果需要,我可以发布调试跟踪或迁移文件,但我觉得这是一个简单的修复。显然,关键是我想为每个调查结果保存多个调查线程。
谢谢!
这部分代码以形式显示。py
,您正在将SurveyThread
对象上的survey
字段设置为None
,但根据您的模型,它不允许是
:None
。py
def save(self, commit=True):
s = SurveyThread()
s.survey = None ### This is the problem
s.email = "test@test.com"
s.comment = self.cleaned_data['comment']
if commit:
s.save()
return s
您必须先将survey
设置为SurveyResult
对象,然后才能保存它,或者允许它在模型中为None
。
我想你应该改成这样:
s.survey = self.survey
好的,代码有点混乱,我相信你最好用ModelForm
来解决你的问题。在我看来,问题实际上是这句话:
s.survey = self.survey
由于s
对象尚未写入数据库,因此访问它的survey
许多字段可能会产生问题。如果您想将同一组调查从self
复制到s
中,您应该像这样迭代:
如果这会产生相同的错误,请先尝试执行s.save()
,然后再复制项目:
s.save()
for item in self.survey:
s.survey.add(item)
您的代码可能会保持这样:
def save(self, commit=True):
s = SurveyThread()
# these fields aren't problematic
s.email = "test@test.com"
s.comment = self.cleaned_data['comment']
# you can add s.save() here to remove problems associated with object
# not yet persisted
# s.save()
for item in self.survey:
s.survey.add(item)
if commit:
s.save()
return s
我可以看到你有一个如果提交:
来持久化对象,所以试着容纳代码来利用它。如果我的答案的第一个版本有效,那么你可以在最后使用s.save()
,如果第二个版本有效,那么你必须稍微调整代码以坚持提交
值。
希望这有帮助!
我目前有以下3种型号 现在我正试图以这种方式将值插入 我得到了错误 我看了这篇文章,但仍然无法找出问题所在。对此,如果有任何建议,我将不胜感激。
我正在尝试将团队添加到数据库中,但出现此错误。看了类似的问题,但没有一个解决了我的问题。(我是Django的新手) 我的代码看起来像: 形式。派克 模型。派克 意见。派克 当我尝试不使用表单时,例如仅使用标题字段: 它是成功地添加它。我在这里做错了什么?
我正在做一个像电子商务网站这样的项目。到目前为止,一切正常,但如果用户购物车/包中没有任何内容,则会发生错误。我试过保存方法,但我想我做错了什么。有人能帮我解决吗 views.py 模型。派克 错误和回溯 先谢谢你。
问题内容: 考虑以下模型和形式: 当你查看ToppingForm时,它使你可以选择浇头所用的披萨,而一切都太花哨了。 我的问题是:如何为披萨定义一个ModelForm,让我利用披萨和馅料之间的多对多关系,并让我选择披萨上的馅料? 问题答案: 我想你会在这里新添加到你,并手动链接,表单字段与模型领域,如Django会不会为你做自动。 以下代码段可能会有所帮助: 这然后可以使用无处不在,甚至在admi
我在Django中创建了一个数据模型,它具有多对一关系(N个主题对1个用户),如下所示: 来自django。db从django导入模型。contrib。auth。模型导入用户 当我尝试在“管理”页面中加载数据模型时,出现以下错误: 我错过了数据模型中的什么吗? 谢谢。
问题内容: 这可能无关紧要,只是想问一下, 如果一个对象从视图传递到模板,并且在模板中我将能够查询许多字段 型号代码: 观看次数: 在模板中可以解码多对多字段,因为我们正在传递对象 谢谢.. 问题答案: 通常,您可以通过django模板系统中的路径来跟踪任何不带参数的属性或方法调用。 对于上面的视图代码,类似 应该做您期望的。 (我无法完全从代码示例中找出具体细节,但希望这会阐明您可以从模板中学到