在Django中保存表单数据

时间:2015-09-06 12:10:18

标签: python django forms

我正在尝试在Django中设置一个表单并将数据保存到我的数据库,而不使用ModelForm。我的表单正在运行,但我坚持的部分是如何处理表单数据并将其保存在视图中。正如你所看到的,在'if form.is_valid()之后:'我陷入困境,无法想到正确的代码。

# 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 个答案:

答案 0 :(得分:12)

您需要手动创建对象并设置所有字段。这是一个例子。

{{1}}

请注意,如果字段值不遵循约束,则保存对象可能会失败。所以你需要照顾它。

答案 1 :(得分:0)

在Django 2.0中,我认为有一种简单的方法,在基于类的视图中使用 FormView

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 )

我没有测试它运行,但我认为它会没问题。更多https://docs.djangoproject.com/en/2.0/topics/forms/modelforms/