2016-04-11 10 views
0

私が作成した模擬ウェブサイトのDjangoテストを現在作成しようとしています。ここ
は私のテストで:Djangoテストはテストユーザーを受け付けません

class ListingsTestCase(TestCase): 
    def test_listing(self): 
     user = User.objects.create_user(username='test') 
     user.set_password('test') 
     user.save() 

     c = Client() 
     c.login(username='test', password='test') 
     category = Category.objects.get_or_create(name='test') 

     t_listing = { 
        'title': 'Test', 
        'email': '[email protected]', 
        'phone_number': '4057081902', 
        'description': 'Test', 
        'category': category, 
        'user': user, 
        } 

     form = ListingForm(data=t_listing) 
     self.assertEqual(form.errors, {}) 
     self.assertEqual(form.is_valid(),True) 

マイモデル:

class Listing(models.Model): 
    user = models.ForeignKey(User) 
    title = models.CharField(max_length = 200) 
    email = models.EmailField(max_length=50) 
    phone_number = models.CharField(max_length=12, default='') 
    listing_price = models.IntegerField(blank=True, null=True) 
    image = models.FileField(upload_to='listing_images') 
    description = models.TextField() 
    created_date = models.DateTimeField(auto_now=True) 
    category = models.ForeignKey('Category', null=True) 

    def __str__(self): 
     return self.title 

ここでは私のListingFormです:

class ListingForm(forms.ModelForm): 
    image = forms.FileField(required=False) 
    class Meta: 
     model = Listing 
     fields = [ 
      'user', 
      'title', 
      'email', 
      'phone_number', 
      'description', 
      'listing_price', 
      'image', 
      'category', 
     ] 
     widgets = {'user': forms.HiddenInput()} 

そして、ここでは、私が取得していますエラーです:

FAIL: test_listing (seller.tests.ListingsTestCase) 
Traceback (most recent call last): 
File "/home/local/CE/mwilcoxen/project/hermes/seller/tests.py", line 35, in test_listing 
self.assertEqual(form.errors, {}) 
AssertionError: {'category': [u'Select a valid choice. That choice is not one of the available choices.'], 'user': [u'Select a valid choice. That choice is not one of the available choices.']} != {} 

私は最初のassertEqualsを使用して何がエラーを投げているのかを確認しました。私はテストユーザーがログインできることを知るためにいくつかのブレークポイントを使用しましたが、もし誰かが私に大きな助けとなる助けを与えることができたら。

+0

あなた 'ListingForm'コードは何してくださいですか? –

+0

ListFormを貼り付けることはできますか? –

+0

がそれを投稿しました。 –

答えて

1

実際のオブジェクトではなくusercategoryのIDを使用してください。

t_listing = { 
    'title': 'Test', 
    'email': '[email protected]', 
    'phone_number': '4057081902', 
    'description': 'Test', 
    'category': category.id, 
    'user': user.id, 

}

注意あなたがその行を変更する必要がありますのでget_or_createは、タプルを返すこと:

category, created = Category.objects.get_or_create(name='test') 
+0

'AttributeError: 'tuple'オブジェクトに属性 'id'がないことを示しています –

+0

Duh、私はそれが私に言いました。私はそれをとても感謝します、これは私が私の髪を引き出したいと思っていた –

関連する問題