Home > Enterprise >  Adding a linebreak into a django form
Adding a linebreak into a django form

Time:01-01

beginner here!

i've created a Django form and it works but all the fields are in the same line when i open the page, could someone help please?

that's my code, it works but they all stay in the same line

class NewListingForm(forms.Form):
    title = forms.CharField(label="Title", max_length=64)
    description = forms.CharField(label="Description", max_length=200)

CodePudding user response:

In your template write this:

{{ form.as_p }}

CodePudding user response:

You can also add additional styling (bootstrap) to your form. This is an example of my contact form used in production:

class ContactForm(forms.Form):
    name = forms.CharField(max_length = 40, label = False, required = True,error_messages={'required': 'Name is required'},
    widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Name*'})
    )
    email = forms.EmailField(max_length = 40, label = False, required = True,error_messages={'required': 'Email is required'},
    widget=forms.EmailInput(attrs={'class': 'form-control', 'placeholder': 'Email*'})
    )
    confirm_email = forms.EmailField(max_length = 40, label = False, required = True,error_messages={'required': 'Email is required'},
    widget=forms.EmailInput(attrs={'class': 'form-control', 'placeholder': 'Confirm Email*'})
    )
    subject = forms.CharField(max_length = 40, label = False, required = True,error_messages={'required': 'Subject is required'},
    widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Subject*'})
    )
    message = forms.CharField(max_length = 300, label = False, required = True,error_messages={'required': 'Message is required'},
    widget=forms.Textarea(attrs={'class': 'form-control', 'placeholder': 'Message*'})
    )
    ###Requires django-recaptcha###
    pip/pip3 install django-recaptcha
    ###add 'captcha' to installed apps in settings.py###
    from captcha.fields import ReCaptchaField
    captcha = ReCaptchaField(label=False,error_messages={'required': 'reCaptcha verification required'})
    ###

    def clean(self):
        cleaned_data = super().clean()
        email = cleaned_data.get("email")
        confirm_email = cleaned_data.get("confirm_email")

        if email and confirm_email and email != confirm_email:
            msg = "Emails must match"
            self.add_error('email', msg)
            self.add_error('confirm_email', msg)
  • Related