Search code examples
pythondjangoweb-applications

Set initial value in a form in Django


I have a model in my application:

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)
    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")

Then, I have a form to add new entries to the model

class fmAccesorios(ModelForm):
    class Meta:
        model=bdAccesorios
        fields='__all__'

What I can't accomplish is that the form starts with an initial value, so far what I have done in my views is this, but the field shows blank

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
    })

MORE INFO:

I know that I can use the following code in my form to set initial values

def __init__(self, *args, **kwargs):
    super(fmAccesorios, self).__init__(*args, **kwargs)
    self.fields['fdClienteAcc'].disabled = True
    self.fields['fdClienteAcc'].initial = "foo"

But I can't use that, because I need the variable "foo" to change dynamically, my ultimate goal is to use the request.user.username variable and then use that variable to get another value from another model


Solution

  • In your view you have to pass the current instance you need to the form like this:

    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
        })