如何建立多个提交按钮Django表单?

我有一个带有一个电子邮件输入和两个提交按钮的表单,用于订阅和取消订阅新闻通讯:


<form action="" method="post">

{{ form_newsletter }}

<input type="submit" name="newsletter_sub" value="Subscribe" />

<input type="submit" name="newsletter_unsub" value="Unsubscribe" />

</form>

我也有课表:


class NewsletterForm(forms.ModelForm):

    class Meta:

        model = Newsletter

        fields = ('email',)

我必须编写自己的clean_email方法,并且我需要知道表单是通过哪个按钮提交的。但是提交按钮的值不在self.cleaned_data字典中。否则我可以获取按钮的值吗?


饮歌长啸
浏览 1055回答 3
3回答

当年话下

您可以self.data在clean_email方法中使用来在验证之前访问POST数据。它应包含一个称为newsletter_sub或newsletter_unsub取决于所按下按钮的键。# in the context of a django.forms formdef clean(self):&nbsp; &nbsp; if 'newsletter_sub' in self.data:&nbsp; &nbsp; &nbsp; &nbsp; # do subscribe&nbsp; &nbsp; elif 'newsletter_unsub' in self.data:&nbsp; &nbsp; &nbsp; &nbsp; # do unsubscribe
打开App,查看更多内容
随时随地看视频慕课网APP