Dominik
Dominik

Reputation: 99

Django. How to set default option use generic CreateView

Model:

class MyModel(model.Models)
   status = models.ForeignKey(Statuses, on_delete=models.PROTECT, null=True, blank=True)

Views:

class MyViewCreate(CreateView):
    model = MyModel
    form_class = MyFrom
    template_name = 'mymodel_form.html'

Forms:

class MyForm(ModelForm):

    class Meta:
        model = MyModel
        fields = '__all__'

How i can in form set default or first value on the option list >

Upvotes: 3

Views: 1498

Answers (1)

Jahongir Rahmonov
Jahongir Rahmonov

Reputation: 13733

You can use initial like this:

class MyViewCreate(CreateView):
    model = MyModel
    form_class = MyFrom
    initial = {'status': '0'}
    template_name = 'mymodel_form.html'

or like this:

class MyViewCreate(CreateView):
    model = MyModel
    form_class = MyFrom
    template_name = 'mymodel_form.html'

    def get_initial(self):
        state = get_object_or_404(MyModel, some_field=some_value)
        return {
            'state':state,
        }

Hope it helps!

Upvotes: 8

Related Questions