在我的表单中,有一个选择字段,其选择取决于用户的条件。 表单初始化时,表单会从request.user中获取用户。
我的问题是,如何在表单的单元测试中设置用户信息?
我收到如下错误消息:
错误:test_form_valid(zmock.tests.test_forms.TestForm) 追溯(最近一次通话): 文件“ D:\ dp \ opc_community \ zmock \ tests \ test_forms.py”,行16,在test_form_valid中 'msg':'mymsg', init 中的文件“ D:\ dp \ opc_community \ zmock \ forms.py”,第23行 self.user = kwargs.pop('user') KeyError:“用户”
下面是我编写的测试和相关的python代码。
test_forms.py
from django.test import TestCase
from ..forms import EntryPostForm
class TestForm(TestCase):
fixtures = ['myfixture.json', ]
def test_form_valid(self):
login_result = self.client.login(email='foo@bar.com', password='foobar1234', )
self.assertTrue(login_result)
form = EntryPostForm(data={
# 'user': self.request.user,
'title': 'mytitle',
'msg': 'mymsg',
})
self.assertTrue(form.is_valid())
forms.py
from django import forms
from .models import Entry
CHOICES_THREE = [
(1, 'PUBLIC'),
(2, 'FORUM USER ONLY'),
(3, 'PREMIUM USER ONLY'),
]
CHOICES_TWO = [
(1, 'PUBLIC'),
(2, 'FORUM USER ONLY'),
]
class EntryPostForm(forms.ModelForm):
postto = forms.ChoiceField(widget=forms.Select, choices=CHOICES_THREE)
class Meta:
model = Entry
fields = ['title', 'msg', 'postto']
def __init__(self, *args, **kwargs):
self.user = kwargs.pop('user')
super(EntryPostForm, self).__init__(*args, **kwargs)
if self.user.is_staff or self.user.groups.filter(name='mygroup').exists():
self.fields['postto'].choices = CHOICES_THREE
else:
self.fields['postto'].choices = CHOICES_TWO
views.py
from django.views.generic import CreateView
from .models import Entry
from .forms import EntryPostForm
class CreatingView(CreateView):
form_class = EntryPostForm
model = Entry
def get_form_kwargs(self):
kwargs = super(CreatingView, self).get_form_kwargs()
kwargs['user'] = self.request.user
return kwargs