django 2.0 使用没有 jquery 的表单

django 2.0 work with forms without jquery

从 django 导入表单

class Find(forms.Form):
    object_name = forms.CharField()

views.py
    def get_obj(request, object_name='000'):
        print(object_name)
        form = FindSSK()
        print(request.GET)

urlpatterns = [
    # path(r'ssk/<str:object_name>/', get_obj),
    re_path(r'^(?P<object_name>)#$', get_obj),
    path(r'', get_obj),

]


{% block find %}

<form class="form-inline ml-5" action="#" method="GET">
        {% comment %} {{form}}     {% endcomment %}
    {% comment %} <input type="number" class="form-control" placeholder="Enter obj" aria-label="Search"> {% endcomment %}
    {% comment %} <input  type="text" > {% endcomment %}
    <input type="text" name="object_name" />
    <input class="btn btn-outline-success ml-1 fas fa-search" type="submit" >

    </input>
</form>
{% endblock %}

当我在表单上推送提交时,他会重定向 http://127.0.0.1:8000/?object_name=001

但是 var object_name 窃取了 000 结果打印在 get_obj()

000
<QueryDict: {'object_name': ['001']}>

抱歉英语不好。

您无法获得所需的参数,因为您实际上是将值作为 GET 参数发送。但是 object_name 在您的视图中作为参数和 URL 参数传递给您的 URL 模式,这意味着它应该像 url/object_name/ 一样包含在 URL 中== http://127.0.0.1:8000/001/。不确定这是否更符合您的需求。

要向视图发送数据,您可以像 http://127.0.0.1:8000/?object_name=001 一样使用 POST 请求或 GET 请求。

对于以上两个选项,您不需要将 object_name 作为参数,也不需要 url 模式中的 ^(?P<object_name>)

VIEW: def get_obj(request <s>object_name='000'</s>):
______________________
URL: re_path(r'^$', get_obj),

method="GET":如果你在表单<form class="form-inline ml-5" action="#" method="GET">中使用GET请求,你可以像下面这样检索值

def get_obj(request):
    <b>object_name = request.GET.get('object_name')</b> # object_name is the field name in form
    print(object_name)

method="POST":如果您使用 POST 表单 <form class="form-inline ml-5" action="#" method="POST"> 请求,您可以像下面这样检索值

def get_obj(request):
    object_name = None
    <b>if request.method == 'POST':
        object_name = request.POST.get('object_name')</b>
    print(object_name)

If you use POST request, don't forget to add {% csrf_token %} in your form