hii iam是Django的新手,所以iam在我的第一个博客(articals blog)上工作,因此我试图使用Django表单从模板中保存文章,但同时保存错误'bool'对象没有属性'_committed'iam搜索解决方案,但未找到任何解决方案。请帮助我。
Models.py:
class post(models.Model):
author = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE)
title = models.CharField(max_length=20)
discription=models.CharField(default=None ,max_length=100)
text = models.TextField(max_length=2000)
image=models.ImageField(upload_to="blog/",default=True,null=True,blank=True)
created_date = models.DateTimeField(default=timezone.now())
published_date=models.DateTimeField(blank=True , null=True)
def publish(self):
self.published_date=timezone.now()
self.save()
def __str__(self):
return self.title
forms.py:
from django import forms
from .models import post
class post_form(forms.ModelForm):
class Meta:
model=post
fields=[
'title','discription','text','image'
]
views.py:
def post_new(request,*args,**kwargs):
if request.method == 'POST':
form=post_form(request.POST,request.FILES)
if form.is_valid():
p=form.save(commit=False)
p.author=request.user
p.published_date=timezone.now()
p.save()
return redirect("/post_list")
else:
form = post_form()
context = {
'form': form
}
return render(request,'blog/post_new.html',context)
跟踪:
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/post_new
Django Version: 2.2.3
Python Version: 3.7.2
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'blog']
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 "C:\Users\lenovo\Envs\blogproject\lib\site-
packages\django\core\handlers\exception.py" in inner
34. response = get_response(request)
File "C:\Users\lenovo\Envs\blogproject\lib\site-
packages\django\core\handlers\base.py" in _get_response
115. response = self.process_exception_by_middleware(e,
request)
File "C:\Users\lenovo\Envs\blogproject\lib\site-
packages\django\core\handlers\base.py" in _get_response
113. response = wrapped_callback(request, *callback_args,
**callback_kwargs)
File "C:\Users\lenovo\Desktop\blogproject\mysite\blog\views.py" in
post_new
39. p.save()
File "C:\Users\lenovo\Envs\blogproject\lib\site-
packages\django\db\models\base.py" in save
741. force_update=force_update,
update_fields=update_fields)
File "C:\Users\lenovo\Envs\blogproject\lib\site-
packages\django\db\models\base.py" in save_base
779. force_update, using, update_fields,
File "C:\Users\lenovo\Envs\blogproject\lib\site-
packages\django\db\models\base.py" in _save_table
870. result = self._do_insert(cls._base_manager, using,
fields, update_pk, raw)
File "C:\Users\lenovo\Envs\blogproject\lib\site-
packages\django\db\models\base.py" in _do_insert
908. using=using, raw=raw)
File "C:\Users\lenovo\Envs\blogproject\lib\site-
packages\django\db\models\manager.py" in manager_method
82. return getattr(self.get_queryset(), name)(*args,
**kwargs)
File "C:\Users\lenovo\Envs\blogproject\lib\site-
packages\django\db\models\query.py" in _insert
1186. return
query.get_compiler(using=using).execute_sql(return_id)
File "C:\Users\lenovo\Envs\blogproject\lib\site-
packages\django\db\models\sql\compiler.py" in execute_sql
1334. for sql, params in self.as_sql():
File "C:\Users\lenovo\Envs\blogproject\lib\site-
packages\django\db\models\sql\compiler.py" in as_sql
1278. for obj in self.query.objs
File "C:\Users\lenovo\Envs\blogproject\lib\site-
packages\django\db\models\sql\compiler.py" in <listcomp>
1278. for obj in self.query.objs
File "C:\Users\lenovo\Envs\blogproject\lib\site-
packages\django\db\models\sql\compiler.py" in <listcomp>
1277. [self.prepare_value(field, self.pre_save_val(field,
obj)) for field in fields]
File "C:\Users\lenovo\Envs\blogproject\lib\site-
packages\django\db\models\sql\compiler.py" in pre_save_val
1228. return field.pre_save(obj, add=True)
File "C:\Users\lenovo\Envs\blogproject\lib\site-
packages\django\db\models\fields\files.py" in pre_save
286. if file and not file._committed:
Exception Type: AttributeError at /post_new
Exception Value: 'bool' object has no attribute '_committed'
答案 0 :(得分:0)
据我所知,您的forms.py或views.py中没有错误。
我看到从未设置author
字段。由于它不能为空,因此将产生一个错误。因此,在保存之前将null=True
添加到作者字段或在表单中设置作者。我想您想选择第二种选择。
我还注意到2个较小的东西,这可能会更容易。查看created_date
和published_date
class post(models.Model):
author = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE)
title = models.CharField(max_length=20)
discription=models.CharField(default=None ,max_length=100)
text = models.TextField(max_length=2000)
image=models.ImageField(upload_to="blog/",default=True,null=True,blank=True)
created_date = models.DateTimeField(auto_now_add=True)
published_date=models.DateTimeField(auto_now=True)
def __str__(self):
return self.title
答案 1 :(得分:0)
由于这里的default=True
,您看到此特定错误:
class post(models.Model):
...
image=models.ImageField(upload_to="blog/",default=True,null=True,blank=True)
从您发布的代码来看,为什么使用默认值并不明显,但是我猜测是您没有选择文件或文件数据未发送,因为您的表单未设置enctype="multipart/form-data"
。