Python 在 Django 中保存表单数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32423401/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 11:32:08  来源:igfitidea点击:

Save form data in Django

pythondjangoforms

提问by Casey

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.

我正在尝试在 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})

采纳答案by Rohan

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.

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

回答by tim

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

在 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 )

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/

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