简体   繁体   中英

AssertionError: 302 != 200 : Couldn't retrieve content: Response code was 302 (expected 200)

i'm trying to test admin and getting AssertionError: 302:= 200: Couldn't retrieve content: Response code was 302 (expected 200)

even i check the solution over here but i already did the same and getting same error.

My model file, admin file, and Testing file are below.

admin.py

from django.contrib import admin

# Register your models here.
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin

from . import models


class UserAdmin(BaseUserAdmin):
    ordering = ['id']
    list_display = ['email', 'name']


admin.site.register(models.User, UserAdmin)

tests/test_admin.py

from django.test import TestCase, Client
from django.contrib.auth import get_user_model
from django.urls import reverse

class AdminSiteTests(TestCase):
    
    def setUp(self):
        self.client = Client()
        self.admin_user = get_user_model().objects.create_user(
            email = 'admin@admin.com',
            password = 'admin'
        )

        self.client.force_login(self.admin_user)
        self.user = get_user_model().objects.create_user(
            email = 'test@londondevapp.com',
            password = 'Test@123',
            name = 'Test 1'
        )
    
    def test_user_listed(self):
        """Test that users are listed on user page"""

        url = reverse('admin:core_user_changelist')
        res = self.client.get(url)

        self.assertContains(res, self.user.name)
        self.assertContains(res, self.user.email)

i fixed with from create_user to create_superuser and it's work! in def setUp() function at admin side code.

it's superuser login stuff so instead of using create_user i put create_superuser and test is OK!

class AdminSiteTests(TestCase):
    
    def setUp(self):
        self.client = Client()
        self.admin_user = get_user_model().objects.create_superuser( <-- #Here
            email = 'admin@admin.com',
            password = 'admin'
        )

        self.client.force_login(self.admin_user)
        self.user = get_user_model().objects.create_user(
            email = 'test@londondevapp.com',
            password = 'Test@123',
            name = 'Test 1'
        )

Here's what google says

The HTTP response status code 302 Found is a common way of performing URL redirection. The HTTP/1.0 specification initially defined this code, and gave it the description phrase "Moved Temporarily" rather than "Found". An HTTP response with this status code will additionally provide a URL in the header field Location

It have redirect event so that's why it gave code 302 cuz it want you to go somewhere that isn't at the page that gonna take you.

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