Django 1.11 でフォームを作成しようとしています。ウォッチ リストに一連のチェックボックスがあり、ユーザーが後で通知を受け取りたいアイテムに複数のアラートを設定できるようにしています。ただし、このようなフィールドで複数のオプションを表す方法がわかりません。
ここに私のモデルコードがあります:
class Watchlist(models.Model):
CLOSES_IN_2_WEEKS, CLOSES_IN_1_WEEKS, CLOSES_IN_3_DAYS, CLOSES_TOMORROW = (
"CLOSES_IN_2_WEEKS",
"CLOSES_IN_1_WEEKS",
"CLOSES_IN_3_DAYS",
"CLOSES_TOMORROW"
)
ALERT_OPTIONS = (
(CLOSES_IN_2_WEEKS, "Closes in 2 weeks",),
(CLOSES_IN_1_WEEKS, "Closes in 1 weeks",),
(CLOSES_IN_3_DAYS, "Closes in 3 days",),
(CLOSES_TOMORROW, "Closes tomorrow",),
)
# I want to store more than one option
alert_options = models.CharField(max_length=255, blank=True)
def save(self):
"""
If this is submitted create 1 alert:
"CLOSES_IN_1_WEEKS"
If this submitted, create 3 alerts:
"CLOSES_IN_2_WEEKS",
"CLOSES_IN_1_WEEKS",
"CLOSES_IN_3_DAYS",
"""
# split the submitted text values, to create them
# yes, this should probably be a formset. I wasn't sure how I'd
# handle the logic of showing 4 optional alerts, and only creating models
# on the form submission, and remembering to delete them when a user
# unchecked the choices in the form below
そして、これが私が使用しているフォームです。メソッドにフックして、__init__
可能な選択肢をフォームに事前入力します。
class WatchlistForm(forms.ModelForm):
alert_options = forms.ChoiceField(
choices=[],
label="Alert Options",
required=False,
widget=forms.CheckboxSelectMultiple(),
)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields["alert_options"].choices = WatchlistForm.ALERT_OPTIONS
def clean_alert_options(self):
# I'm dropping into ipython to look around here
import ipdb; ipdb.set_trace()
return data["alert_options"]
class Meta:
model = WatchlistForm
fields = ("alert_options")
これは現在、チェックされた単一のチェックボックスに対しては正常に機能しますが、複数あると、最後の選択肢のみが選択され、アクセス方法がわかりません。
1つだけではなく、ここですべての選択肢をキャプチャするにはどうすればよいですか?
ここでおそらくフォームセットを使用する必要があることは承知しています。問題は、事前入力されたフォームセット オプションのセットを作成して、アクティブなアラートと非アクティブなアラートの選択肢を表す方法がわかりませんでした。
テストを使用して目的を示すそれが役立つ場合は、情報を保存しようとしているので、そのように保存されます-テストスイートでpytestを使用して、私に基づいた疑似コードを追加しました。
def test_form_accepts_multiple_alert_values(self, db, verified_user):
form_data = {
"user_id": verified_user.id,
"alert_options": "CLOSES_IN_2_WEEKS CLOSES_IN_3_DAYS",
}
submission = forms.WatchlistForm(form_data)
instance = submission.save()
assert instance.alert_options == "CLOSES_IN_2_WEEKS CLOSES_IN_3_DAYS",