[Fixed]-Save form data in Django


You need to create the object and set all fields manually. Here is an example.

def new_business(request):
    if request.method == 'POST':
        form = NewBusinessForm(request.POST)
        if form.is_valid():
            # process form data
            obj = Listing() #gets new object
            obj.business_name = form.cleaned_data['business_name']
            obj.business_email = form.cleaned_data['business_email']
            obj.business_phone = form.cleaned_data['business_phone']
            obj.business_website = form.cleaned_data['business_website']
            #finally save the object in db
            return HttpResponseRedirect('/')

Note that saving object may fail if field values do not follow the constraint. So you need to take care of that.



In Django 2.0, I think there is an easy way, use FormView in class based view.

from django.views.generic.edit import FormView
class newBusiness(FormView):
    form_class = NewBusinessForm
    success_url ="/"
    template_name = "temp.html"
    def form_valid(self, form):
        return redirect(self.success_url )

I did not test it to run, but i think it will be OK. More at https://docs.djangoproject.com/en/2.0/topics/forms/modelforms/


Leave a comment