如何创建Person(models.Model):存储通过调查表提交的数据?

时间:2015-05-10 22:36:55

标签: django python-2.7 django-models

我创建了一个小型Django(1.6.2)调查应用程序,它使用连接到MySQL数据库的SessionWizardView分割成多个页面。 However I found out through this question 我没有创建将表单数据保存到数据库的必要模型。

我要做的是在数据库中为每个完成表单的人创建一个单独的条目。为此,我尝试在Person(models.Model):中创建一个models.py,其中包含forms.py

中调查问题的相应条目

当我运行python manage.py syncdb时,我没有错误,我可以通过phpMyAdmin看到新创建的survey_person表。当我检查表结构时,我可以看到代表我刚刚创建的Person(models.Model);的每个单独的字段/行。

问题在于,当我填写并提交我的调查申请时,似乎没有任何数据被保存到数据库中。

问题:如何使用我刚创建的Person模型将通过我的调查表提交的数据存储到数据库中?

如果有人能告诉我甚至如何存储一个元素,例如email我相信我能弄明白其余的事情。

由于

models.py

from django.db import models
from django.forms import ModelForm
from survey.forms import SurveyFormA, SurveyFormB


class Person(models.Model):

    sender = models.EmailField(max_length=200)
    birthdate = models.DateField(blank=True, null=True)
    sex = models.ForeignKey('Person', related_name='Person_sex')
    smart_phone_ownership = models.ForeignKey('Person', related_name='Person_smart_phone_ownership')


    def __unicode__(self):
        return self

forms.py

from django import forms
from django.core import validators
from django.forms import extras
import random

class SurveyFormA(forms.Form):

    sender = forms.EmailField(label='What is your email address?', required = False)

    birthdate = forms.DateField(widget=extras.SelectDateWidget(years = range(1995, 1900, -1)), label='What is your Date of Birth?', required = False)

    MALE = 'M'
    FEMALE = 'FM'

    SEX = (
        ("", "----------"), 
        (MALE, "Male"),
        (FEMALE, "Female"),
               )   
    sex = forms.ChoiceField(widget=forms.Select(), choices=SEX, initial= "", label='What sex are you?', required = False) 

class SurveyFormB(forms.Form): 

    YES_SMARTPHONE = 'Yes'
    NO_SMARTPHONE = 'No'

    SMART_PHONE_OWNERSHIP = (
        (YES_SMARTPHONE, 'Yes'),
        (NO_SMARTPHONE, 'No'),
               )    
    smart_phone_ownership = forms.ChoiceField(widget=forms.RadioSelect(), choices=SMART_PHONE_OWNERSHIP, initial= "", label='Do you own a Smartphone?', required = False)

    ....
    ....

任何帮助都是一如既往,非常感谢。

1 个答案:

答案 0 :(得分:1)

如果您使用ModelForm代替Form,则应自动保存您的模型。

https://docs.djangoproject.com/en/1.8/topics/forms/modelforms/

<强> forms.py

from django import forms

from .models import Person


class SurveyFormA(forms.ModelForm):
    class Meta:
        model = Person
        fields = ['sender', 'birthdate']

class SurveyFormB(forms.ModelForm):
    class Meta:
        model = Person
        fields = ['smart_phone_ownership']

您的选择,help_text等可以直接在模型中设置:

<强> models.py

from django.db import models


class Person(models.Model):

    sender = models.EmailField(null=True)
    birthdate = models.DateField(null=True)

    MALE = 'M'
    FEMALE = 'F'
    SEX = (
        (MALE, "Male"),
        (FEMALE, "Female"))   
    sex = models.ChoiceField(choices=SEX, ...) 
    ...