Set initial value in django model form

Question:

I want to set initial data in model form, how can i do that?

I’ve been looking for an answer but mostly the answer is using initial or instance in view.

Is there a way so we can initialize form field in model form?

views.py

def create_order(request, *args, **kwargs):
# move this thing into model form
initial_data = {
    'user': request.user.username,
    'products': Product.objects.get(pk=kwargs['pk'])
}
form = CreateOrderForm(request.POST or None, initial=initial_data)
if form.is_valid():
    form.save()
    return redirect('homepage')
return render(request, "orders/create_order.html", {"form": form})

forms.py

class CreateOrderForm(forms.ModelForm):

# How to initialize value in this model form?

class Meta:
    model = Order
    fields = ['user', 'products', 'quantity', 'address', 'total_price']
    widgets = {
        # Make user fields disabled
        'user': forms.TextInput(attrs={'disabled': True}),
    }

Thank you.

Asked By: penk

||

Answers:

class CreateOrderForm(forms.ModelForm):

# How to initialize value in this model form?

class Meta:
    model = Order
    fields = ['user', 'products', 'quantity', 'address', 'total_price']


    address = forms.CharField(
            required = True,
            widget = forms.TextInput(
                attrs={
                    'class': 'form-control valid',
                    'name': 'address',
                    'id': 'address',
                    'onfocus': 'this.placeholder = ''',
                    'onblur': "this.placeholder = 'Enter Your Address'",
                    'id': 'address',
                    'type':'text',
                    'placeholder': 'sych as: dhaka, Bangladesh',
                    'value': 'dhaka, Bangladesh'
                    'required' : True
                }
            )
    )

Such way you can set values and add CSS attributes.

Answered By: Jafoor

You can override __init__ to also get your fields, and set their initial like so:

class CreateOrderForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.fields['my_field'].initial = 'my_initial'
Answered By: Brian Destura

Django ModelForm._init__() takes an initial keyword argument. So you can pass in initial values by adding to that during your forms __init__(). For example:

class MyModelForm(forms.ModelForm):

    def __init__(self, **kwargs):
        initial = kwargs.get("initial", {})
        initial["my_field"] = "blah"
        kwargs["initial"] = initial
        
        super().__init__(*args, **kwargs)


Answered By: k0nG

i solved my problem from doc.. from here!
i wanted to send the logged in user, without the user choosing
first of all you need models and use a foreignkey
then you most exclude in forms (if you use all fields) or do not use in fields..

for example..
in models:

class Author(models.Model):
    name = models.CharField(max_length=200)
    user = models.ForeignKey(User, on_delete=models.CASCADE)

in forms:

class AuthorCreateForm(forms.ModelForm):
    class Meta:
        model = Item
        fields = '__all__'
        exclude = ('user', )

in views:

class AuthorCreateView(LoginRequiredMixin, CreateView):
    model = Author
    fields = ['name']

    def form_valid(self, form):
        #here we set default logged in user
        form.instance.user = self.request.user
        return super().form_valid(form)
Answered By: ErfanSafarzad7