作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我尝试编写用于编辑记录及其单元测试的代码。这是我的代码:test_view.py
def test_edit_address(self):
address1 = Address.objects.create(first_name='Edith', last_name='Star', address='Some City', phone_number='123455')
response = self.client.post(
reverse('edit', kwargs={'address_id': address1.id}),
{'first_name': 'Patrick', 'last_name': 'Stars', 'address': 'Other City', 'phone_number': '0123455'})
self.assertEqual(response.status_code, 302)
address1.refresh_from_db()
self.assertEqual(address1.first_name, 'Patrick')
View .py
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import redirect, render
from addressbooksapp.models import Address
from django.contrib import messages
def edit(request, address_id):
if request.method == 'POST':
addresses = Address.objects.get(pk=address_id)
addresses.first_name = request.POST.get('firstname_text')
addresses.last_name = request.POST.get('lastname_text')
addresses.address = request.POST.get('address_text')
addresses.phone_number = request.POST.get('phone_text')
addresses.save()
messages.success(request, ('Record Has Been Edited!'))
return redirect('home')
else:
addresses = Address.objects.get(pk=address_id)
return render(request, 'edit.html', {'addresses': addresses})
models.py
from django.db import models
class Address(models.Model):
first_name = models.CharField(max_length=200)
last_name = models.CharField(max_length=200)
address = models.TextField()
phone_number = models.CharField(max_length=200)
urls.py
from django.urls import path
from addressbooksapp import views
urlpatterns = [
path('', views.home_page, name='home'),
path('delete/<address_id>',views.delete, name='delete'),
path('edit/<address_id>',views.edit, name='edit'),
]
但是当运行测试时,我收到错误“django.db.utils.IntegrityError:NOT NULL 约束失败:addressbooksapp_address.first_name”
最佳答案
您在测试中发送的数据与您在 View 中处理的数据不匹配。在测试中,您发送一个以 first_name
、last_name
、address
和 phone_number
作为键的请求。但在 View 中,您使用 firstname_text
、lastname_text
、address_text
和 phone_text
处理数据。
您可以更改名称,例如在 View 中使用:
def edit(request, address_id):
if request.method == 'POST':
addresses = Address.objects.get(pk=address_id)
addresses.first_name = request.<b>POST['first_name']</b>
addresses.last_name = request.<b>POST['last_name']</b>
addresses.address = request.<b>POST['address']</b>
addresses.phone_number = request.<b>POST['phone_number']</b>
addresses.save()
messages.success(request, ('Record Has Been Edited!'))
return redirect('home')
else:
addresses = Address.objects.get(pk=address_id)
return render(request, 'edit.html', {'addresses': addresses})
我建议在这里使用下标,因此 POST[key]
而不是使用 .get()
方法,因为这样如果 key 会引发错误丢失了。
关于python - 如何测试django中的编辑功能? (错误 django.db.utils.IntegrityError : NOT NULL constraint failed),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59629083/
我是一名优秀的程序员,十分优秀!