django动态模型将无法验证

时间:2012-08-23 20:43:40

标签: python django dynamic django-forms

  

可能重复:
  Validating a form with overloaded init

我花了整整一个下午试图弄清楚我在这里做错了什么,而且我知道这将是一件令人尴尬的事情。当用户填写表单时,位置选择框取决于用户的国家/地区,并相应地列出不同的城市。

模特&的ModelForm

class Cars(models.Model):
    owner = models.ForeignKey(User)
    name = models.CharField(max_length=25)
    location = models.PositiveIntegerField(default=1)
    created = models.DateTimeField(default=utc_time)

class CarsForm(ModelForm):
    def __init__(self, country, *args, **kwargs):
        super(CarsForm, self).__init__(*args, **kwargs)
        self.fields['location'] = forms.ModelChoiceField(queryset=Cities.objects.filter(country=country))

    class Meta:
        model = Cars
        exclude = ('owner', 'created',)

查看

def new_car(request):
    if request.method == u'POST' and request.is_ajax():
        form = CarsForm(request.POST)
        if form.is_valid():
                      etc...

根据stackoverflow的建议,我编辑了modelform init 以允许传递country变量。表单创建和html显示很好,一切都很好,只是现在表单不会验证。

更新: 好吧,看起来我(意思是'你')让它运转起来。有些事情是丑陋的,一旦修好就可以了:

  • 位置字段类型已更改为foreignkey,更正了 数据不匹配问题
  • 修改了init以接受国家作为kwarg
  • 表单验证现在将变量作为kwarg传递 CarsForm(request.POST,country = country)

SUCCESS!在一个小时之内。非常感谢大家!!

2 个答案:

答案 0 :(得分:1)

您的更改使country成为第一个参数,但您将POST数据作为第一个参数传递。 form = CarsForm(request.POST)

答案 1 :(得分:1)

这是解决方案,或者您的复制粘贴存在问题;)

您已正确定义了过度使用的__init__方法,但实际上并未传递country参数;这样做会是这样的:

form = CarsForm(country, request.POST)

这意味着request.POST始终存储在country中,并且永远不会传递给父类的__init__方法。

如果表单没有数据,is_valid()将始终返回False

附注:SkillForm来自哪里?应该是CarsForm

相关问题