Model
class Publisher(models.Model):
name = models.CharField(max_length=30)
address = models.CharField(max_length=50)
city = models.CharField(max_length=60)
state_province = models.CharField(max_length=30)
country = models.CharField(max_length=50)
website = models.URLField()
Form
from django import forms
class ContactForm(forms.Form):
name = forms.CharField()
address = forms.CharField()
city = forms.CharField()
state_province = forms.CharField()
country = forms.CharField()
website = forms.URLField()
And view
def test(request):
if request.method=='POST':
form = ContactForm(request.POST)
if form.is_valid():
print form.cleaned_data
p=Publisher()
p.name=form.cleaned_data.get('name')
p.address=form.cleaned_data.get('address')
p.city=form.cleaned_data.get('city')
p.state_province=form.cleaned_data.get('state_province')
p.country=form.cleaned_data.get('country')
p.website=form.cleaned_data.get('website')
p.save()
return HttpResponse("Done")
else:
form = ContactForm()
return render(request, 'contact_form.html', {'form': form})
I am saving the data to the database when the submitted form is valid.
But what I did is extracting each field from dictionary form.cleaned_data and then assigned it to instance of Publisher object manually for e.g p.name=form.cleaned_data.get('name')
My question is that is there is any way to assign the form.cleaned_data dictionary to Publisher object. In short can i do it like ,
p=Publisher()
p=form.cleaned_data
p.save()