自定义Django表单中的Clean()方法未被调用

时间:2017-07-06 05:17:37

标签: django forms validation raise validationerror

我需要验证依赖于多个字段的 Experiment 类中的条件。我指定了一个' clean'我的 ExperimentForm 中的方法,但永远不会引发验证方法。完美显示模型的验证错误。

这就是forms.py的样子:

from django import forms
from django.utils.translation import ugettext, ugettext_lazy as _

class ExperimentForm(forms.Form):
    name = forms.CharField(max_length=254)
    student_n = forms.IntegerField()
    expert_n = forms.IntegerField()
    student_cmd_n = forms.IntegerField()
    expert_cmd_n = forms.IntegerField()
    is_active = forms.BooleanField()

    error_messages = {
        'insufficient_assignments': _("The total number of commands to be evaluated must be"
                  "Greater than 28. Right now it's  %(command_number)"),
    }

    def clean(self):
        cleaned_data = super(ExperimentForm, self).clean()
        s_n = cleaned_data.get("student_n")
        e_n = cleaned_data.get("expert_n")
        s_cmd_n = cleaned_data.get("student_cmd_n")
        e_cmd_n = cleaned_data.get("expert_cmd_n")
        command_number = s_n*s_cmd_n + e_n*e_cmd_n

        if command_number < 28:
            raise forms.ValidationError(
                self.error_messages['insufficient_assignments'],
                code='insufficient_assignments',
                params={'command_number': command_number},
            )
        return self.cleaned_data

这是我的views.py

from __future__ import unicode_literals
from django.shortcuts import render
from django.http import HttpResponse
from django.template import loader
from django.core.urlresolvers import reverse_lazy
from vacs.forms import ExperimentForm
from django.views.generic import TemplateView,ListView
from django.views.generic.edit import FormView, CreateView, UpdateView, DeleteView
from django.views.generic.detail import DetailView
from vacs.models import Experiment

class ExperimentView(FormView):
    template_name = 'vacs/experiment.html'
    form_class = ExperimentForm
    success_url = '/vacs/experiments/'

    def form_valid(self, form):
        return super(ExperimentView, self).form_valid(form)

class ExperimentDetailView(DetailView):
    model = Experiment

class ExperimentListView(ListView):
    model = Experiment

class ExperimentCreateView(CreateView):
    model = Experiment
    success_url = reverse_lazy('experiment_list')
    fields = ['name', 'student_n', 'expert_n', 'student_cmd_n', 'expert_cmd_n']

class ExperimentUpdateView(UpdateView):
    model = Experiment
    success_url = reverse_lazy('experiment_list')
    fields = ['is_active' ]

class ExperimentDeleteView(DeleteView):
    model = Experiment
    success_url = reverse_lazy('experiment_list')

models.py按以下方式定义:

# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
from django.core.validators import MaxValueValidator, MinValueValidator
from django.utils.encoding import python_2_unicode_compatible
from django.contrib.auth.models import User
from django.db import models
from jsonfield import JSONField
import collections

class Experiment(models.Model):
    name = models.CharField(max_length=200)
    student_n = models.IntegerField(default=0,
            validators=[MinValueValidator(0)])
    expert_n = models.IntegerField(default=0,
            validators=[MinValueValidator(0)])
    student_cmd_n  = models.IntegerField(default=2,
            validators=[MinValueValidator(2)])
    expert_cmd_n  = models.IntegerField(default=1,
            validators=[MinValueValidator(1)])
    is_active = models.BooleanField(default=True)
    replications = JSONField(load_kwargs={'object_pairs_hook': collections.OrderedDict},
            blank=True)

最后,模板experiment_form.html:

{% extends "vacs/base.html" %}
{% load widget_tweaks %}
{% block content %}

{% if form.errors %}
<div class="alert alert-danger" role="alert">
    Form error!
</div>
{% endif %}

<form method="post">{% csrf_token %}
    {{ form.as_p }}
    <input type="submit" value="Submit" />
</form>

{% endblock %}

谢谢!

2 个答案:

答案 0 :(得分:0)

您需要覆盖模型的save方法。

所以要运行clean_fields()clean()将以下方法添加到模型中

def save(self, *args, **kwargs):
    self.full_clean()
    return super().save(*args, **kwargs)

答案 1 :(得分:0)

在表单处理期间运行三种类型的清洁方法。这些通常在您在计算机上调用is_valid()方法时执行 表格。

Django documentation