Django表示数据不在mysql数据库中提交/可见

时间:2015-05-19 19:15:35

标签: django django-models django-forms

我使用连接到MySQL数据库的SessionWizardView设计并构建了一个Django 1.6.2调查应用程序。

问题在于(据我所知)提交的表单数据没有保存到数据库中。这是我第一次构建这样的应用程序,甚至是使用数据库。

有人可以看看我做了什么和我的代码,并指出我为什么看不到我的调查表提交的任何内容的错误?

The last time I posted a similar question我被告知我需要为数据创建一个模型,并建议我使用ModelForm在数据库中创建表和列。我已经这样做但我仍然没有看到我提交的内容

我的流程

  • 我在MySQL(Ver 14.14 Distrib 5.6.20)中创建了数据库 终端CREATE database django_db;及其中的表格已创建 当我运行命令python manage.py syncdb时。

  • 我可以在本地计算机和公共服务器上完成调查。没有错误,看起来一切正常

  • 我已经设置了phpMyAdmin,可以看到django_db数据库和survey_person模型。但是,我似乎无法找到表单应提交的任何数据。

  • 我曾尝试使用phpMyAdmin中的搜索工具查找我提交的任何表单数据但看不到它

  • 我已将数据库导出为.CSV文件,但该文件为空。

  • 如果我在phpMyAdmin中使用插入工具,数据将保存在数据库中,我可以在使用搜索工具时返回它。导出时,CSV文件中也会显示相同的数据。

这似乎表明,在向数据库提交内容时,我在应用程序的某处错过了一个步骤。

谁能告诉我哪里出错了?

我的代码

我试图将以下内容仅限于相关代码

settings.py

DATABASES = {
    'default': { 
        'ENGINE': 'django.db.backends.mysql', 
        'NAME': 'django_db',                                       
        'USER': 'root',
        'PASSWORD': 'xxxxxxxxxxxxxxxxx',
        'HOST': '127.0.0.1',
        #'PORT': '', 
    }
}

urls.py

url(r'^surveyone/$', SurveyWizardOne.as_view([
                                             SurveyFormA, 
                                             SurveyFormB,
                                             SurveyFormC,
                                             ....
                                             ....
                                             SurveyFormG,
                                             SurveyFormH,
                                             SurveyFormI
                                             ])),

forms.py

class SurveyFormA(forms.ModelForm):

    birthdate = forms.DateField(widget=extras.SelectDateWidget(years = range(1995, 1900, -1)), required=False)

    class Meta:
        model = Person
        fields = ['sender', 'birthdate', 'sex', 'relationship', 'state']



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

        widgets = {'internet_usage' : RadioSelectNotNull,
                   'smart_phone_ownership' : RadioSelectNotNull,
                   'smart_phone_usage' : RadioSelectNotNull,
                   }


class SurveyFormC(forms.ModelForm):   
    class Meta:
        model = Person
        fields = ['education', 'wages', 'presentage_savings', 'occupation', 'living']        

        widgets = {'education' : forms.RadioSelect,
                   'wages' : forms.RadioSelect,
                   'presentage_savings' : forms.RadioSelect,
                   'occupation' : forms.RadioSelect,
                   'living' : forms.RadioSelect,} 

        ....
        ....

models.py

     sender = models.EmailField(null=True, blank=True, verbose_name='What is your email address?')     

        birthdate = models.DateField(null=True, blank=True) #overwritten in forms.py so passed no more arguments

        SEX = (
            ('MALE', 'Male'),
            ('FEMALE', 'Female'))    
        sex = models.CharField(null=True, blank=True, max_length=100, choices=SEX, verbose_name='What sex are you?')


        RELATIONSHIP = (
            ('SINGLE', "Single"),
            ('INARELATIONSHIP', "In a relationship"),
            ('MARRIED', "Married"),
            ('DIVORCED', "Divorced"),
            ('SEPARATED', "Separated"),
            ('WIDOWED', "Widowed"),)    
        relationship = models.CharField(null=True, blank=True, max_length=100, choices=RELATIONSHIP, verbose_name='What is your relationship status?')             



                ....

                ....

                def __unicode__(self):
                return self

views.py

我的views.py是我的应用程序中最复杂的部分。不确定是否有必要展示,但我认为以防万一

class SurveyWizardOne(SessionWizardView):                             
    def get_context_data(self, form, **kwargs):
        context = super(SurveyWizardOne, self).get_context_data(form, **kwargs)                      
        step = int(self.steps.current)        

        if step == 0:
            self.request.session['path_one_images'] = ['P1D1.jpg', 'P2D2.jpg', 'P3D3.jpg', 'P4D4.jpg', 'P5D5.jpg', 'P6D6.jpg', 'P7D7.jpg', 'P8D8.jpg', 'P9D9.jpg']    
            self.request.session['instruction_task_one_images'] = ['IT1A.jpg', 'IT1B.jpg', 'IT1C.jpg']    
            self.request.session['instruction_task_two_images'] = ['IT2A.jpg', 'IT2B.jpg', 'IT2C.jpg']    
            self.request.session['images'] = []
            self.request.session['slider_DV_values'] = []


        PATH_ONE_IMAGES = self.request.session.get('path_one_images', [])        
        images = self.request.session.get('images', [])
        slider_DV_values = self.request.session.get('slider_DV_values', [])
        INSTRUCTION_TASK_ONE_IMAGES = self.request.session.get('instruction_task_one_images', [])
        INSTRUCTION_TASK_TWO_IMAGES = self.request.session.get('instruction_task_two_images', [])

        if step in range (0, 27):   
            self.request.session['path_one_images'] = PATH_ONE_IMAGES                   
            self.request.session['images'] = images
            self.request.session['slider_DV_values'] = slider_DV_values
            self.request.session['instruction_task_one_images'] = INSTRUCTION_TASK_ONE_IMAGES
            self.request.session['instruction_task_two_images'] = INSTRUCTION_TASK_TWO_IMAGES

            if step == 0:
                instruction_task_first_image = random.choice(INSTRUCTION_TASK_ONE_IMAGES)     
                context['display_image'] = instruction_task_first_image                                 

            elif step == 1:
                instruction_task_second_image = random.choice(INSTRUCTION_TASK_TWO_IMAGES)   
                context['display_image'] = instruction_task_second_image  

            elif step == 9:
                first_image = random.choice(PATH_ONE_IMAGES)   
                PATH_ONE_IMAGES.remove(first_image)               
                context['display_image'] = first_image                                 
                images.insert(0, first_image)   
                self.request.session['first_image'] = images[0] 
                self.request.session.get('first_image')                          

            elif step == 10:
                second_image = random.choice(PATH_ONE_IMAGES)   
                PATH_ONE_IMAGES.remove(second_image)


            ....

            ....


        return context 


    def done(self, form_list, **kwargs):
        return render(self.request, 'Return_to_AMT.html', {
            'form_data': [form.cleaned_data for form in form_list],            
        })  

phpMyAdmin的

来自phpMyAdmin的数据库的屏幕截图。注意:开头的隐藏字段不是调查表单中的介绍步骤,为简洁起见,此处未显示代码。

enter image description here

1 个答案:

答案 0 :(得分:1)

将数据提交到模型表单不会导致自动保存。如果要将模型表单中的数据保存到数据库,则需要调用其save()方法。您可以在向导的done()方法中执行此操作。

def done(self, form_list, **kwargs):
    # I don't know whether this will work, I am not familiar with your forms.
    for form in form_list:
        form.save()
    # Note the docs suggest redirecting instead of rendering a template.
    return render(self.request, 'Return_to_AMT.html', {
        'form_data': [form.cleaned_data for form in form_list],            
    })