12

I'm trying to set up a form in Django and save the data to my database, without using a ModelForm. My form is working, but the part I am stuck on is how to process the form data and save it within the view. As you can see, after 'if form.is_valid():' I am stuck and cannot think of the right code.

# models.py

from django.db import models

class Listing(models.Model):
    business_name = models.CharField(max_length=80)
    business_email = models.EmailField()
    business_website = models.CharField(max_length=80)
    business_phone = models.CharField(max_length=80)

# forms.py

from django import forms

class NewBusinessForm(forms.Form):
    business_name = forms.CharField(label='Business Name', max_length=100)
    business_phone = forms.CharField(label='Phone Number', max_length=100)
    business_email = forms.EmailField(label='Email Address', max_length=100)
    business_website = forms.CharField(label='Web Site', max_length=100)

# views.py

from django.shortcuts import render
from django.http import HttpResponseRedirect
from .forms import NewBusinessForm

def new_business(request):
    if request.method == 'POST':
        form = NewBusinessForm(request.POST)
        if form.is_valid():
            # process form data
            return HttpResponseRedirect('/')

    else:
        form = NewBusinessForm()

    return render(request, 'directory/new.html', {'form': form})

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

6 Comments

don't forget to import the Listing model
This worked, thank you! Do most people put this logic into views.py? Or is better to include it in forms.py as a function?
@Casey, mostly this should be done using model forms. Or if you want you can put this logic in form.save() method.
@BogeyJammer hi i am new, how to import Listing model? tried google search but cannot find. :) tqvm
Listing is a class specific to this application. The required syntax may be different but something like 'from .models import Listings' at the beginning of view.py should do the trick.
|
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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.