简体   繁体   中英

Django testing form with modelchoicefield

I amended a form to make a ModelChoiceField so that users can only select categories that they have set up. This is working correctly when I run my app in the browser but fails the test (in that it says the form is not valid), which passes if you remove the ModelChoiceField and allow it to display all categories from the model.

I am happy that the code for the form works as expected and required in the browser; it is the test case that I would like to fix. I imagine there is something obvious I can't see, because I have looked at it too many times.

Extract from test case

def setUp(self):
    user = User.objects.create(username='user', password='')
    self.category = Category.objects.create(id=1, user=user, title='category1')
    self.myitem = MyModel.objects.create(id=1, user=user, title='title1', amount=10, category=self.category)

def test_form_validation_with_valid_data(self):
    user = User.objects.get(username='user')
    now = timezone.now()
    form = MyModelForm({'title': 'title1', 'category': 1,  'amount': 100, 'date': now,}, user)
    self.assertTrue(form.is_valid())

Extract from forms.py

class MyModelForm(forms.ModelForm):

    class Meta:
        model = MyModel
        fields = ('title', 'category', 'amount', 'date',)

    category = forms.ModelChoiceField(queryset=None)

    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user')
        super(MyModelForm, self).__init__(*args, **kwargs)
        self.fields['category'].queryset = Category.objects.filter(user=self.user)

您需要以kwarg身份传递user

form = MyModelForm({'title': 'title1', 'category': 1,  'amount': 100, 'date': now,}, user=user)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM