Django Class Based View for both Create and Update

后端 未结 7 783
有刺的猬
有刺的猬 2020-12-13 18:46

Say I want to create a Class Based View which both updates and creates an object. From a previous question I worked out I

相关标签:
7条回答
  • 2020-12-13 19:30

    In case you don't need to raise 404 and want all fields to be blank if the object doesn't exists, create object when first saving and updating when it exists you can use this.

    views.py

    from django.views.generic import UpdateView
    
    
    class CreateUpdateView(UpdateView):
        model = MyModel
        form_class = MyModelForm
    
        def get_object(self, queryset=None):
            return self.model.objects.filter(...).first()
    

    forms.py

    class MyModelForm(forms.ModelForm):
    
        class Meta:
            model = MyModel
            fields = [...]
    
    0 讨论(0)
提交回复
热议问题