[Answer]-Django – Form element's default value error

1👍

initial only works when the form is unbound.

When you click the new post link, you are doing a get request on the page, so the form is unbound and the initial value is used.

When you enter a title and submit, I assume you are doing a post request on the page. Therefore the form is bound, and the initial value will not be used.

I’m afraid I don’t understand the question completely, and you haven’t show much code, so I can’t suggest any work arounds for you. Hope you get it working.

Update following edits to your question

When the data comes from the add_post view, don’t create a bound form, because then the data will be validated and you’ll get the error messages.

Instead, fetch the title from the post data, and use that to create an initial dictionary to instantiate your addForm with.

You need a way to tell whether the post request came from the admin or add post view. You could do this by adding another hidden field to the addForm.

action = forms.CharField(widget=forms.HiddenInput, initial="addform")

Then change your add_post view to something like:

if request.method == 'POST':
    if request.POST.get('action') == 'addform':
        form = addForm(initial={'title': request.POST.get('title'), 'isdraft': True})
    else:
        # your existing code for handling a request post

Leave a comment