我有两个模型,我正在做一个自定义表单,这样我就可以查看表单并将其从我的 html 保存到数据库中。但是当我尝试保存时,我得到了这个错误。
追溯
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8008/
Django Version: 1.4
Python Version: 2.7.3
Installed Applications:
('django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'SecondBlog.blog',
'django.contrib.admin',
'django.contrib.admindocs')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware')
Traceback:
File "c:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "f:\apt3\SecondBlog\SecondBlog\blog\views.py" in home
10. if form.is_valid():
File "c:\Python27\lib\site-packages\django\forms\forms.py" in is_valid
124. return self.is_bound and not bool(self.errors)
File "c:\Python27\lib\site-packages\django\forms\forms.py" in _get_errors
115. self.full_clean()
File "c:\Python27\lib\site-packages\django\forms\forms.py" in full_clean
272. self._post_clean()
File "c:\Python27\lib\site-packages\django\forms\models.py" in _post_clean
309. self.instance = construct_instance(self, self.instance, opts.fields, opts.exclude)
File "c:\Python27\lib\site-packages\django\forms\models.py" in construct_instance
51. f.save_form_data(instance, cleaned_data[f.name])
File "c:\Python27\lib\site-packages\django\db\models\fields\__init__.py" in save_form_data
454. setattr(instance, self.name, data)
File "c:\Python27\lib\site-packages\django\db\models\fields\related.py" in __set__
366. self.field.name, self.field.rel.to._meta.object_name))
Exception Type: ValueError at /
Exception Value: Cannot assign "u'Sasa'": "Book.author" must be a "Author" instance.
模型.py
class Author(models.Model):
name = models.CharField(max_length = 30)
class Book(models.Model):
author = models.ForeignKey(Author)
title = models.CharField(max_length = 100)
def __unicode__(self):
return '%s' % (self.title)
表格.py
class CustomForm(ModelForm):
author = forms.CharField()
def save(self, commit=True):
author = Author.objects.get_or_create(name=self.cleaned_data['author'])
instance = super(CustomForm, self).save(commit=commit)
instance.author = author
if commit:
instance.save()
return instance
class Meta:
model = Book
fields = ('author','title',)
视图.py
def home(request):
if request.method == 'POST':
form = CustomForm(request.POST)
if form.is_valid():
print "all validated"
form.save()
return HttpResponseRedirect('index.html')
else:
print "failed"
else:
form = CustomForm()
variables = RequestContext(request, {'form' : form})
return render_to_response('index.html', variables)
非常感谢。