如何在 Django 表单中将两个表单字段渲染为一个字段? [英] How to render two form fields as one field in Django forms?

查看:29
本文介绍了如何在 Django 表单中将两个表单字段渲染为一个字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发 Django 应用程序,我需要以不同的方式呈现表单.

I'm working on Django application where I need to render a form differently.

表单包含与一个人相关的多个字段.

The form contains multiple fields related to a person.

 1. Firstname
 2. Lastname
 3. Email
 4. Address
 5. City
 6. Country
 7. Phone
 8. Pincode

我的应用程序中有两个流.在第一个流程中,我可以呈现所有表单字段并在用户输入一些数据并提交时保存它们.

There are two flows in my application. In the first flow I can render all the form fields and save them when the user enters some data and submit.

但在第二个流程中,我只需要显示如下三个字段.

But in the second flow, I need to display only three fields as below.

 1. Name - *Combination of Firstname and Lastname*
 2. Email
 3. Phone

姓名字段中输入的数据应由空格分隔 - 并保存为 Firstname 和 Lastname.对于表单中其他未呈现的剩余必填字段,我可以填充空值并将模型保存在后端.

The data entered in the name field should be split by empty space - and saved as Firstname and Lastname. And for other remaining mandatory fields in the form that are not rendered, I can fill empty values and save the model in Backend.

针对每个流以不同方式呈现表单的最佳方法是什么?

What is the best way to render the forms differently for each flow?

Python: 3.7.3
Django: 2.1.5

推荐答案

您可以使用请求的 Post/Get 功能.例如:sudo 代码

You can use Post / Get feature of request. For example: sudo code

def DataView(request):
    if request.method == 'POST':
        form = DataForm(request.POST)
        if form.is_valid():
            form.save()
            return render(request, 'users/form1.html', {'form': form})
        else
            ValidationError(_('Please login-in first'), code='invalid')
    else: 
        #do your magic here. make a new form with limited fields or render this old form on another page where in html you can limit/modify the fields.
        form = DataForm1()
        return render(request, 'users/form1.html', {'form': form})

这篇关于如何在 Django 表单中将两个表单字段渲染为一个字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆