Search code examples
pythondjangodjango-class-based-viewsdjango-2.0

is it necessary to implement ModelForm in our project to implement a CreateView (CBV) in Django 2.0.2?


I am a beginner programming in Django framework and I am learning how to implement a CreateView (a class based view for creating a form based on a model) in my views.py file.


Solution

  • No, you don't the view will automatically create a model form for you, but you have to option of overwriting it.

    Let's assume you have MyModel, you can do this:

    from myapp.models import MyModel
    
    # views.py
    
    class MyCreateView(CreateView):
        model = MyModel
        fields = ['something', 'somethingelse']  # these are fields from MyModel
    

    If you do not specify the fields Django will throw an error.

    If you want to customize your form validation in some way, you can do this:

    # forms.py
    class MyForm(ModelForm):
        class Meta:
            model = MyModel
            fields = ['something']  # form fields that map to the model
    
            # ... do some custom stuff
    
    # views.py
    class MyCreateView(CreateView):
        model = MyModel
        form_class = MyForm
    

    Notice that we are not specifying the fields anymore on MyView because if we would it will also throw an error, and the reasons is because the view will fetch the fields from the form.

    More information: https://docs.djangoproject.com/en/2.1/topics/class-based-views/generic-editing/

    Code that handles the form_class: https://github.com/django/django/blob/master/django/views/generic/edit.py#L74