我最近读了一本关于Python中TDD的书,并认为我可以开始遵循这种模式。
但是第一个问题已经出现,我似乎无法解决。
HTML form (declared in forms.py)
发布并打印时,得到以下输出:
<QueryDict: {'csrfmiddlewaretoken': ['...'], 'personal_interests': ['3', '1']}>
为了测试此视图,到目前为止,我已经尝试过使用Django客户端进行测试:
response = self.client.post('/',
data={'reading': False,
'investing': True,
'traveling': True})
response = self.client.post('/', {'personal_interests': ['3', '1']})
也尝试过作为元组:
response = self.client.post('/', {'personal_interests': ('3', '1'),})
但是这些似乎都不发送我想要发送的数据。
谢谢。
views.py:
def home_page(request):
default_customer, _ = Customer.objects.get_or_create(name="John", surname="Doe")
default_customer.interests.clear()
form = InterestsForm()
if request.method == 'POST':
form = InterestsForm(request.POST)
if form.is_valid():
for key, value in form.cleaned_data.items():
for interest in value:
filtered_interest, _ = Category.objects.get_or_create(name=interest)
default_customer.interests.add(filtered_interest)
default_customer.save()
return redirect('/user/'+str(default_customer.id)+'/interests')
else:
messages.error(request, "An error has occured. Check all the fields.")
return redirect('/')
context = {'form': form}
return render(request, 'home.html', context)
forms.py:
class InterestsForm(forms.Form):
personal_interests = forms.ModelMultipleChoiceField(
widget=forms.CheckboxSelectMultiple,
queryset=Category.objects.all().order_by('name'),
required=False,
label='Interests')
class Meta:
model = Category
答案 0 :(得分:0)
我发现错误出在哪里...测试数据库和普通数据库不同,因此我在测试时缺少在数据库中创建的对象。
所以我要做的就是创建项目,然后发送POST
response = self.client.post('/', {'personal_interests': ['3', '1']})
的工作原理,其中“ 3”和“ 1”是对象的pk。
这是固定代码。
def test_can_save_a_POST_request(self):
Customer.objects.get_or_create(name="John", surname="Doe")
reading_interest, _ = Category.objects.get_or_create(name="reading")
investing_interest, _ = Category.objects.get_or_create(name="investing")
traveling_interest, _ = Category.objects.get_or_create(name="traveling")
post_data = {'personal_interests': [str(investing_interest.id),
str(traveling_interest.id)]}
response = self.client.post('/',
data=post_data)
new_customer = Customer.objects.first()
customer_interests = [category.name for category in new_customer.interests.all()]
self.assertNotIn('reading', customer_interests)
self.assertIn('traveling', customer_interests)
self.assertIn('investing', customer_interests)