2

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.

4 Answers 4

9

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'
Sign up to request clarification or add additional context in comments.

3 Comments

thankyou for the answer but can we use something like this : self.fields['user'].initial = request.user or self.fields['product'].initial = product.name ?
It should be the same type as the field, so self.fields['user'].initial = request.user should be fine, self.fields['product'].initial = product.name -- probably not
Thank you this saved me! One typo: should be super().__init__(*args, **kwargs)
2
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.

Comments

2

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)


Comments

1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.