[Fixed]-Save form data in Django

35๐Ÿ‘

โœ…

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
            obj.save()
            return HttpResponseRedirect('/')
        ....

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

๐Ÿ‘คRohan

3๐Ÿ‘

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):
        form.save()
        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/

๐Ÿ‘คtim

Leave a comment