Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
240 views
in Technique[技术] by (71.8m points)

python - Migration clashes with forms.py

The command python manage.py makemigrations fails most of time due to the forms.py, in which new models or new fields are referenced at class definition level.

So I have to comment each such definitions for the migration to operate. It's a painfull task.

I don't understand why the migration process import the forms.py module. I think that importing models modules should be sufficient.

Is there a way to avoid those errors ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I was having this same issue and found the specific problem. When the migrate command was being called, Django's system checks made their way into my forms.py and then would fail when they encountered a line of code that made a query against a table that the migration was supposed to create. I had a choicefield that instantiated the choices with a database query like this:

university = forms.ChoiceField(
    choices=[('', '')] + [(university.id, university.name) for university in University.objects.all()],
    widget=forms.Select(
        attrs={
            'class': 'form-control',
            'placeholder': 'University',
        }
    ),
    required=True
)

The solution was to remove the query from choices (leaving it just as [('', '')] and then populate the choices in the class's init method instead.

class UniversityForm(forms.Form):

    university = forms.ChoiceField(
        choices=[('', '')],
        widget=forms.Select(
            attrs={
                'class': 'form-control',
                'placeholder': 'University',
            }
        ),
        required=True
    )


def __init__(self, *args, **kwargs):
    super(UniversityForm, self).__init__(*args, **kwargs)

    # Load choices here so db calls are not made during migrations.
    self.fields['university'].choices = [('', '')] + [(university.name, university.name) for university in University.objects.all()]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...