当我提交表单时,它会显示一个空白表单,并说“#34;字段是必需的"对于每个领域。但是当我再次填写并提交时,它就可以了。这样做的原因是什么?
def forum_modules(request):
if request.method == 'POST':
pform = PostForm(data=request.POST, prefix='PostForm')
if pform.is_valid():
new_post = pform.save(commit=False)
new_post.user = request.user
new_post.save()
return HttpResponse("Post was successfully added")
else:
pform = PostForm()
return render(request, 'forum/forum_modules.html', 'pform': pform})
PostForm:
class PostForm(ModelForm):
class Meta:
model = Post
fields = ['title', 'body']
exclude = ['user']
发布模型:
class Post(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, )
title = models.CharField(max_length=100)
body = models.TextField()
date = models.DateField(auto_now_add=True, blank=True)
likes = models.IntegerField(default=0, blank=True)
def __str__(self):
return self.title
答案 0 :(得分:1)
您在POST时实例化时使用前缀,但在GET上没有。这意味着这些领域不匹配;在提交时,Django期待以" PostForm"开头的字段名称,但它不会在表单中输出那些开头的字段。
我不知道你为什么要使用前缀 - 这似乎不需要 - 但是如果你这样做,你需要在POST和GET中使用它实例化表单时阻塞。
答案 1 :(得分:1)
prefix
中的Form
参数,既可以在GET和POST表单中使用它,也可以不在两种表单中使用它。
def forum_modules(request):
if request.method == 'POST':
pform = PostForm(data=request.POST)
if pform.is_valid():
new_post = pform.save(commit=False)
new_post.user = request.user
new_post.save()
return HttpResponse("Post was successfully added")
else:
pform = PostForm()
return render(request, 'forum/forum_modules.html', 'pform': pform})