majid
majid

Reputation: 723

How to save form fields in the model in a view

I'm new to the django. I have a one form in my app with this codes:

/app/forms.py <==

from django import forms


class ContactForm(forms.Form):
    name = forms.CharField(max_length=100)
    family = forms.CharField(max_length=250)
    phone = forms.IntegerField(max_value=12)
    state= forms.CharField(max_length=50)
    agreed= forms.BooleanField(initial=True)
    why = forms.CharField(max_length=50)

And this is My Model :

class ContactModel(models.Model):
    name = models.CharField(max_length=100)
    family = models.CharField(max_length=250)
    phone = models.IntegerField(max_length=12)
    state= models.CharField(max_length=50)
    agreed= models.BooleanField(default=True)
    why = models.CharField(max_length=50)


    def __str__(self):
        return self.name + "  "  + self.family

and this is my view:

def contact(request):
    if request.method == 'post':
        form = ContactForm(request.POST)

        if form.is_valid():
            cd = form.cleaned_data

            ==> "i dont what can i do here !!!"


    else:
        form = ContactForm()

    return render(request, 'rango/contact.html', {'form': form})

Now my question is how can I save the entered values in form to the model. I know, I can do this with ModelForm but I need do this with form.

Upvotes: 0

Views: 48

Answers (1)

ilse2005
ilse2005

Reputation: 11429

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()

Upvotes: 1

Related Questions