首页 > 解决方案 > 使用 Django 保存表单时遇到问题

问题描述

好吧,我正在建立一个博客网站,我希望用户在其中注册自己然后发布他们的文章。但是我在保存文章时遇到了麻烦。当我点击“发送”按钮时,帖子没有被提交。我为此目的使用了 django forms.py。经过调查,我发现表单没有得到验证。form.is_valid() 返回 false。如何完成?这是我的代码:

模型.py:

class Writer(models.Model):
    user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE)
    name = models.TextField()
    username = models.CharField(max_length=15, unique=True)
    email = models.EmailField(unique=True)
    profile_pic = models.ImageField(upload_to = 'Bloggers')
    bio = models.TextField()
    locality = models.TextField()
    state = models.TextField()
    country = models.TextField()
    instagram = models.URLField(unique=True, null=True)
    linkedin = models.URLField(unique=True, null=True)
    facebook = models.URLField(unique=True, null=True)

    def __str__(self):
        return self.name + ' , aka,  ' + self.username

class Post(models.Model):
    blogChoice = (
        ('Sneak Peek', 'Sneak Peek'),
        ('Events', 'Events'),
        ('Lifestyle', 'Lifestyle'),
        ('Trends', 'Trends'),
    )
    blogType = models.CharField(max_length=25, choices=blogChoice,null=True)
    title = models.CharField(max_length=25)
    cover = models.ImageField(upload_to='Blog Image')
    content = models.TextField()
    author = models.OneToOneField(Writer, on_delete=models.CASCADE)
    timestamp = models.DateTimeField(auto_now_add=True, blank=True)
    approve = models.BooleanField(default=False)
    recommend = models.BooleanField(default=False)
    time = models.IntegerField()

    def __str__(self):
        return self.title + ' by ' + self.author

表格.py:

class PostForm(ModelForm):
    class Meta:
        model = Post
        fields = '__all__'
        exclude = ['timestamp', 'approve', 'recommend']

视图.py:

def writewithus(request):
    form = PostForm()
    if request.method == "POST":
        form = PostForm(request.POST, request.FILES)
        print("hi")
        if form.is_valid():
            print("hey")
            c = form.save()
            if c:
                print("hello")
            return redirect('/')
            # only "hi" gets printed
    context = {'form':form}
    return render(request, 'Blog/writewithus.html', context)

writewithus.html:

          <form class="" method="POST" enctype="multipart/form-data">
            {% csrf_token %}
            <div class="file btn btn-lg btn-primary mt-3"
              style="background: linear-gradient(to right, #00d2ff, #3a7bd5);">
              Upload Article cover
              {{form.cover}}
            </div>
            <div class="form-group">
              {{form.title}}
            </div>
            <div class="form-group">
              {{form.content}}
            </div>
            <div class="form-group">
            {{form.author}}
            </div>
            <div class="form-group">
              {{form.blogType}}
            </div>
            <div class="form-group">
              {{form.time}}
            </div>
            <div class="form-check mt-3">
              <input type="checkbox" class="form-check-input" id="exampleCheck1" required>
              <label class="form-check-label" for="exampleCheck1">I agree to the totellexpress <a href="">Terms of
                  service</a> and <a href="">Privacy Policy.</a></label>
            </div>
            <button type="submit" class="btn btn-dark mt-3">Send</button>
          </form>

标签: pythondjangodjango-modelsdjango-formsdjango-views

解决方案


检查form.errors验证错误。然后你就会知道,为什么它不保存。


推荐阅读