[英]Django Form validation won't work
我有一個基於模型的表單,但是驗證無法正常工作。
當我使用空值提交表單時,出現錯誤:
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ñ: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))
在我驗證的表單中,用戶可以插入相同代碼和相同日期的數據。
該模型有一些領域
空=真,空白=真
但是對於其他字段,我需要驗證該字段是否必須是必需的,但是不起作用。
如果我填寫了所有字段,則表單可以正常使用,但是如果必填字段中的任何一個為空,則會出現錯誤
KeyError field_name
當視圖到達
If form.is_valid():
任何建議或指導方針將不勝感激
提前致謝
問題是您的clean
方法的這一部分。
def clean(self):
cleaned_data = super(CambioPrecioForm, self).clean()
idp = cleaned_data['id_proveedor']
您不能假定cleaned_data
中將出現任何字段。
您應該更改代碼以在訪問值之前檢查該值是否出現在cleaned_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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.