djangodjango-admin

How to set the default/initial value for a field in a Django AdminForm?


I have a Django admin form. And now I want to fill it's initial field with data based on my model. So I tried this:

class OrderForm(forms.ModelForm):
    class Meta:
        model = Order

    email = CharField(initial="null", widget=Textarea(attrs={'rows': 30, 'cols': 100}))

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

        self.request = kwargs.pop('request', None)

        products = kwargs['instance'].products.all()

        self.message = purchase_message % (
            "".join(["<li>" + p.name + ": " + str(p.price) + "</li>" for p in products]),
            reduce(lambda x, y:x + y.price, products, 0)
        )

        # and here I have a message in self.message variable

        super(OrderForm, self).__init__(*args, **kwargs)

At this point i don't know how to access email field to set it's initial value before widget is rendered. How can i do this?


Solution

  • I'm not too sure what you need to set email to, but You can set the initial values in lots of different places.

    Your function def init() isn't indented correctly which i guess is a typo? Also, why are you specifically giving the email form field a TextInput? It already renders this widget by default

    You can set the email's initial value in your form's initialized (def __ init __(self))

    (self.fields['email'].widget).initial_value = "something"
    

    or in the model.py

    email = models.CharField(default="something")
    

    or as you have in forms.py

    email = models.CharField(initial="something")