Django FormWizard使用FK发布到数据库

时间:2017-12-22 22:48:40

标签: python django forms models django-formwizard

我正在使用Django表单向导,我已经成功创建了一个能够创建新用户的多步表单。我有一个名为UserAddon的第二个模型,我将OnetoOne关系设置为。我无法弄清楚如何POST到该模型并在UserAddon中创建该关系。如果有人知道,我应该使用像

这样的支票
if form.is_valid():

if request.method == 'POST':

在我发布之前?

谢谢!

向导

class ContactWizard(SessionWizardView):
    template_name = "wizardApp/contact_form.html"
    def done(self, form_list, **kwargs):
        process_form_data(form_list)
        return HttpResponseRedirect('../home')

处理表单数据

def process_form_data(form_list):
    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']


    print(last_name)
    print(first_name)
    print(email)

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

    ##### SOMETHING LIKE THIS ####
    user_addon = UserAddon.objects.create(user.email)

    return form_data 

还值得注意的是,我的代码是用来设置用户电子邮件地址作为用户名

1 个答案:

答案 0 :(得分:0)

我实际上能够弄明白看到评论

处理表单数据

def process_form_data(form_list):
    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[1]['fav_food']
    fav_drink = form_data[1]['fav_drink']

    # print(username)
    print(last_name)
    print(first_name)
    print(email)
    print(fav_food)
    print(fav_drink)

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

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

我仍然不清楚检查帖子的请求,如果表格有效,那么任何帮助仍然是apreciated!