Django检查Form is_valid()

时间:2017-12-28 18:22:26

标签: python django forms validation

我正在尝试复制

/* eslint-disable  func-names */
/* eslint-disable  dot-notation */
/* eslint-disable  new-cap */
/* eslint quote-props: ['error', 'consistent']*/
/**
 * This sample demonstrates a simple skill built with the Amazon Alexa Skills
 * nodejs skill development kit.
 * This sample supports en-US lauguage.
 * The Intent Schema, Custom Slots and Sample Utterances for this skill, as well
 * as testing instructions are located at https://github.com/alexa/skill-sample-nodejs-trivia
 **/

'use strict';

const Alexa = require('alexa-sdk');
const questions = require('./question');

const ANSWER_COUNT = 4; // The number of possible answers per trivia question.
const GAME_LENGTH = 10;  // The number of questions per trivia game.
const GAME_STATES = {
    TRIVIA: '_TRIVIAMODE', // Asking trivia questions.
    START: '_STARTMODE', // Entry point, start the game.
    HELP: '_HELPMODE', // The user is asking for help.
};
const APP_ID = undefined; // TODO replace with your app ID (OPTIONAL)

const languageString = {
    'en': {
        'translation': {
            'QUESTIONS': questions['HS_QUESTIONS_EN_US'],
            'GAME_NAME': 'Science Bowl',
            'HELP_MESSAGE': 'I will ask you %s multiple choice questions. Respond with the number of the answer. ' +
                'For example, say one, two, three, or four. To start a new game at any time, say, start game. ',
            'REPEAT_QUESTION_MESSAGE': 'To repeat the last question, say, repeat. ',
            'ASK_MESSAGE_START': 'Would you like to start playing?',
            ...
        },
    },
};

const newSessionHandlers = {
    'LaunchRequest': function () {
        this.handler.state = GAME_STATES.START;
        this.emitWithState('StartGame', true);
    },
    'SetSchool': function() {
        this.handler.state = GAME_STATES.START;
        this.emitWithState('School', true);
    },
    'AMAZON.StartOverIntent': function () {
        this.handler.state = GAME_STATES.START;
        this.emitWithState('StartGame', true);
    },
    'AMAZON.HelpIntent': function () {
        this.handler.state = GAME_STATES.HELP;
        this.emitWithState('helpTheUser', true);
    },
    'Unhandled': function () {
        const speechOutput = this.t('START_UNHANDLED');
        this.emit(':ask', speechOutput, speechOutput);
    },
};

...

const startStateHandlers = Alexa.CreateStateHandler(GAME_STATES.START, {
    'StartGame': function (newGame) {
        let speechOutput = newGame ? this.t('NEW_GAME_MESSAGE', this.t('GAME_NAME')) + this.t('WELCOME_MESSAGE', GAME_LENGTH.toString()) : '';

        this.handler.state = GAME_STATES.START;
        this.emit(':ask', speechOutput, speechOutput);
    },
    'School': function(newGame) {           
        this.handler.state = GAME_STATES.START;
        this.response.speak('test');
        this.emit(':responseReady');
    }
});

exports.handler = function (event, context) {
    const alexa = Alexa.handler(event, context);
    alexa.appId = APP_ID;
    // To enable string internationalization (i18n) features, set a resources object.
    alexa.resources = languageString;
    alexa.registerHandlers(newSessionHandlers, startStateHandlers, triviaStateHandlers, helpStateHandlers); // these were defined earlier
    alexa.execute();
};

使用django表单向导。 (这个问题不应该与向导有任何关系)

我有这段代码:

if form.is_valid():

如果我打印出form_list,我会得到这个

class ContactWizard(SessionWizardView):

def get_template_names(self):
    return [TEMPLATES[self.steps.current]]

def done(self, form_list, **kwargs):
    if self.request.method == 'POST':
        print(form_list)
        process_form_data(form_list)
    return HttpResponseRedirect('../home')

def process_form_data(form_list):
    if form.is_valid():
        form_data = [form.cleaned_data for form in form_list]

        first_name = form_data[0]['first_name']
        last_name = form_data[0]['last_name']
        email = form_data[0]['email']

        fav_food = form_data[0]['fav_food']
        fav_drink = form_data[0]['fav_drink']

        user = User.objects.create_user(email)
        user.first_name = first_name
        user.last_name = last_name
        user.email = email
        user.save()

        user_addon = UserAddon.objects.create(user=user,fav_food=fav_food,fav_drink=fav_drink)
        user_addon.save()

        return form_data

如果我尝试用

运行它
odict_values([<UserAddonForm bound=True, valid=True, fields=(fav_food;fav_drink;first_name,last_name;email)>,ContactForm3 bound=True, valid=True, fields=(info1;info2;message)>])

我得到了

form.is_valid() 

如何获得form.is_valid()的等效工作?

由于

1 个答案:

答案 0 :(得分:2)

您正在将form_list传递给函数process_form_data,但会检查名称formform.is_valid()),但此时不存在。

假设form_list是一个可迭代的,你可以迭代它并按顺序处理表单:

def process_form_data(form_list):
    for form in form_list:
        if form.is_valid():
            form_data = form.cleaned_data
            first_name = form_data[0]['first_name']
            last_name = form_data[0]['last_name']