我想测试我的Django表单,但是我收到了这个错误
django.core.exceptions.ValidationError: ['ManagementForm data is missing or has been tampered with']
这样做:
self.client.post(self.url, {"title" : 'title', "status" : 2, "user" :1})
我的模特只需要那些领域......
谢谢:)
编辑1: 这是表格:
class ArticleAdminDisplayable(DisplayableAdmin):
fieldsets = deepcopy(ArticleAdmin.fieldsets)
list_display = ('title', 'department', 'publish_date', 'status', )
exclude = ('related_posts',)
filter_horizontal = ['categories',]
inlines = [ArticleImageInline,
ArticlePersonAutocompleteInlineAdmin,
ArticleRelatedTitleAdmin,
DynamicContentArticleInline,
ArticlePlaylistInline]
list_filter = [ 'status', 'keywords', 'department', ]
class ArticleAdmin(admin.ModelAdmin):
model = Article
关于文章模型,有太多的继承,所以你要相信我所需的唯一字段(模型)是标题,状态和用户。
答案 0 :(得分:0)
Formsets需要拥有ManagementForm
。
查看this website和this post,为您指明正确的方向。
答案 1 :(得分:0)
好的,所以根据你的form
判断,你有很多正在使用的django插件。我应该问你的全部test
,但我想我可能会理解一些问题的来临。
当您self.client.post
时,您确实在查看view
,而不一定是表格。 {"title" : 'title', "status" : 2, "user" :1}
是client
为post
的3个值。
Input Field : Data(Value of the Field)
title :'title' # A string
status : 2 # The number 2
user : 1 # The number 1
这是一些对我有用的测试代码。希望它可以帮助你。
forms.py
from .models import CustomerEmployeeName
class EmployeeNameForm(ModelForm):
class Meta:
model = CustomerEmployeeName
fields = [
'employee_choices',
'first_name',
'middle_name',
'last_name',
]
test_forms.py
from django.test import TestCase
from .forms import EmployeeNameForm
class TestEmployeeNameForm(TestCase):
"""
TESTS: form.is_valid
"""
# form.is_valid=True
# middle_name not required.
# middle_name is blank.
def test_form_valid_middle_optional_blank(self):
name_form_data = {'first_name': 'First', # Required
'middle_name': '', # Optional
'last_name': 'Last', # Required
'employee_choices': 'E', # Required
}
name_form = EmployeeNameForm(data=name_form_data)
self.assertTrue(name_form.is_valid())
view.py
from .forms import EmployeeNameForm
def create_employee_profile(request):
if request.POST:
name_form = EmployeeNameForm(request.POST)
if name_form.is_valid():
new_name_form = name_form.save()
return redirect(new_name_form) #get_absolute_url set on model
else:
return render(request,
'service/template_create_employee_profile.html',
{'name_form': name_form}
)
else:
name_form = EmployeeNameForm(
initial={'employee_choices': 'E'}
)
return render(request,
'service/template_create_employee_profile.html',
{'name_form': name_form}
)
test_views.py
from django.test import TestCase, Client
from service.models import CustomerEmployeeName
class TestCreateEmployeeProfileView(TestCase):
# TEST: View saves valid object.
def test_CreateEmployeeProfileView_saves_valid_object(self):
response = self.client.post(
'/service/', {
'first_name': 'Test', # Required
'middile_name': 'Testy', # Optional
'last_name': 'Testman', # Required
'employee_choices': 'E', # Required
})
self.assertTrue(CustomerEmployeeName.objects.filter(
first_name='Test').exists())
如果您想发布更多代码,我将很乐意看到它。