Home > Net >  Formatting Django forms elements in html templates
Formatting Django forms elements in html templates

Time:06-09

I have a contact form that I'm trying to use in one of my Django templates. I created a class for it in forms.py:

class ContactForm(forms.Form):
name = forms.CharField(max_length=100)
email_address = forms.EmailField(max_length=150)
message = forms.CharField(widget = forms.Textarea,max_length=2000)

and added it to my views.py:

def contact(request):
if request.method == 'POST':
    form = ContactForm(request.POST)
    if form.is_valid():
        subject = "Website Inquiry" 
        body = {
        'name': form.cleaned_data['name'], 
        'email': form.cleaned_data['email_address'], 
        'message':form.cleaned_data['message'], 
        }
        message = "\n".join(body.values())

        try:
            send_mail(subject, message, '[email protected]', ['[email protected]']) 
        except BadHeaderError:
            return HttpResponse('Invalid header found.')
        return redirect ("BobbleHead:home")
  
form = ContactForm()
return render(request, "BobbleHead/contact.html", {'form':form})

and am now trying to get the form to render with specific html formatting in my template (contact.html), but am having difficulties.

Previously, I was using the built in Django capabilities to render, like this:

<form action="" method="post">
   {% csrf_token %}
     {{ form.as_p }}
     <button type="submit">Submit</button>
</form>

That worked fine, but I don't like the way it looks on my webpage and wanted to clean up the formatting. I want the form to render with specific formatting, like this:

<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<div >
    <form action="/home" target="_blank">
      {% csrf_token %}
      <div  style="margin:0 -16px 8px -16px">
        <div >
          <div >
          <input  type="text" placeholder="Name" required name="name">
          </div>
        </div>
        <div >
          <input  type="text" placeholder="Email" required name="email_address">
        </div>
      </div>
      <input  type="text" placeholder="Message" required name="message">
      <button  type="submit">SEND</button>
    </form>
  </div>

But I'm not sure how to change the <input> elements in the stylized block to use my django form.

CodePudding user response:

You can add attributes (class, name, etc) to django forms using widgets

class CommentForm(forms.Form):
    name = forms.CharField(widget=forms.TextInput(attrs={'class': 'special'}))
    url = forms.URLField()
    comment = forms.CharField(widget=forms.TextInput(attrs={'size': '40'}))

https://docs.djangoproject.com/en/4.0/ref/forms/widgets/#styling-widget-instances

and in the template refer directly to the fields using {{form.name}}, {{form.comment}} etc to put them anywhere in the template

CodePudding user response:

You can use form attributes, and define error_messages while defining the form and use in the template in the following way.

forms.py

class ContactForm(forms.Form):
    name = forms.CharField(
        widget=forms.TextInput(
            attrs={
                "class": "w3-input w3-border",
                "placeholder": "Name"
            }
        ),
        error_messages={
         'required':'name is required'
        },
        max_length=100
    )
    email_address = forms.EmailField(
        widget=forms.EmailInput(
            attrs={
                "class": "w3-input w3-border",
                "placeholder": "Email",
            }
        ),
        error_messages={
        "required":"Email is required"
        },
        max_length=150
    )
    message = forms.CharField(
        widget=forms.TextInput(
            attrs={
                "class": "w3-input w3-border",
                "placeholder": "Message",
            }
        ),
        error_messages={
        'required':'Message is required'
        },
        max_length=2000
    )

Template file:

<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<div >
    <form action="/home" target="_blank">
      {% csrf_token %}
      <div  style="margin:0 -16px 8px -16px">
        <div >
          <div >
          {{form.name}}
          {% for error in form.name.errors %}
             {{error|striptags}}
          {% endfor %}
          </div>
        </div>
        <div >
          {{form.email}}
          {% for error in form.email.errors %}
            {{error|striptags}}
          {% endfor %}

        </div>
      </div>
      {{form.message}}
      {% for error in form.message.errors %}
      {{error|striptags}}
      {% endfor %}
      
      <button  type="submit">SEND</button>
    </form>
  </div>

The views.py can be remain same, you can also specify other attributes like help_texts etc.

See all form fields of django.

CodePudding user response:

class ContactForm(forms.Form):
    name = forms.CharField(
        widget=forms.TextInput(
            attrs={
                "class": "w3-input w3-border",
                "type": "text",
                "placeholder": "Name",
                "name": "name",
            }
        ),
        max_length=100
    )
    email_address = forms.EmailField(
        widget=forms.TextInput(
            attrs={
                "class": "w3-input w3-border",
                "type": "text",
                "placeholder": "Email",
                "name": "email_address",
            }
        ),
        max_length=150
    )
    message = forms.CharField(
        widget=forms.TextInput(
            attrs={
                "class": "w3-input w3-border",
                "type": "text",
                "placeholder": "Message",
                "name": "message",
            }
        ),
        max_length=2000

    )
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<div >
  <form action="" method="post">
    {% csrf_token %}
    <div  style="margin:0 -16px 8px -16px">
      <div >
        {{ form.name }}
      </div>
      <div >
        {{ form.email_address }}
      </div>
    </div>
    {{  form.message }} 
    <button  type="submit">SEND</button>
  </form>
</div>
  • Related