[Fixed]-How to save form fields in the model in a view

1๐Ÿ‘

โœ…

If you really want to do this without a ModelForm, you have to create an instance of ContactModel yourself and assign all values to it.

def contact(request):
    if request.method == 'post':
        form = ContactForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            obj = ContactModel()
            obj.name = cd['name']
            obj.family = cd['family']
            ...
            obj.save()

Instead of assigning every attribute by hand you can also loop over cleaned_data:

if form.is_valid():
    cd = form.cleaned_data
    obj = ContactModel()
    for key, value in cd.iteritems():
        setattr(obj, key, value)
    obj.save()
๐Ÿ‘คilse2005

Leave a comment