How can I get a textarea from model+ModelForm?
Asked Answered
A

3

12

models.py=>

from django.db import models
from django.forms import ModelForm
from datetime import date
import datetime
from django import forms
from django.forms import Textarea

class Post(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField()
    created = models.DateField(auto_now_add=True)
    modified = models.DateField(auto_now_add=True)

    def __unicode__(self):
        return self.title

class PostModelForm(ModelForm):
    class Meta:
        model = Post

But I get a text input not textarea for models.TextField(). Is that a reason of css?

Athletic answered 6/1, 2012 at 16:32 Comment(0)
I
22

I think this section in the documentation should be useful to solve the problem.

from django.forms import ModelForm, Textarea

class PostModelForm(ModelForm):
    class Meta:
        model = Post
        widgets = {
            'content': Textarea(attrs={'cols': 80, 'rows': 20}),
        }
Immunity answered 6/1, 2012 at 16:35 Comment(6)
It's models.CharField(), not forms.CharField(), posting complete example may help.Athletic
Sorry, my previous answer assumed you were using forms directly instead of ModelForm. The new link should provide the information that you need.Immunity
I have tried that but that didn't work, i don't see any height or weight for that textarea.Athletic
He used cols & rows, but you can just as easily put a class into the attrs and style off of that (or put the styles in directly, but why hard-code presentation logic that far down into the back-end?)Buckjumper
@Buckjumper I used the same example as in the documentation, but you're right, it's better to keep presentation and business logic separate.Immunity
@Immunity - no worries, I more meant that for the OP.Buckjumper
B
11

Alternative to jcollardo's solution (same result, different syntax):

from django import forms

class PostModelForm(forms.ModelForm):
    content = forms.CharField(widget=forms.Textarea)
    class Meta:
        model = Post
Buckjumper answered 6/1, 2012 at 17:31 Comment(1)
and add col/row attrs like: content = forms.CharField(widget=Textarea(attrs={'cols':80, 'rows': 20}))Pelagianism
N
1

You are using models not forms, which means you can't use textarea properly. Instead you can try TextField:

field_name = models.TextField( **options)
Nga answered 2/2, 2023 at 17:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.