Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 >

like image 728
Dominik Avatar asked Dec 12 '25 07:12

Dominik


1 Answers

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!

like image 52
Jahongir Rahmonov Avatar answered Dec 13 '25 23:12

Jahongir Rahmonov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!