使用 Django 和 Crispy 表单,我试图在区域字段中为我的无线电选择小部件设置初始/默认值。
有人告诉我,最好的方法是在创建表单类时为其赋予“初始”值。我试过了,我得到了'CreateForm' object is not callable
。我还通过在区域字段中将其作为额外参数提供给表单本身进行了尝试,但该以太币没有成功。
视图.py:
class CreateRequest(LoginRequiredMixin, CreateView):
model = Request
fields = ['region', 'ddi', 'zen_desk_ticket', 'user_assigned', 'user_requester', 'date_due', 'description']
template_name = "requests_app/create_request.html"
obj = Region.objects.get(name='Chicago')
form_class = CreateForm(initial = {"region": unicode(obj.pk)})
success_url = '/'
def form_valid(self, form):
objects = form.save()
return super(CreateRequest, self).form_valid(form)
表格.py:
class CreateForm(ModelForm):
date_due = forms.DateTimeField(
widget=DateTimePicker(options={"format": "YYYY-MM-DD HH:MM",
"pickTime": True}))
region = forms.ModelChoiceField(widget=forms.RadioSelect, queryset= Region.objects.all(),
empty_label=None)
class Meta:
model = Request
exclude = ('completed', 'date_completed')
def __init__(self, *args, **kwargs):
super(CreateForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_class = 'form-horizontal'
self.helper.label_class = 'col-lg-2 control-label'
self.helper.field_class = 'col-lg-4'
self.helper.layout = Layout(
Fieldset('Create',
'region',
'user_assigned',
'user_requester',
'date_due',
'description',
),
FormActions(
Submit('submit', 'Submit', css_class='btn-primary')
)
)