Py学习  »  Django

如何用URL参数预先填充表单(Django)

garmars • 4 年前 • 262 次点击  

我想用URL参数作为表单的前缀,但我不确定应该如何配置URL。我需要填写多个字段,所以使用URL参数仍然是最好的方法吗?在我回顾的教程中,大多数情况下只使用GET请求中的1或2个参数。在我看来,我目前只处理一个字段,因为我有一个参数的麻烦。您可以在表单模型中看到我要填充的其他字段。非常感谢您的帮助!

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})

网址.py

 re_path(r'new_opportunity/new_opportunity_confirm/(?P<account_manager>\w+)/$', view=views.new_opportunity_confirm,
         name='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>
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/57047
 
262 次点击  
文章 [ 1 ]  |  最新文章 4 年前
RemyAlves
Reply   •   1 楼
RemyAlves    4 年前

这取决于您是否希望参数成为url的一部分,在您的情况下,我建议您不要这样做,但是让我们看看这两种方法。

获取参数(url?var1=小马&var2=独角兽): 你可以通过 request.GET.get("var1") ,或 request.GET.get("var1", "default") 如果你想要一个默认值以防找不到它。 在模板中,可以使用 {{ request.GET.var1 }} .

您需要配置url来捕获所需的部分,并且需要在接收视图中有一个参数来获取url中的部分:

def new_opportunity_confirm(request, account_manager):

然后,您可以像访问任何其他变量一样访问它,并将其发送到您的模板(如果您想在那里访问它)。

同样,第二种方式似乎不适合你想要达到的目标。 你已经走到一半了,你只是混合了两种方法。