Hoa
Hoa

Reputation: 20438

How can I customize the HTML in a Django UserCreation form?

In my views I have something like:

form = UserCreationForm()
return render(request, "mypage.html", {'form': form})

In my view I have the somewhat magic:

{{ form.as_p }}

Which produces the HTML for a form. How can I customize this HTML?

Upvotes: 0

Views: 57

Answers (2)

kjarsenal
kjarsenal

Reputation: 934

if I understand your question correctly, it's actually quite simple. The format, taken from the django docs, is as follows:

<form action="/contact/" method="post">
{{ form.non_field_errors }}
<div class="fieldWrapper">
    {{ form.subject.errors }}
    <label for="id_subject">Email subject:</label>
    {{ form.subject }}
</div>
<div class="fieldWrapper">
    {{ form.message.errors }}
    <label for="id_message">Your message:</label>
    {{ form.message }}
</div>
<div class="fieldWrapper">
    {{ form.sender.errors }}
    <label for="id_sender">Your email address:</label>
    {{ form.sender }}
</div>
<div class="fieldWrapper">
    {{ form.cc_myself.errors }}
    <label for="id_cc_myself">CC yourself?</label>
    {{ form.cc_myself }}
</div>

the complete instructions can be found here: https://docs.djangoproject.com/en/dev/topics/forms/ just scroll down to the "Customizing the Form Template" section

Upvotes: 1

Jack Shedd
Jack Shedd

Reputation: 3531

form.as_p renders the form using internal Django logic (basically a big string of fields wrapped in paragraph tags)

You can't customize that (unless you override the as_p method on your Form subclass).

What you can do is just create your own HTML and manually render the form fields within it.

So, in your mypage.html you could do:

<form>
{{ form.username }}
{{ form.password }}
</form>

There are numerous methods available on each field, just read the docs: https://docs.djangoproject.com/en/dev/ref/forms/api/

Upvotes: 0

Related Questions