Я пишу тест, который следует логике моих взглядов:
Просмотр 1:
- Отображение формы поиска (запрос GET)
- Пользователь использует поискформа (POST-запрос)
- Форма поиска проверена по запросу. POST querydict
- Если допустимо, HttpReponseRedirect для другого представления
Просмотр 2:
- Отображение формы поиска с использованием kwargs из перенаправления
- Пользователь нажимает на флажки (MultipleChoiceField) - (POST-запрос)
- Форма флажка проверяется на соответствие запросу. Queryydict POST
- Еслидопустимый, другой HttpReponseRedirect
Однако в моем тесте при View 2, шаг 3 и 4, метод form.is_valid () вызывает ошибку «errorlist nonfield» и указывает, что один из вариантов не являетсяимеется в наличии.В тесте я использую значение (идентификатор модели), которое должно отображаться, поэтому я не понимаю, почему это происходит:
test.py:
def test_new_report(self):
self.uploadTestDataRequired()
run_obj = Run.objects.all()[0]
# VIEW 1
data = {
'experiment_name': str(run_obj),
'choice': 'primary',
'submit': 'Search experiment',
}
response = self.client.post('/reporting/', data)
self.assertRedirects(
response,
reverse('results:search_sample_run',
kwargs={
'run_id': run_obj.id,
'choice': 'primary',
}
),
status_code=302,
target_status_code=200,
)
# VIEW 2
sr_obj = SampleRun.objects.filter(run_id=run_obj)
data = {
'run_id': str(run_obj.id),
'sample_run_id': sr_obj[0].id,
'submit': 'Report samples'
}
query_dict = QueryDict('', mutable=True)
query_dict.update(data)
response = self.client.post(response.url, query_dict)
views.py:
Вид 1:
class Search(LoginRequiredMixin, GroupRequiredMixin, View):
runsearchform = RunSearchForm
template_name = 'results/search_templates/search_form.html'
def get(self, request, *args, **kwargs):
print('Search View: Get')
context = {
'run_form': self.runsearchform(),
}
return render(request, self.template_name, context)
def post(self, request, *args, **kwargs):
print('Search View: Post')
context = {
'run_form': self.runsearchform(),
'server': server,
}
if request.POST['submit'] == 'Search experiment':
run_form = self.runsearchform(request.POST)
if run_form.is_valid():
print('Run Form is valid')
run_obj = run_form.cleaned_data['experiment_name']
choice = run_form.cleaned_data['choice']
return HttpResponseRedirect(
reverse('results:search_sample_run',
kwargs={'run_id': run_obj.id,
'choice': choice,
}
))
else:
print('Run Form is NOT valid')
print(run_form.errors)
context['run_form'] = run_form
return render(request, self.template_name, context)
Вид 2:
class SearchSampleRun(LoginRequiredMixin, GroupRequiredMixin, View):
samplerunform = SampleRunSearchForm
template_name = 'results/search_templates/samplerun_search_form.html'
def get(self, request, *args, **kwargs):
print('SearchSampleRun View: Get')
context = {
'server': server,
}
self.run_obj = get_object_or_404(Run, id=kwargs['run_id'])
context['run_obj'] = self.run_obj
context['choice'] = kwargs['choice']
self.sample_run_obj = SampleRun.objects.filter(run_id=self.run_obj)
samplerunform = self.samplerunform(initial={
'sr_obj': self.sample_run_obj
})
context['samplerunform'] = samplerunform
context['choice'] = self.choice
return render(request, self.template_name, context)
def post(self, request, *args, **kwargs):
print('SearchSampleRun View: Post')
context = {
'server': server,
}
if request.POST['submit'] == 'Report samples':
samplerunform = self.samplerunform(request.POST)
******* THIS IS THE STEP THAT IS NOT VALIDATING *****
if samplerunform.is_valid():
print('SampleRunForm: VALID')
current_sr_id = samplerunform.cleaned_data['sample_run_id'][0]
to_report_sr_ids = samplerunform.cleaned_data['sample_run_id'][1:]
to_report_sr_ids = '&'.join(to_report_sr_ids)
return HttpResponseRedirect(
reverse('results:variant_sample_run_list',
kwargs={
'sr_id': current_sr_id,
'run_id': kwargs['run_id'],
'choice': kwargs['choice'],
'to_report_sr_ids': to_report_sr_ids,
}
))
else:
print('SampleRunForm: ERRORS')
print(samplerunform.errors)
context['errors'] = samplerunform.errors
self.run_obj = get_object_or_404(Run, id=kwargs['run_id'])
self.choice = kwargs['choice']
self.sample_run_obj = self.obtainCorrectSamples()
samplerunform = self.samplerunform(initial={
'sr_obj': self.sample_run_obj
})
context['samplerunform'] = samplerunform
context['choice'] = self.choice
return render(request, self.template_name, context)
В тесте - нужно ли разделить их на 2 разных теста?Я полагаю, что я получаю эту ошибку из-за того, что форма в представлении 2 имеет начальное значение, и, возможно, этого не происходит в тесте?
спасибо