Asif
Asif

Reputation: 1648

Initial value of inputs in Django not working

I defined an initial value to my title field, but once I execute it, it shows no error and the initial value is not showing in my field how do I solve it? Thanks

def form_view(request):
    if request.method == "POST":
        initial_data = {
            'title': 'default title'
        }
        form = ProductForm(request.POST, initial=initial_data)
        if form.is_valid():
            form.save()
            form = ProductForm()
    else:
        form = ProductForm()
    return render(request, "form.html", {"form": form})

Upvotes: 0

Views: 30

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599796

You've put it in the wrong place. If you want it to show when the form is first rendered, you shouldn't put it in the POST block - which is called when the form is submitted - but the else block.

if request.method == 'POST':
    form = ProductForm(request.POST)
    ...
else:
    form = ProductForm(initial=initial_data)

Upvotes: 2

Related Questions