Django 更新视图在测试期间不会更新对象



我正在为我的视图编写测试,我被UpdateView和POST请求卡住了。对于这个简单的测试,我只尝试更改first_name,但断言失败。我做错了什么?然而,当我调用响应时。它给我的上下文是(它有更新的雇员):

[{'True': True, 'False': False, 'None': None}, {'csrf_token': <SimpleLazyObject: <function csrf.<locals>._get_val at 0x7f070ed6eee0>>, 'request': <WSGIRequest: POST '/employees/7/update'>, 'user': <SimpleLazyObject: <User: testuser@test.com>>, 'perms': <django.contrib.auth.context_processors.PermWrapper object at 0x7f070ecb33d0>, 'messages': <django.contrib.messages.storage.fallback.FallbackStorage object at 0x7f070ed1b130>, 'DEFAULT_MESSAGE_LEVELS': {'DEBUG': 10, 'INFO': 20, 'SUCCESS': 25, 'WARNING': 30, 'ERROR': 40}}, {}, {'object': <Employee: John Smith>, 'employee': <Employee: John Smith>, 'form': <EmployeeUpdateForm bound=True, valid=False, fields=(first_name;last_name;user;position;reports_to;birthday;hire_date;address;phone_number;pfp)>, 'view': <employees.views.EmployeesUpdateView object at 0x7f070ed1b310>}]

测试:

class TestEmployeesUpdateView(TestCase):
def setUp(self):
self.test_user = User.objects.create_user(
username='test_user', email=
'testuser@test.com', password='Testing12345')
self.test_employee = Employee.objects.create(
first_name='Bob', last_name='Smith', user=self.test_user, position='SM',
birthday=date(year=1995, month=3, day=20),
hire_date=date(year=2019, month=2, day=15),
address='...',
)
self.client = Client()

def test_updateview_post(self):
self.client.force_login(user=self.test_user)
response = self.client.post(reverse('employees:employee-update', kwargs={'pk': self.test_employee.pk}), {'first_name': 'John'})
self.test_employee.refresh_from_db()
self.assertEqual(self.test_employee.first_name, 'John')

视图:

class EmployeesUpdateView(LoginRequiredMixin, UpdateView):
model = Employee
template_name = 'employees/employee_details.html'
form_class = EmployeeUpdateForm

和错误:

FAIL: test_updateview_post (employees.tests.test_views.TestEmployeesUpdateView)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/main/dev/project1/employees/tests/test_views.py", line 63, in test_updateview_post
self.assertEqual(self.test_employee.first_name, 'John')
AssertionError: 'Bob' != 'John'
- Bob
+ John

编辑:错误。

你在test_updateview_post()中有一个错别字它是{' first_name ': 'John'}

从你的User, Employee Model来看,我没有看到任何first_name

您的表单无效,请检查response.context['form']。

相关内容

  • 没有找到相关文章

最新更新