Alien13
Alien13

Reputation: 618

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. e.g. {{ form.password }} However, that does not seem to work. (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:

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:

<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

Upvotes: 1

Views: 989

Answers (1)

cMeIIIHo
cMeIIIHo

Reputation: 273

If i've understood your question correctly, here is how django says you should render django form fields manually.

{{ 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.

Upvotes: 3

Related Questions