Home > other >  form don't save in django
form don't save in django

Time:01-22

I create a weblog and want add create view this is my form

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

and this my model

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

when I submit my form data don't save I want author auto quantification

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

I tried that and printed bug is here (when try from admin panel everything is right)

CodePudding user response:

In Your Blog Model have ImageField() so you need to pass request.FILES and also need to add enctype="multipart/form-data" in HTML form like this

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 form

<!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>
  • Related