Modify django simple captcha

Viewed 292

I'm using django-simple-captcha and crispy form

Here is my code:

forms.py

from django import forms
from captcha.fields import CaptchaField


class ContactEntryForm(forms.Form):
    name = forms.CharField(
        label="",
        widget=forms.TextInput(attrs={'placeholder': 'Full Name'})
    )
    email = forms.CharField(
        label="",
        widget=forms.TextInput(attrs={'placeholder': 'Email', 'type': 'email'})
    )
    subject = forms.CharField(
        label="",
        widget=forms.TextInput(attrs={'placeholder': 'Subject'})
    )
    message = forms.CharField(
        label="",
        widget=forms.Textarea(attrs={'placeholder': 'Message', 'rows': 5})
    )
    captcha = CaptchaField()

page.html

<form method="POST">
  {% csrf_token %} {{ contact_entry_form|crispy }}
  <input type="submit" value="Submit" class="btn btn-dark" style="width: 100%" />
</form>

But the image and text fields in the captcha section are too narrow. I want to add some margin between the image and text field. Can I do some HTML formatting on forms.py? For example:

captcha = CaptchaField(attrs={'style': 'margin:10px'})

Or is there any better solution to add some margin from forms.py?

1 Answers

You can add attrs to the form field in forms.py but for me it didn't work correctly when someone typed in the wrong values. The red alerts/div did not show up. Somewhere along the lines the existing class attribute gets overridden.

Here's what I ended up doing:

## forms.py
from django import forms
from captcha.fields import CaptchaField

class ContactForm(forms.Form):
    full_name = forms.CharField(label="Name",required=True)
    from_email = forms.EmailField(label="Email", required=True)
    subject = forms.CharField(required=True)
    message = forms.CharField(widget=forms.Textarea, required=True)
    captcha = CaptchaField(label='Please enter the characters in the image')

And then in your css:

#id_captcha_1 {
    max-width: 100px;
    margin-top: 8px;
}

max-width because it looks silly for the text-input to be so wide and margin-top so that the image doesn't cut into the top of the text-input.

enter image description here

Related