模型:

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

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

最佳答案

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

希望能帮助到你!

关于姜戈。如何设置默认选项使用通用 CreateView,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45692129/

10-16 17:53