Django表单验证不起作用

时间:2016-01-19 16:27:04

标签: python django django-forms django-views

我有一个基于模型的表单,但验证不起作用。

当我提交带有空值的表单时,我收到错误:

  

KeyError' id_proveedor'

我的模特:

class Cambio_Precio(models.Model):
      id_precio = models.AutoField(primary_key=True)
      id_proveedor = models.ForeignKey(Proveedor,db_column='id_proveedor', verbose_name='Proveedor')
      id_codigo = ChainedForeignKey(Codigo_Corto,chained_field="id_proveedor",chained_model_field="id_proveedor",show_all=False,auto_choose=True,verbose_name='Codigo Corto')
      anio = models.CharField(max_length=4,blank=False,null=False)
      mes = models.CharField(max_length=2,blank=False,null=False)
      dia = models.CharField(max_length=2,blank=False,null=False)
      precio_nominal = models.DecimalField(max_digits=9,decimal_places=4,blank=False,null=False)
      precio = models.DecimalField(max_digits=9,decimal_places=4,blank=False,null=False)
      revenue = models.DecimalField(max_digits=9,decimal_places=4)
      moneda = models.CharField(max_length=2)
      codigo_as = models.CharField(max_length=15,blank=True,null=True,verbose_name='Codigo AS400')
      imp_rifas = models.BooleanField(verbose_name='Imp rifas y encuestas')      
      bizflow_id = models.CharField(max_length=50,blank=True,null=True)
      estado = models.BooleanField()
      usuario = models.CharField(max_length=50)
      fecha_registro = models.DateTimeField()

我的表格:

class CambioPrecioForm(forms.ModelForm):
      id_proveedor = forms.ModelChoiceField(queryset=Proveedor.objects.all().order_by('nombre'),required=True,label='Proveedor')
      anio = forms.IntegerField(label='A&ntilde:o')
      mes = forms.ChoiceField(
               choices = (
                          ('01',"Enero"),
                          ('02',"Febrero"),
                          ('03',"Marzo"),
                          ('04',"Abril"),
                          ('05',"Mayo"),
                          ('06',"Junio"),
                          ),
               widget = forms.Select(attrs={'style': 'width:100px'}),required=True
              )
      dia = forms.IntegerField(widget = forms.NumberInput(attrs={'style': 'width:80px'}),required=True)
      precio_nominal = forms.DecimalField(widget = forms.NumberInput(attrs={'style': 'width:100px'}),required=True)
      precio = forms.DecimalField(widget = forms.NumberInput(attrs={'style': 'width:100px'}),required=True)
      revenue = forms.DecimalField(widget = forms.NumberInput(attrs={'style': 'width:100px'}),required=True)
      moneda = forms.ChoiceField(
               choices = (
                          ('$',"$"),('L',"L"),
                          ),
               widget = forms.Select(attrs={'style': 'width:50px'})
             ,required=True )
      def __init__(self,*args,**kwargs):
         super(CambioPrecioForm,self).__init__(*args,**kwargs)

      class Meta:
            model = Cambio_Precio
            exclude = ['usuario','estado','fecha_registro']

      def clean(self):
          cleaned_data = super(CambioPrecioForm, self).clean()
          idp = cleaned_data['id_proveedor']
          idc = cleaned_data['id_codigo']
          mesv = cleaned_data['mes']
          diav = cleaned_data['dia']
          prenv = cleaned_data['precio_nominal']
          prefv = cleaned_data['precio']
          bizv = cleaned_data['bizflow_id']
          aniov = cleaned_data['anio']

          try:             Cambio_Precio.objects.get(id_proveedor=idp,id_codigo_id=idc,mes=mesv,dia=diav,anio=aniov)
              raise forms.ValidationError('Ya se registrado un cambio de precio para esta misma fecha')
          except Cambio_Precio.DoesNotExist:
              pass

          return cleaned_data

我的观点:

@login_required(login_url='/login/')
def CambioPrecioView(request):
    if request.method == 'POST':
       form = CambioPrecioForm(request.POST)
       provf = request.POST.get('id_proveedor')
       codf = request.POST.get('id_codigo')
       mesf = request.POST.get('mes')
       diaf = request.POST.get('dia')
       precionf = request.POST.get('precio_n')
       preciof = request.POST.get('precio')
       if form.is_valid():
          obj = form.save(commit=False)
          obj.usuario = request.user
          obj.estado = 0
          obj.fecha_registro = datetime.datetime.now()
          obj.save()
          alarma = Alarma_Precio()
          spalarma = alarma.precio(provf,codf,preciof)
          return HttpResponseRedirect('/home/')
    else:
       form = CambioPrecioForm()

    return render_to_response("cambioprecioform.html",
                              {'form':form},
                              context_instance=RequestContext(request))

在我验证的表单中,用户可以插入相同代码和相同日期的数据。

该模型包含一些

字段
  

Null = True,空白= True

但对于其他领域我需要验证该字段必须是必需的,但不起作用。

如果我填写所有字段,表单无任何问题,但如果必填字段为空,则会收到错误

  

KeyError field_name

当视图到达

时会引发错误
If form.is_valid():

非常感谢任何建议或指南

提前致谢

1 个答案:

答案 0 :(得分:3)

问题在于clean方法的这一部分。

def clean(self):
    cleaned_data = super(CambioPrecioForm, self).clean()
    idp = cleaned_data['id_proveedor']

您无法假设cleaned_data中存在任何字段。

您应该更改代码,以便在访问之前检查该值是否出现在cleaning_data中。

def clean(self):
    cleaned_data = super(CambioPrecioForm, self).clean()
    if 'id_proveedor' in cleaned_data:
        idp = cleaned_data['id_proveedor']
        # do something with idp
    else:
        # don't use idp in this branch