【发布时间】:2021-06-02 06:25:29
【问题描述】:
我在 django 中有一个视图,其中 post 方法有 2 种不同类型的表单:
def post(self, request):
tweet_form = TweetForm(request.POST, request.FILES)
comment_form = TweetCommentForm(request.POST)
print(request.POST['form-button'])
if request.POST['form-button'] == 'add_tweet':
print(tweet_form.is_valid)
if tweet_form.is_valid():
content = tweet_form.cleaned_data['content']
image = tweet_form.cleaned_data['image']
tweet = Tweet.objects.create(
user=request.user,
content=content,
)
if image != None:
tweet.image = image
tweet.save()
return redirect("/home")
if request.POST['form-button'] == 'add_comment':
print(comment_form.is_valid)
if comment_form.is_valid():
content = comment_form.cleaned_data['body']
return redirect("/home")
ctx = {"tweet_form": tweet_form, "comment_form": comment_form}
return render(request, "home.html", ctx)
这两种形式具有不同的名称、值和 ID。
当我打印(tweet_form.is_valid()) 或(comment_form.is_valid()) 时,我会收到类似的信息:
<bound method BaseForm.is_valid of <TweetForm bound=True, valid=Unknown, fields=(content;image)>>
分别适用于两种形式。 我可以以某种方式重新组织视图以处理这两种形式还是我必须有另一个视图?
问候
【问题讨论】: