我是django的新手并试图在html文件中显示一个表单,当我在浏览器上访问此特定页面时,我看不到这些字段。
这是html文件:我可以看到所有内容,但显示的形式为two_factor.html
{% extends 'authentication/base.html' %}
{% block title %}Two Factor{% endblock title %}
{% block two_factor %}
<div class="container">
<h3>Your code</h3>
<form role="form" action="" method="post" enctype="multipart/form-data">
<div class="form-group">
{% csrf_token %}
{{ form }}
<div class="form-group">
<button type="submit" class="btn btn-success">Submit</button>
</div>
</div>
</form>
</div>
{% endblock two_factor %}
my forms.py
class TwoFactorForm(forms.Form):
code = forms.CharField(label='Code', widget=forms.TextInput(attrs={'type': 'text', 'placeholder': 'Your code'}))
my views.py
class TwoFactorView(View):
form_class = TwoFactorForm
template_name = 'authentication/two_factor.html'
def get(self, request):
form = self.form_class(None)
return render(request, self.template_name, {'form': form})
def post(self, request):
form = self.form_class(request.POST)
if form.is_valid():
return redirect('authentication/secret.html')
return render(request, self.template_name, {'form': form})
我在base.html中添加了块。我只看到按钮提交。网址很好。
答案 0 :(得分:0)
将视图类更改为
class TwoFactorView(View):
form_class = TwoFactorForm
template_name = 'authentication/two_factor.html'
def get(self, request):
form = self.form_class()
return render(request, self.template_name, {'form': form})
def post(self, request):
form = self.form_class(request.POST)
if form.is_valid():
return redirect('authentication/secret.html')
return render(request, self.template_name, {'form': form})
而不是使用
form = self.form_class(None)
使用
form = self.form_class()