[Django]-How to set a default value on a form when it's excluded?

4👍

DealershipForm(request.POST, instance=Dealership(my_field="my_value"))

Should work.

EDIT:

Your code after modification:

def my_view(request):
    if request.method == 'POST':
        form = DealershipForm(request.POST, instance=Dealership(entred_by=User(id=2))
        if form.is_valid():
            form.save()
            messages.success(request, 'Dealership added.')
    else:
        form = DealershipForm()
    return response(request, template='misc/my_template.html',
                    vars={'form':form})

Edit after your comment:

def my_view(request):
    if request.method == 'POST':
        instance = Dealership()
        instance.entered_by_id = 2
        form = DealershipForm(request.POST, instance=instance)
        if form.is_valid():
            form.save()
            messages.success(request, 'Dealership added.')
    else:
        form = DealershipForm()
    return response(request, template='misc/my_template.html',
                    vars={'form':form})

Leave a comment