Search code examples
python-3.xdjangodjango-forms

Django migrate error on first migration due to forms Meta class using User


I am getting the auth_user does not exist error on manage.py migrate when I try to migrate my app for the first time. This is due to the following part in one of my forms:

    class MyForm(ModelForm):
        def __init__(self, *args, **kwargs):
               ***dothings and super init***
        def clean(self):
               ***dothings****
    
    # This is where it goes wrong:
    class Meta:
        owner_choices_base = User.objects.values_list('username', flat=True)
        owner_choices = [(c, c,) for c in owner_choices_base]
        owner_choices.insert(0, (None, None,))
        model = SomeModel
        widgets = {
            'owner': forms.Select(choices=owner_choices)
            }

It seems this executes before any of the migrations are done and it will see that User related things actually don't exist yet. It works nicely when I delete the Meta part and after that recreate it. Now I would like to have an app that works without having to comment out code for the first time you create it, but I have no idea how to get around this issue while still being able to populate my "special" owner field with users and I hope someone here will have an idea.

For more information on why the Meta class is there: The owner field in the form is just a charfield, but I want to make it a forms.Select widget with the choices from User (so any current User account). So anything that makes that work just as nicely as this (without making it a foreignkey relation, which it should not be!) is also fine!

See above what I did


Solution

  • It seems that during my testing I overlooked some logical solutions. The code works when putting it in the init of the form:

    class MyForm(ModelForm):
        def __init__(self, *args, **kwargs):
               ***dothings and super init***
               owner_choices_base = User.objects.values_list('username', flat=True)
               owner_choices = [(c, c,) for c in owner_choices_base]
               owner_choices.insert(0, (None, None,))
               self.fields['owner'].widget = forms.Select(choices=owner_choices)
    
        def clean(self):
               ***dothings****