使用Django和Crispy表单我正在尝试为区域字段中的无线电选择小部件创建初始/默认值。
有人告诉我,最好的方法是在创建时为表单类提供'initial'值。我试过了,我得到了'CreateForm' object is not callable
。我也在表单本身中尝试过它作为区域字段中的额外参数但是没有成功使用那个以太。
views.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)
forms.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')
)
)
答案 0 :(得分:1)
为表单设置参数的好地方是get_form_kwargs
方法。例如:
class YourView(CreateView):
form = YourFormClass # no arguments here
def get_form_kwargs(self):
kwargs = super(YourViewName, self).get_form_kwargs()
kwargs['initial'] = {} # your initial data here
return kwargs