Debug School

rakesh kumar
rakesh kumar

Posted on

How to add textarea and its css in forms in django

To add a label, id attribute, center the textarea, set margin, and adjust the height and width using Django's forms.py, you can customize the field's widget and apply CSS styles. Here's an example:

formspy

from django import forms

class MyForm(forms.Form):
    my_textarea = forms.CharField(
        label='My Label',
        widget=forms.Textarea(attrs={
            'id': 'my-textarea',
            'class': 'centered-textarea',
            'style': 'height: 300px; width: 500px; margin-left: 20px;'
        })
    )
Enter fullscreen mode Exit fullscreen mode

In the above example, we define a MyForm class with a field named my_textarea. We provide the label parameter to set the label text for the field.

To add the id attribute, we include it in the textarea's attrs dictionary as 'id': 'my-textarea'.

For centering the textarea, we add a custom CSS class 'centered-textarea' in the class attribute of the textarea's attrs dictionary.

To adjust the height and width of the textarea, we use the inline style attribute in the textarea's attrs dictionary. In this example, the textarea is set to have a height of 300 pixels and a width of 500 pixels. The margin-left property is set to 20 pixels to add left margin.

Now, you can use this form in your Django view and template to render the customized textarea input. Here's an example:

views.py

from django.shortcuts import render
from .forms import MyForm

def my_view(request):
    form = MyForm()
    return render(request, 'my_template.html', {'form': form})
Enter fullscreen mode Exit fullscreen mode
<form method="POST">
  {% csrf_token %}
  {{ form.my_textarea.label_tag }}
  {{ form.my_textarea }}
  <button type="submit">Submit</button>
</form>
Enter fullscreen mode Exit fullscreen mode

In the template, we use to render the label for the textarea field, and to render the textarea itself.

By customizing the widget attributes in the textarea field of your Django form, you can set the label, id attribute, center the textarea, adjust margin, and modify the height and width of the textarea according to your requirements.

Top comments (0)