我创建一个博客,并希望添加创建视图,这是我的形式
def create_blog_view(request):
if request.method == 'POST':
blog_form = BlogForm(request.POST)
if blog_form.is_valid():
new_form = blog_form.save(commit=False)
new_form.author = request.user
new_form.save()
return redirect('blog_list')
else:
print('its bog')
else:
blog_form = BlogForm()
return render(request, 'pages/create_blog.html', context={
'form': blog_form
})
这是我的模特
class Blog(models.Model):
title = models.CharField(max_length=100)
cover = models.ImageField(upload_to='blog_cover/')
description = models.CharField(max_length=200)
text = models.TextField()
author = models.ForeignKey(get_user_model(), on_delete=models.CASCADE)
active = models.BooleanField(default=False)
date_create = models.DateField(auto_now_add=True)
date_modified = models.DateField(auto_now=True)
def __str__(self):
return f'{self.title} : {self.author}'
def get_absolute_url(self):
return reverse('blog_detail', args=[self.id])
当我提交我的表单数据不保存我想要作者自动量化
if blog_form.is_valid():
new_form = blog_form.save(commit=False)
new_form.author = request.user
new_form.save()
return redirect('blog_list')
else:
print('bug is here')
我试过了,打印的错误在这里(当尝试从管理面板一切都是正确的)
1条答案
按热度按时间myss37ts1#
在您的
Blog
模型中有ImageField()
,因此您需要传递request.FILES,还需要在HTML表单中添加enctype="multipart/form-data"
,如下所示网站views.py
HTML表单