简体   繁体   English

Django将字段表示为模板变量

[英]Django form fields as template variables

The main question is if it is possible to specifify specific form fields at different given locations in your html template in any smooth way. 主要问题是,是否可以以任何平滑的方式在html模板中的不同给定位置指定特定的表单字段。 eg {{ form.password }} However, that does not seem to work. 例如{{form.password}}但是,这似乎不起作用。 (I swear that I have seen this somewhere, but I just can't find it anymore on the internet) (我发誓我已经在某个地方见过这个,但我在互联网上找不到它)

My view for signing up new users is inheriting from UserCreationForm and looks kind of like this: 我对注册新用户的看法是继承自UserCreationForm,看起来像这样:

views.py views.py

def signup(request):
if request.method == "POST":
    form = UserCreationForm(request.POST)
    if form.is_valid():
        form.save()
        username = form.cleaned_data.get('username')
        raw_password = form.cleaned_data.get('password1')
        user = authenticate(username=username, password=raw_password)
        login(request, user)
        return redirect('home')

else:
    form = UserCreationForm()
return render(request, 'core/authentication/registration_form.html', {'form': form})

It sends this form straight to the template registration_form.html, this is how I wish it worked: 它将此表单直接发送到模板registration_form.html,这是我希望它工作的方式:

<form class="form" method="POST" action="">
    <div class="card-body">
        <div class="input-group form-group-no-border">
            <span class="input-group-addon">
                <i class="now-ui-icons users_circle-08"></i>
            </span>
            {{ form.first_name }}
       </div>
    </div>

This is how it actually works (for now): 这是它实际工作的方式(目前):

<form class="form" method="POST" action="">
    <div class="card-body">
        <div class="input-group form-group-no-border">
            <span class="input-group-addon">
                <i class="now-ui-icons users_circle-08"></i>
            </span>
            <input type="text" class="form-control" placeholder="First Name...">
       </div>
    </div>

This might be a stupid question, but oh well I am curious. 这可能是一个愚蠢的问题,但是我很好奇。

Thank you in advance 先感谢您

If i've understood your question correctly, here is how django says you should render django form fields manually. 如果我已经正确理解了你的问题,那么django说你应该手动渲染django表单字段。

{{ form.non_field_errors }}  # here django renders errors which do not belong to any field
<div>
    {{ form.field_1.errors }}  # here django renders errors which belong to field_1
    {{ form.field_1.label_tag }}  # label element
    {{ form.field_1 }}  # input element
</div>

# some html

<div>
    {{ form.field_2.errors }}
    {{ form.field_2.label_tag }}
    {{ form.field_2}}
</div>

You can read this here in the lower half. 您可以阅读这里的下半部分。

Each field ( each label, input, error elements ) can be rendered with custom classes and widgets. 可以使用自定义类和窗口小部件呈现每个字段(每个标签,输入,错误元素)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM