[英]The proper Django way to make a form field required on CreateView, but optional on UpdateView?
[英]Django Disable/Exclude Field in CreateView but enable/include it in UpdateView
我想在創建新對象時排除/禁用Charfield(帶有選項和默認值),但在編輯此對象時,我想啟用/包含Charfield以供用戶更改它。
到目前為止,我嘗試了在Stackoverflow上找到的這個答案 ,但對我來說這不是完整的解決方案。 Charfield確實被禁用但是當我嘗試創建我的對象時,Django總是告訴我該字段是必需的(即使它有默認值)。
我的代碼:
class OfferCreateForm(forms.ModelForm):
class Meta:
model = Offer
exclude = ['date', 'number']
def __init__(self, *args, **kwargs):
request = kwargs.pop("request", None)
super(OfferCreateForm, self).__init__(*args, **kwargs)
instance = getattr(self, 'instance', None)
if instance and instance.pk:
self.fields['status'].widget.attrs['disabled'] = False
else:
self.fields['status'].widget.attrs['disabled'] = True
self.helper = FormHelper()
self.helper.form_tag = False
self.helper.help_text_inline = True
self.helper.add_layout(Layout(
Fieldset('Angebot',
Row(
Div(
Field('name'),
css_class='col-sm-12'
),
Div(
Field('category'),
css_class='col-sm-6'
),
Div(
Field('status'),
css_class='col-sm-6'
),
)),
Fieldset('Kunde',
Row(
Div(
Field('customer', css_class='selectize'),
css_class='col-sm-6'
),
Div(
Field('receiver', css_class='selectize'),
css_class='col-sm-6'
),
)),
Fieldset('Kundeninformation',
Row(
Div(
Field('introduction'),
css_class='col-sm-12'
),
),
),
Fieldset('Zusätzliche Informationen',
Row(
Div(
Field('footer'),
css_class='col-sm-12',
),
),
),
))
def clean_status(self):
instance = getattr(self, 'instance', None)
if instance and instance.pk:
return instance.status
else:
return self.cleaned_data['status']
我的模型中的狀態字段:
status = models.CharField(default="CREATED", max_length=255, choices=STATUSES, verbose_name="Status")
另請注意:從不調用clean_status函數。 我試着調試它,但顯然這個功能絕對沒有。
我知道我可以創建兩種不同的形式,但我想盡可能避免這種情況,也請不要使用Javascript。
您可以從字段列表中完全刪除字段,而不是使用fields.pop()
方法禁用它:
def __init__(self, *args, **kwargs):
request = kwargs.pop("request", None)
super(OfferCreateForm, self).__init__(*args, **kwargs)
instance = getattr(self, 'instance', None)
if instance and instance.pk:
self.fields.pop('status')
至於div部分你可以這樣做:
divs = [Div(
Field('name'),
css_class='col-sm-12'
),
Div(
Field('category'),
css_class='col-sm-6'
)]
if not instance and not instance.pk:
divs.append(Div(
Field('status'),
css_class='col-sm-6'
))
self.helper.add_layout(Layout(
Fieldset('Angebot',
Row(*divs)))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.