Python 在Django格式中设置初始值
我的应用程序中有一个模型: models.py:Python 在Django格式中设置初始值,python,django,web-applications,Python,Django,Web Applications,我的应用程序中有一个模型: models.py: class bdAccesorios(models.Model): fdClienteAcc=models.CharField(max_length=35) fdProveedorAcc=models.CharField(max_length=60) fdSkuAcc=models.CharField(max_length=30) fdNombreAcc=models.CharField(max_length=60
class bdAccesorios(models.Model):
fdClienteAcc=models.CharField(max_length=35)
fdProveedorAcc=models.CharField(max_length=60)
fdSkuAcc=models.CharField(max_length=30)
fdNombreAcc=models.CharField(max_length=60)
fdCostoAcc=models.DecimalField(max_digits=8, decimal_places=2)
fdUnidadAcc=models.CharField(max_length=30)
fdExistenciaAcc=models.IntegerField()
fdAuxAcc=models.CharField(max_length=60, default="0")
然后,我有一个表单向模型中添加新条目
class fmAccesorios(ModelForm):
class Meta:
model=bdAccesorios
fields='__all__'
我无法做到的是表单以初始值开始,到目前为止我在视图中所做的是这样的,但是字段显示为空白
views.py
def vwCrearAccesorio(request):
vrCrearAcc=fmAccesorios(initial={'fdClienteAcc':"foo"}) ###Here is the problem ###
if request.method == "POST":
vrCrearAcc=fmAccesorios(request.POST)
if vrCrearAcc.is_valid():
vrCrearAcc.save()
return redirect('/')
else:
vrCrearAcc=fmAccesorios()
return render(request,"MyApp/CrearAccesorio.html",{
"dtCrearAcc":vrCrearAcc
})
更多信息:
我知道我可以在表单中使用以下代码来设置初始值
def __init__(self, *args, **kwargs):
super(fmAccesorios, self).__init__(*args, **kwargs)
self.fields['fdClienteAcc'].disabled = True
self.fields['fdClienteAcc'].initial = "foo"
但我不能使用它,因为我需要变量“foo”来动态更改,我的最终目标是使用
使用request.user.username变量,然后使用该变量从另一个模型中获取另一个值在您的视图中,您必须将当前的实例传递到如下表单:
def vwCrearAccesorio(request):
vrCrearAcc=fmAccesorios(initial={'fdClienteAcc':"foo"}) # this will not be used because you reassign `vrCrearAcc` later
if request.method == "POST":
vrCrearAcc=fmAccesorios(request.POST, initial={'fdClienteAcc':"foo"}) # pass it here
if vrCrearAcc.is_valid():
vrCrearAcc.save()
return redirect('/')
else:
vrCrearAcc=fmAccesorios(initial={'fdClienteAcc':"foo"}) # and here
return render(request,"MyApp/CrearAccesorio.html",{
"dtCrearAcc":vrCrearAcc
})
谢谢很好。不客气:)