Django 1.9 form.is_valid在ModelForm上失败

时间:2016-04-19 13:55:47

标签: python django forms

当我有两个字段时,我的模型表单完美运行:标题和文件。我决定在我的模型表单中添加一些额外的字段,现在我无法让form.is_valid()返回true。

查看

def upload_view(request):  
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        print request.POST
        print request.FILES
        if form.is_valid():
            print "Form valid"
            upload = form.save()
            path = change_name(upload)
            runscript.delay(upload.pk, (str(upload.author.id) + '_' + str(upload.id)), path, setting, permutations, biohel_runs, attributes)
            return render(request, 'upload/submitted.html', {'title': upload.title, 'link': 'job/' + str(upload.id)})
        else:
            form = UploadFileForm()
            return render(request, 'upload/upload_view.html', {'error': "Sorry, try submitting your form again", 'form': form})
    else:
        form = UploadFileForm()


    return render(request, 'upload/upload_view.html', {'form': form})

模板

{{ error }}
    {{ form.errors }}
    {% if form.non_field_errors or form.errors %}
        <div class="error-list-block">
            <p>
                Please correct the errors below - Ensure all required fields
                are completed.
            </p>
            <ul>
                {% for error in form.non_field_errors|add:form.errors %}
                    <li>{{ error }}</li>
                {% endfor %}
            </ul>
        </div>
    {% endif %}
    <form class="upload" method="post" action="../upload/" enctype="multipart/form-data">{% csrf_token %}
        <label for="{{ form.title.id_for_label }}">{{ form.title.label }}</label>
            {{ form.title }}
        <span style="margin:0 auto;"><label for="{{ form.file.id_for_label }}">{{ form.file.label }}</label>
        {{ form.file }}</span>

        <div style="margin:10px auto;">
            <label for="{{ form.setting.id_for_label }}">{{ form.setting.label }}</label>
                {{ form.setting }}
             <label for="{{ form.permutations.id_for_label }}">{{ form.permutations.label }}</label>
                {{ form.permutations }}
             <label for="{{ form.biohel_runs.id_for_label }}">{{ form.biohel_runs.label }}</label>
                {{ form.biohel_runs }}
             <label for="{{ form.attributes.id_for_label }}">{{ form.attributes.label }}</label>
                {{ form.attributes }}
        </div>

模型

class Upload(models.Model):
    SETTING = (
        ('1', '1'),
        ('2', '2'),
        ('3', '3'),
        ('4', '4'),
    )

    PERMUTATIONS = (
        ('10', '10'),
        ('50', '50'),
        ('100', '100'),
        ('200', '200'),
    )

    BIOHEL = (
        ('250', '250'),
        ('500', '500'),
        ('1000', '1000'),
        ('2500', '2500'),
    )

    ATTRIBUTES = (
        ('10', '10'),
        ('50', '50'),
        ('100', '100'),
        ('200', '200'),
    )
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    author = models.ForeignKey(settings.AUTH_USER_MODEL, default=1)
    title = models.CharField(max_length=20)
#TODO - change status to be a text field and merge with error
    status = models.BooleanField(default=False)
    error = models.BooleanField(default=False)
    submit_date = models.DateTimeField(
            default=timezone.now)
    start_date = models.DateTimeField(
            blank=True, null=True)
    finish_date = models.DateTimeField(
            blank=True, null=True)#TODO change to unique name
    file = models.FileField(upload_to='experiments', null=True)
    result = models.FileField(null=True)
    setting = models.PositiveSmallIntegerField(default=1, choices=SETTING)
    permutations = models.PositiveSmallIntegerField(default=10, choices=PERMUTATIONS)
    biohel_runs = models.PositiveSmallIntegerField(default=250, choices=BIOHEL)
    attributes = models.PositiveSmallIntegerField(default=10, choices=ATTRIBUTES)

表格

from django import forms

from .models import Upload

class UploadFileForm(forms.ModelForm):

    class Meta:
        model = Upload
        fields = ('title', 'file', 'setting', 'permutations', 'biohel_runs', 'attributes')

当我提交应该是完全有效的表格时,我无法让它验证。模板中的错误处理都不会显示任何错误。这是POST和FILE值的打印输出。你可以看到没有什么遗漏!重申一下,当我只有两个字段时会起作用:title和file。

<QueryDict: {u'title': [u'sadsda'], u'biohel_runs': [u'250'], u'permutations': [u'10'], u'setting': [u'1'], u'attributes': [u'10'], u'csrfmiddlewaretoken': [u'EntGKVQhYqjnxYTIh6v8135Ic3JHZPRw']}>
<MultiValueDict: {u'file': [<InMemoryUploadedFile: 1_652a60b7-ff84-4b9d-bac0-623417de3d9d.arff (application/octet-stream)>]}>

感谢您抽出宝贵时间阅读我的问题

1 个答案:

答案 0 :(得分:4)

在else子句中,通过将新表单实例分配给变量,删除对表单实际产生的任何错误的所有引用。  所以你需要删除这个

else:
    form = UploadFileForm()  # Remove me!

您的代码没有其他问题,您的表单无效。

事实证明你还有4个字段PositiveIntegerFields,但他们的选择都是字符串,所以要么将字段更改为CharField,要么将选项更改为整数

(10, '10'),