How to Prefill Form with URL Parameters (Django)

Question:

I would like to prefill a form with URL parameters, but I am unsure as to how I should configure my URLs. I need to fill multiple fields, so is using URL parameters still the best method? In the tutorials I have been reviewing, most cases only use 1 or 2 parameters from the GET request. In my view, I am only handling one field currently as I am having trouble with just one parameter. You can see in the form model the other fields I would like to fill. Any help is greatly appreciated!

views.py

def new_opportunity_confirm(request):
    form_class = OpportunityForm

    account_manager = request.GET.get('account_manager')

    form = form_class(initial={'account_manager': account_manager})

    return render(request, 'website/new_opportunity_confirm.html', {'form': form})

urls.py

 re_path(r'new_opportunity/new_opportunity_confirm/(?P<account_manager>w+)/$', view=views.new_opportunity_confirm,
         name='new_opportunity_confirm'),

new_opportunity_confirm.html

<form action="" method="post" name="newOpportunityForm" id="newOpportunityForm">
                {% csrf_token %}
                <div class="field">
                    <label class="label">Account Manager:</label>
                    <div class="select">
                        <select name="account_manager" id="account_manager" required>
                            <option value="{{ form }}">{{ form }}</option>
                        </select>
                    </div>
                </div>
Asked By: garmars

||

Answers:

It depend if you want your parameters to be part of the url or not, and in your case I would suggest not, but let’s see both method.

For GET parameters (url?var1=poney&var2=unicorn):
You do not need to configure your url. Django will do the work for you, you just have to configure what is before the interrogation point.
You can then access those with request.GET.get("var1"), or request.GET.get("var1", "default") if you want a default value in case it’s not found.
In your template, you can access it with {{ request.GET.var1 }}.

For parameters in the url (url/poney/unicorn):
You need to configure the url to capture the part you want, and you need to have a parameter in the receiving view to get the one in the URL:

def new_opportunity_confirm(request, account_manager):

You can then access it like any other variable, and send it to your template if you want to have access to it there.

Again, that second way does not seem fitting to what you want to achieve.
You were halfway there, you just mixed a little bit of both methods.

Answered By: RemyAlves
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.