我在我的示範場,它指示用戶是否願意接收電子郵件更改布爾值
receive_invites = models.BooleanField(default=True, help_text="Receive an invite email from friends")
我也有一個選項觀點:
[X]我不想接收電子郵件......
通過默認 receive_invites是真因此複選框是打勾。不過,我希望用戶勾選複選框,以便將receive_invites更改爲False。我在我的ModelForm中做了以下操作來實現這一點。有沒有人有一個更優雅的方式來做到這一點?
class UnsubscribeForm(forms.ModelForm):
class Meta:
model = Entrant
fields = ('receive_invites')
def __init__(self, *args, **kwargs):
if kwargs.has_key('instance'):
instance = kwargs['instance']
if instance.receive_invites:
instance.receive_invites = False
else:
instance.receive_invites = True
super(UnsubscribeForm, self).__init__(*args, **kwargs)
,並在視圖中我有這樣的:
if request.method == 'POST':
unsubscribe_form = UnsubscribeForm(request.POST, instance=me)
if unsubscribe_form.is_valid():
receive_invites = unsubscribe_form.cleaned_data['receive_invites']
if receive_invites:
user.receive_invites = False
else:
user.receive_invites = True
unsubscribe_form.save()
return redirect('index')
else:
unsubscribe_form = UnsubscribeForm(instance=me)
整點是不改變字段名,我有具有相同命名約定的其他字段(試圖保持一致) –
@NgoMinhNam如果它創建這些問題,命名約定有什麼意義?最終目標是讓代碼可讀,而不是因爲一些約定而使其複雜化。 – DrTyrsa