Sonya Voneva
Sonya Voneva

Reputation: 57

Multiline Charfield Django

How can I make a multi-line CharField in a model form in Django? I don't want to use Textarea, as I want the input to be with limited length. The question is about the field 'description' This is my model:

class Resource(models.Model):
    type = models.CharField(max_length=50)
    name = models.CharField(max_length=150)
    description = models.CharField(max_length=250, blank=True)
    creationDate = models.DateTimeField(default=datetime.now, blank=True)

And this is my form:

class AddNewResourceForm(forms.ModelForm):
    class Meta:
        model = Resource       
        fields = ("name","type","description")

    def __init__(self, *args, **kwargs):
        super(AddNewResourceForm, self).__init__(*args, **kwargs)
        self.fields['name'].widget.attrs.update({'class' : 'new-res-name', 
            'placeholder' : 'max 150 characters'})
        self.fields['type'].widget.attrs.update({'class' : 'new-res-type', 
            'placeholder' : 'max 50 characters'})
        self.fields['description'].widget.attrs.update({'class' : 'new-res-
            description', 'placeholder' : 'max 250 characters'})

Upvotes: 4

Views: 5946

Answers (1)

bonidjukic
bonidjukic

Reputation: 1479

I think that you should use the TextField, making sure to enforce the desired limit, which can be done in 2 steps:

1) Set a max_length attribute on the description field which will make sure that the limit is reflected on the client side.

From the docs:

If you specify a max_length attribute, it will be reflected in the Textarea widget of the auto-generated form field. However it is not enforced at the model or database level.

2) Apply MaxLengthValidator to your field to make sure you have a server-side limit validation as well, e.g.

from django.core.validators import MaxLengthValidator


class Resource(models.Model):
    type = models.CharField(max_length=50)
    name = models.CharField(max_length=150)
    description = models.TextField(max_length=250, blank=True,
                                   validators=[MaxLengthValidator(250)])
    creationDate = models.DateTimeField(default=datetime.now, blank=True)

Upvotes: 6

Related Questions