【问题标题】:Django. How to set default option use generic CreateView姜戈。如何设置默认选项使用通用 CreateView
【发布时间】:2018-01-23 07:57:46
【问题描述】:

型号:

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__'

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

【问题讨论】:

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


    【解决方案1】:

    你可以像这样使用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,
            }
    

    希望对你有帮助!

    【讨论】:

    • 这正是我想要的。谢谢
    • 这些 some_field=some_value 是什么?
    猜你喜欢
    • 2016-04-25
    • 2012-11-10
    • 1970-01-01
    • 2021-07-28
    • 2013-02-01
    • 2010-11-11
    • 2010-10-09
    • 1970-01-01
    • 2023-04-01
    相关资源
    最近更新 更多