Skip to content

Instantly share code, notes, and snippets.

@rg3915
Created December 23, 2022 05:28
Show Gist options
  • Save rg3915/0dc4bc76f8f0016ea27284e9cd60ba2f to your computer and use it in GitHub Desktop.
Save rg3915/0dc4bc76f8f0016ea27284e9cd60ba2f to your computer and use it in GitHub Desktop.
django form default value

Objetivo: definir um valor default para um campo, simples né?

Pega a visão:

  • __init__
class MyForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.fields['preco'].initial = 0.0
  • initial na views
def my_create(request):
    my_form = MyForm(request.POST or None, initial={'preco': 0.0})

https://docs.djangoproject.com/en/4.1/ref/forms/api/#initial-form-values

  • Apelando com Javascript
document.getElementById("id_preco").defaultValue = "0"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment