【问题标题】:Django how to use request data as form in an html templateDjango如何在html模板中使用请求数据作为表单
【发布时间】:2020-01-16 10:11:45
【问题描述】:

我正在使用 Django rest 框架 rest-auth 进行登录和注册。但我不想使用可浏览的 API 作为我的 UI。我正在构建自己的表单。

所以我正在使用这样的自定义登录网址:

path('rest-auth/customlogin', CustomLoginView.as_view(), name='rest_login'),

其中CustomLoginView 定义为:

class CustomLoginView(LoginView):

    def get(self, request):
        return render(request, "api/test_template.html")

现在在test_template.html,我想要两个输入字段:emailpassword。如果我没有用模板覆盖,则显示在可浏览 API 中的相同字段。

我不确定如何将请求数据放入模板。 (如果电子邮件和密码字段驻留在请求数据中,是否正确?)

test_template.html

{% block content %}
  <div class="row">
    <h3>Login</h3><hr/>
  {# I am not sure how to use input fields here where the data inputted goes in the email and password rest-auth fields#}
  </div>
{% endblock %}

【问题讨论】:

    标签: django django-templates django-rest-auth django-request


    【解决方案1】:

    您需要定义一个表单

    class LoginForm (forms.Form)
        username = forms.CharField(widget = forms.TextInput())
        password = forms.CharField(widget = forms.PasswordxInput())
    

    将其添加到您的视图中

    class CustomLoginView(LoginView):
       form_class = LoginForm
        def get(self, request):
            return render(request, "api/test_template.html")
    

    然后在你的模板中

    <form method="post" action="">
        {{ form.username}}
        {{form.password }}
    </form>
    

    【讨论】:

    • 我为这个表单导入什么库? allauth.account.formsdjango.contib.auth.forms ?还是自定义表格?在那种情况下我该如何实现它?
    • 既然你刚刚学习,就把它放在你的视野之上。你需要from django import forms在文件的顶部
    • 在模板中看不到表单。这是为什么?另外,我只是在学习,是的,但最终这将成为一个实时站点
    • 尝试form=LoginForm 而不是form_class
    猜你喜欢
    • 2015-07-16
    • 2019-09-15
    • 2013-11-19
    • 2017-06-26
    • 2015-07-20
    • 1970-01-01
    • 1970-01-01
    • 2015-10-14
    • 2021-04-14
    相关资源
    最近更新 更多