Django pass a url kwarg into a form.Form

Viewed 190

I'm trying to get initial values for a form.Form class form from url.

urls.py

path('nueva/<client_id>/', new_check_view, name='nueva valoración'),

views.py

def new_check_view(request, client_id):
    my_form = NewCheckForm()
    # print (client_id)
    if request.method == "POST":
        my_form = NewCheckForm(request.POST)
        if my_form.is_valid():
            Check.objects.create(**my_form.cleaned_data)
        else:
            print(my_form.errors)
    
    context = {
    "form": my_form
    }
    return render (request, 'checks/new-check.html', context)

forms.py

class NewCheckForm(forms.Form):
    user_id = forms.ModelChoiceField(
        label='Nombre',
        queryset= Client.objects.all(), 
        initial=client_id,
        )

However, I don't get how to pass that kwargs from the view to the class form.

1 Answers

You should to use initial param. For your code:

from django.shortcuts import get_object_or_404

def new_check_view(request, client_id):
    client = get_object_or_404(Client, pk=client_id)
    my_form = NewCheckForm(initial={'user_id': client})

Remember to remove initial=client_id from NewCheckForm

Related