Django的。如何设置默认选项使用通用CreateView

时间:2017-08-15 11:41:47

标签: django django-models django-forms django-templates django-views

型号:

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

观点:

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

形式:

class MyForm(ModelForm):

    class Meta:
        model = MyModel
        fields = '__all__'

我如何在选项列表中设置默认值或第一个值>

1 个答案:

答案 0 :(得分:5)

您可以像这样使用initial

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

或者像这样:

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,
        }

希望它有所帮助!