Reputation: 18529
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?
Upvotes: 1
Views: 344
Reputation: 3971
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
.
Upvotes: 1
Reputation: 2880
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 :(
Upvotes: 0