Skip to content

From model to Form

Chris Carroll edited this page Feb 23, 2021 · 1 revision

the data model for our car make is just an id and a string. models.py

class CarMake(models.Model):
    make_id = models.AutoField(primary_key=True)
    make_name = models.CharField(max_length=DEFAULT_MAX)

    def __str__(self):
        return '%s' % self.make_name

the form is autogenerated from its attributes forms.py

class NewMakeForm(forms.ModelForm):
    class Meta:
        model = CarMake
        fields = ['make_name']

    def save(self, commit=True):
        form = super(NewMakeForm, self).save(commit=False)

        if commit:
            form.save()
        return form

    def __init__(self, *args, **kwargs):
        super(NewMakeForm, self).__init__(*args, **kwargs)

and the view is the actual html thats created. form.html is a good basis but if you need more you can create your own feature.html that can give you what you want. views.py

class NewMakeView(CreateView):
    form_class = forms.NewMakeForm
    success_url = reverse_lazy('car_app:newcar')
    template_name = 'form.html'

Clone this wiki locally