Python 属性错误:';httpresponseother';对象没有属性';url';
我想测试一个用户试图登录时的303查看其他状态代码。Django没有处理此状态代码的内置类,因此我构建了一个子类HttpResponse 接下来,我构建了一个测试用例,以在传递有效表单数据时测试视图的响应。但是,测试会引发此错误:Python 属性错误:';httpresponseother';对象没有属性';url';,python,django,Python,Django,我想测试一个用户试图登录时的303查看其他状态代码。Django没有处理此状态代码的内置类,因此我构建了一个子类HttpResponse 接下来,我构建了一个测试用例,以在传递有效表单数据时测试视图的响应。但是,测试会引发此错误:AttributeError:'httpresponseether'对象没有属性“url”。查看Django文档,我看不到任何对具有URL属性的响应对象的引用 如何着手解决此错误,以便服务器在成功执行303查看其他重定向后返回200 OK响应 测试视图.py class
AttributeError:'httpresponseether'对象没有属性“url”
。查看Django文档,我看不到任何对具有URL属性的响应对象的引用
如何着手解决此错误,以便服务器在成功执行303查看其他重定向后返回200 OK
响应
测试视图.py
class TestUserLoginPage(TestCase):
@classmethod
def setUpTestData(cls):
User.objects.create_user(username="User", password="password")
cls.login_creds = {
'username': 'User',
'password': 'password'
}
def test_successful_login_redirect(self):
response = self.client.post(
reverse("login"),
data=self.login_creds,
follow=True
)
self.assertRedirects(response, reverse("photos:main_gallery"), status_code=303)
self.assertTemplateUsed(response, "photos/main_gallery.html")
class LoginPage(View):
def get(self, request):
form = UserAuthenticationForm()
return render(request, 'login.html', context={'form': form})
def post(self, request):
import pdb; pdb.set_trace()
form = UserAuthenticationForm(request, request.POST)
if form.is_valid():
messages.success(request, f"Welcome {request.user}!")
return HttpResponseSeeOther(reverse("photos:main_gallery"))
messages.info(request, "Login Failed. Username not registered.")
form = UserAuthenticationForm()
return render(request, "login.html", context={'form': form})
视图.py
class TestUserLoginPage(TestCase):
@classmethod
def setUpTestData(cls):
User.objects.create_user(username="User", password="password")
cls.login_creds = {
'username': 'User',
'password': 'password'
}
def test_successful_login_redirect(self):
response = self.client.post(
reverse("login"),
data=self.login_creds,
follow=True
)
self.assertRedirects(response, reverse("photos:main_gallery"), status_code=303)
self.assertTemplateUsed(response, "photos/main_gallery.html")
class LoginPage(View):
def get(self, request):
form = UserAuthenticationForm()
return render(request, 'login.html', context={'form': form})
def post(self, request):
import pdb; pdb.set_trace()
form = UserAuthenticationForm(request, request.POST)
if form.is_valid():
messages.success(request, f"Welcome {request.user}!")
return HttpResponseSeeOther(reverse("photos:main_gallery"))
messages.info(request, "Login Failed. Username not registered.")
form = UserAuthenticationForm()
return render(request, "login.html", context={'form': form})
您不应该从HttpResponse
子类化,而应该从HttpResponseRedirectBase
子类化您的自定义响应:
from http import HTTPStatus
from django.http.response import HttpResponseRedirectBase
class HttpResponseSeeOther(HttpResponseRedirectBase):
'''Represents a 303 status code'''
status_code = HTTPStatus.SEE_OTHER
这里是一个参考实施从