表单不保存在django中

qgelzfjb  于 2023-01-21  发布在  Go
关注(0)|答案(1)|浏览(186)

我创建一个博客,并希望添加创建视图,这是我的形式

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')

我试过了,打印的错误在这里(当尝试从管理面板一切都是正确的)

myss37ts

myss37ts1#

在您的Blog模型中有ImageField(),因此您需要传递request.FILES,还需要在HTML表单中添加enctype="multipart/form-data",如下所示

网站views.py

def create_blog_view(request):
    if request.method == 'POST':
        blog_form = BlogForm(request.POST,request.FILES)
        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
    })

HTML表单

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>

    <form action="" method="POST" enctype="multipart/form-data">
        {% csrf_token %}
        {{form.as_p}}
        <button type="submit">Add Data</button>
    </form>
    
</body>
</html>

相关问题