1

Consider the following model

class Book(models.Model):
    name   = models.CharField(max_length=100)
    author = models.ForeignKey(Author) 

class Author(models.Model):
    name = models.CharField(max_length=50)

I want a form to enter a book & author name (both as text input). I don't want a ModelChoiceField for Author. If the author doesn't exist, I'll create it in my view. I can achieve that by declaratively defining author_name field & it's max_length like this:

class BookForm(ModelForm):
    author_name = forms.CharField(max_length=50)

    class Meta:
        model = Book
        fields = ['name']

How can I avoid hard-coding the max_length for author_name in BookForm? Can I deduce it from the linked Author model somehow?

user
  • 17,781
  • 20
  • 98
  • 124

2 Answers2

1

Referring to: programmatically obtain the max_length of a Django model field:

To obtain the max_length of a Model's field,

You can use Author._meta.get_field('name').max_length.

Community
  • 1
  • 1
pcoronel
  • 3,833
  • 22
  • 25
0

Maybe you can use TextField?

Please see: Django CharField vs TextField

ps. if this is not a good idea, please do not downvote me. I tried to add comment as suggestion, but I don't have enough points to do so :(

Community
  • 1
  • 1
trikoder_beta
  • 2,800
  • 4
  • 15
  • 17
  • OK, no downvotes but this answer isn't correct. I don't want to remove the `max_length` restriction, rather I want to have the same restriction on my model fields & form fields without repeating the constant `max_length`. – user May 05 '14 at 14:49