[Fixed]-Default value of a form in Django using REMOTE_USER

1👍

Since you can access the value in the view, that is where you should be setting the default value. You use the initial parameter to pass initial values to a form when you instantiate it.

form = TimeSearchForm(initial={'username': request.META['REMOTE_USER']})

Edit

Don’t do it like that anyway, that’s a fragile hack. Use the proper if/else:

if request.method == 'POST':
    form = TimeSearchForm(request.POST)
    if form.is_valid():
        ... whatever ...
else:
    form = TimeSearchForm(initial={'username': request.META['REMOTE_USER']})
return ...

Leave a comment