Question

Using Django and Crispy forms I am trying to make a initial/default value for my radio select widget in regions field.

I was told that the best way to do this is to do give the form class the 'initial' value when it is created. I tried this and I get 'CreateForm' object is not callable. I've also tried it in the form itself by giving it as an extra argument in the region field but didn't have success with that ether.

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')
            )
        )
Was it helpful?

Solution

A good place to set arguments for your form is the get_form_kwargs method. For example:

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top