문제

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?

도움이 되었습니까?

해결책

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.

다른 팁

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 :(

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top