带有django形式的预填充数据的只读字段

时间:2018-10-15 13:03:06

标签: django django-forms

我有以下摘要,

# models.py
class Test(models.Model):
    username = models.CharField(max_length=100)
    email = models.EmailField()


# forms.py
class TestForm(forms.ModelForm):
    username = forms.CharField()
    email = forms.EmailField()

    class Meta:
        model = Test
        fields = ('username', 'email')


# views.py
def test(request):
    email = "example@example.com"
    """
    How to pass and show the 'email' in django form/template?
    """
    if request.method == 'POST':
        form = TestForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('home')
    else:
        form = TestForm()
    return render(request, 'test.html', {"form": form})

我如何 显示并重复使用 ,将Django表单/模板中email变量(即example@example.com)的值作为 read-only field

2 个答案:

答案 0 :(得分:0)

我们可以通过initial form 参数将 初始数据 传递给表单,< / p>

form = TestForm(initial={"field_1": "field_1 value","field_2":"field_2 value"})


在这种情况下,应为

def test(request):
    email = "example@example.com"
    """
    How to pass and show the 'email' in django form/template?
    """
    if request.method == 'POST':
        form = TestForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('home')
    else:
        form = TestForm(initial={"email": email}) # Change is here <<<<
    return render(request, 'test.html', {"form": form, "email": email})



参考
1. Dynamic initail values--Django doc
2. Django set default form values -- SO post

答案 1 :(得分:0)

尝试这样做:

class TestForm(forms.ModelForm):
    .....
    email = forms.EmailField(initial='{{ context.email }}', disabled=True)
    .....

从视图传递过来的上下文应该有“电子邮件”