简体   繁体   English

Django is_valid()无法与modelformset_factory一起使用

[英]Django is_valid() not working with modelformset_factory

I've created a simple contact form using the modelformset_factory to build the form in the view using the DB model. 我使用modelformset_factory创建了一个简单的联系表单,以使用DB模型在视图中构建表单。 The issue that I am having is that the is_valid() check before the save() is not working. 我遇到的问题是在save()无法正常工作之前进行了is_valid()检查。 When I submit the form with empty fields it still passes the is_valid() and attempts to write to the DB. 当我提交带有空字段的表单时,它仍会传递is_valid()并尝试写入数据库。

I would like the is_valid() check to fail when the fields are empty so that the user can be directed to the form again with an error message. 我希望在字段为空时is_valid()检查失败,以便可以通过错误消息再次将用户定向到该表单。 I believe that there is a simple solution to this. 我相信对此有一个简单的解决方案。 Do you know what I am missing in my code? 您知道我的代码中缺少什么吗?

Thanks. 谢谢。

Code: 码:

models.py models.py

class Response(models.Model):
    name = models.CharField(max_length=50,verbose_name='Your Name:')
    email = models.CharField(max_length=50,verbose_name='Email:')
    phone = models.CharField(max_length=50,verbose_name='Phone Number:')
    apt_size = models.CharField(max_length=25,
                                choices=APT_CHOICES,
                                verbose_name='Apt Size:')
    movein_at= models.DateField(verbose_name='Desired Move-In Date')
    community = models.CharField(max_length=50,
                                 choices=COMMUNITY_CHOICES,
                                 verbose_name='Community You Are Interested In:')
    referred_by = models.CharField(max_length=50,
                                   choices=REFERRED_CHOICES,
                                   verbose_name='Found Us Where?')
    referred_other = models.CharField(blank=True,max_length=50,verbose_name='If Other:')
    comments = models.TextField(verbose_name='Comments:')
    created_at = models.DateTimeField(auto_now_add=True)
    def __unicode__(self):
        return self.name

views.py views.py

from summitpark.contact.models import * 
from django.shortcuts import render_to_response
from django.forms.models import modelformset_factory

def form(request):
    contact_form_set = modelformset_factory(Response,fields=('name','email','phone',
                                                            'apt_size','movein_at',
                                                            'community','referred_by',
                                                            'comments'),
                                                    exclude=('id'))
    if request.method == 'POST':
        formset = contact_form_set(request.POST)
        if formset.is_valid():
            formset.save()
            return render_to_response('contact/confirm.html')
        else: 
            return render_to_response('contact/form.html',{'formset':formset})
    else:
        formset = contact_form_set(queryset=Response.objects.none())
        return render_to_response('contact/form.html',{'formset':formset}

Solution: 解:

class BaseContactFormSet(BaseModelFormSet):
def clean(self):
    if any(self.errors):
        return
    for form in self.forms:
        name = form['name'].data
        if not name:
            raise forms.ValidationError, "Please Complete the Required Fields

Your issue is that providing 0 items is a valid formset, there is no minimum validation. 您的问题是,提供0个项目是有效的表单集,没有最低验证要求。 I'd provide a custom BaseModelFormset subclass that's clean() method just checked for a minimum of one obj. 我将提供一个自定义BaseModelFormset子类,该子类的clean()方法仅检查了至少一个obj。

Did you really want a formset ? 您是否真的想要一个formset I suspect if you have a contacts form with only one instance of the Response in then you want a ModelForm ... 我怀疑如果您只有一个Response实例的联系人表单,那么您需要ModelForm ...

class ResponseForm(forms.ModelForm):
    class Meta:
        model = Response
        fields=('name','email','phone',
               'apt_size','movein_at',
               'community','referred_by',
               'comments')

As for which fields are allowed to be blank and which aren't, make sure it does the right thing in the admin first, then the ModelForm will do exactly the right thing (that is how the admin makes its forms after all). 至于允许哪些字段为空白,哪些字段不允许为空白,请确保首先在管理员中执行正确的操作,然后ModelForm将执行完全正确的操作(这毕竟是管理员创建表格的方式)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM