python - 在 Django 中测试 POST 请求
问题描述
我的 Django 应用程序中有一个函数可以将产品添加到最喜欢的数据库中。我需要为它写一个测试。除了测试之外的一切都运行完美。
def add(request):
data = {'success': False}
if request.method=='POST':
product_id = request.POST.get('product_id')
sub_product_id = request.POST.get('sub_product_id')
user = request.user
sub_product = Product.objects.get(pk=int(sub_product_id))
original_product = Product.objects.get(pk=int(product_id))
p = SavedProduct(username= user, sub_product=sub_product, original_product = original_product)
p.save()
data['success'] = True
return JsonResponse(data)
我的“产品”来自一个 AJAX 调用,我从这个 HTML 中得到它:
<div class='sub_button'>
<form class="add_btn" method='post'>
<input type="hidden" class="product_id" value="{{ product.id }}">
<input type="hidden" class="sub_product_id" value="{{ sub_product.id }}">
<button class='added btn'><i class='fas fa-save'></i></button>
</div>
而那个 AJAX 调用:
$(".row").on('click', '.sub_button', function(event) {
let addedBtn = $(this);
event.preventDefault();
event.stopPropagation();
var product_id = $(this).find('.product_id').val();
var sub_product_id = $(this).find('.sub_product_id').val();
var url = '/finder/add/';
$.ajax({
url: url,
type: "POST",
data:{
'product_id': product_id,
'sub_product_id': sub_product_id,
'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val()
},
datatype:'json',
success: function(data) {
if (data['success'])
addedBtn.hide();
}
});
});
我的 urls.py:
app_name = 'finder'
urlpatterns = [
path('add/', views.add, name='add'),
path('sear/', views.search, name='sear'),
path('sub/', views.sub, name='sub') ]
这是我正在运行的测试:
class AddDeleteProduct(TestCase):
def setUp(self):
User.objects.create(username='Toto', email='toto@gmail.com')
def test_add_product(self):
old_count = SavedProduct.objects.count()
payload = {'product_id': 12, 'sub_product_id': 22}
response = self.client.post(reverse('finder:add', kwargs=payload))
new_count = SavedProduct.objects.count()
self.assertEqual(new_count, old_count + 1)
但我收到此错误消息:
Traceback (most recent call last):
File "/home/pi/Documents/P_11_before/Pur_Beurre_Reload/finder/tests.py", line 155, in test_add_product
response = self.client.post(reverse('finder:add', kwargs=payload))
File "/home/pi/.local/lib/python3.7/site-packages/django/urls/base.py", line 87, in reverse
return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))
File "/home/pi/.local/lib/python3.7/site-packages/django/urls/resolvers.py", line 677, in _reverse_with_prefix
raise NoReverseMatch(msg)
django.urls.exceptions.NoReverseMatch: Reverse for 'add' with keyword arguments '{'product_id': 12, 'sub_product_id': 22}' not found. 1 pattern(s) tried: ['finder/add/$']
解决方案
您需要的是在您的 html 模板中有输入字段。
网址
path('add/<int:product_id>/<int:sub_product_id>', ...)
意见
def add(request):
data = {'success': False}
if request.method=='POST':
product_id = request.POST.get('product_id')
sub_product_id = request.POST.get('sub_product_id')
user = request.user
sub_product = Product.objects.get(pk=int(sub_product_id))
original_product = Product.objects.get(pk=int(product_id))
p = SavedProduct(username= user, sub_product=sub_product, original_product = original_product)
p.save()
data['success'] = True
return JsonResponse(data)
html
<div class='sub_button'>
<form class="add_btn" method='post'>
<input type="hidden" name="product_id" value="{{ product.id }}">
<input type="hidden" name="sub_product_id" value="{{ sub_product.id }}">
<button class='added btn'><i class='fas fa-save'></i></button>
</div>
测试
class AddDeleteProduct(TestCase):
def setUp(self):
User.objects.create(username='Toto', email='toto@gmail.com')
def test_add_product(self):
old_count = SavedProduct.objects.count()
payload = {'product_id': 12, 'sub_product_id': 22}
response = self.client.post(reverse('finder:add', kwargs=payload))
new_count = SavedProduct.objects.count()
self.assertEqual(new_count, old_count + 1)
推荐阅读
- java - 这个 ThreadLocal 如何防止 Classloader 被 GCed
- javascript - 无论何时开始,如何使css动画同时播放?
- java - wkhtmltopdf 不适用于 Spring Boot 和 Docker
- java - 验证 XML 服务响应的最佳方法是另一个 UniversalFileXML 的一部分,在 java 中有很多节点
- javascript - 查找对象数组中的所有键
- java - 布局约束开始顶部不起作用按钮消失
- javascript - Javascript数组修改
- azure - 在 Azure Web APP 部署任务中从删除中排除文件夹
- javascript - 基于javascript / Vue中另一个对象数组的数组索引排序
- visual-studio-2019 - 如何在 Visual Studio 2019 中创建通用发布配置文件