【问题标题】:How can show variable in UI in django from view function?如何从视图函数在 django 的 UI 中显示变量?
【发布时间】:2022-11-30 14:04:23
【问题描述】:

我想在 UI 中显示 pro 的值但没有获取,这是我的测试视图函数代码。pro 的值是使用 django 会话变量从以前的函数获取的。

@api_view(['GET', 'POST'])
def test(request):
    pro = request.session.get('j')
    print("Request ID from Index View : ", pro)

    if request.method == "POST":
        form = TestForm(request.POST)

        if form.is_valid():
            print("Form is Valid")
            selected = form.cleaned_data.get('myfield')
            print(selected)

        else:
            # rq = request_id["request_id"]
            s = sql()
            query = f"""update request_form_db.request_form_mymodel
                                                   set is_approved=1
                                                   where request_id = '{pro}' """
            print(query)
            s.update_query(query)
            print("Updated Successfully")

            form = TestForm()
    else:
        form = TestForm()
    context = {'form': form, 'pro': pro}
    return render(request, 'test.html', context)

这是我的 html 代码 test.html

<form action ="{% url 'test' %}" method="POST">
    <div class="form_data">

        {% csrf_token %}
         <br><br>

        {{form.myfield}}
         <label><b>Git Id</b></label> <br><br>

<br><br>
        {{form.pro}}
     <input type="submit" value="Submit" class="btn btn-success" />

form.myfield 返回我想要的但 pro 变量的值没有得到。请帮忙

【问题讨论】:

    标签: django django-models django-rest-framework django-views django-forms


    【解决方案1】:

    只需传递与您在上下文中创建的密钥相同的密钥。你不必使用{{ form.pro }}

    context = {'form': form, 'pro': pro}
    

    在 html 中你可以渲染:

    {{ pro }}
    

    【讨论】:

    • 谢谢,它奏效了。
    猜你喜欢
    • 1970-01-01
    • 2018-07-23
    • 2023-03-24
    • 2014-09-26
    • 1970-01-01
    • 1970-01-01
    • 2014-02-09
    • 2020-01-11
    • 2016-02-24
    相关资源
    最近更新 更多