Migration clashes with forms.py

前端 未结 5 539
轮回少年
轮回少年 2020-12-11 05:12

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 defin

5条回答
  •  既然无缘
    2020-12-11 05:40

    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()]
    

提交回复
热议问题