python - 如何使用测试客户端填写 Django 表单

标签 python django forms model admin

我想测试我的 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

关于文章模型有太多的继承,所以你必须相信我唯一需要的字段(模型)是标题、状态和用户。

最佳答案

好的,从您的 form 来看,您有很多正在使用的 django 插件。我应该问你完整的test ,但我想我可能明白问题出在哪里了。

当您self.client.post ,你真的在​​查view而不一定是形式。 {"title" : 'title', "status" : 2, "user" :1}是您的 client 的 3 个值是 post ing。

Input Field : Data(Value of the Field)
title       :'title'  # A string
status      : 2       # The number 2
user        : 1       # The number 1

这是一些对我有用的测试代码。希望对你有帮助。

表格.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())

查看.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}
                )

测试 View .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())

如果您想发布更多代码,我很乐意查看。

关于python - 如何使用测试客户端填写 Django 表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50138500/

相关文章:

python - 如何创建一个包含原始数据帧中所有空值的数据帧?

python - Django MEDIA_URL 和 MEDIA_ROOT

python - Django/MySQL 中的间隙检测

django - Django 模板中的嵌套 block

javascript - 用于表单验证的 Rails Way + 无提交按钮

python - 如果不属于 Python 中的一组匹配模式,则删除字符串中的字符

python - 如果找到某些字符串,则提取链接和文本 - BeautifulSoup

python - 如何处理 Python Selenium 重复加载模式并保持 DRY?

javascript - FIrefox 不会阻止发送的提交事件

jQuery get Select 选项值显示未定义错误