如何添加"标题"上下文所以它可以在模板中访问。我想它需要以某种方式通过获取请求?将此变量传递给FormView类中的get方法的pythonic方法是什么?
views.py
class IndexView(FormView):
template_name = 'index.html'
form_class = CheckForm
success_url = reverse_lazy('index')
def form_valid(self, form, **kwargs):
context = self.get_context_data(**kwargs)
context['headers'] = form.result()
return super(IndexView, self).form_valid(form)
的index.html
<form action="." method="post" name="url" id="url" novalidate>
{{ form.as_p }}
{% csrf_token %}
<button type="submit">Check</button>
{% if headers %}
{% for k,v in headers %}
{{ k }}: {{ v }}<br>
{% endfor %}
{% else %}
<br>No data
{% endif %}
forms.py
from django import forms
import requests
class CheckForm(forms.Form):
url = forms.URLField(max_length=255, label='')
def result(self):
cd = self.cleaned_data
url = cd['url']
r = requests.get(url)
r.headers
return r
urls.py
urlpatterns = [
url(r'^$', views.IndexView.as_view(), name='index'),
]
答案 0 :(得分:0)
主要问题是重定向成功。这将向同一窗口抛出另一个get请求。在您的情况下,这是不可取的,因为您想要利用表单中的数据。
<强> views.py 强>
import requests
class IndexView(FormView):
template_name = 'index.html'
form_class = CheckForm
def form_valid(self, form, **kwargs):
context = self.get_context_data()
context['headers'] = form.get_headers()
return self.render_to_response(context)
<强> forms.py 强>
import requests
from django import forms
class CheckForm(forms.Form):
url = forms.URLField(max_length=255, label='')
def get_headers(self):
if self.cleaned_data:
url = self.cleaned_data['url']
return requests.get(url).headers
return {}
<强>的index.html 强>
<form action="." method="post" name="url" id="url" novalidate>
{{ form.as_p }}
{% csrf_token %}
<button type="submit">Check</button>
{% if headers %}
{% for k,v in headers.items %}
{{ k }}: {{ v }}<br>
{% endfor %}
{% else %}
<br>No data
{% endif %}
答案 1 :(得分:0)
我很确定您要使用messages
from django.contrib import messages
现在你可以添加一些内容并将其发送到下一个模板。
messages.success(request, u"Success message - text only")
在模板中:
{% if messages %}
<ul class="messages">
{% for message in messages %}
<li{% if message.tags %} class="{{ message.tags }}"{% endif %}>
{% if message.level == DEFAULT_MESSAGE_LEVELS.ERROR %}Important: {% endif %}
{{ message }}
</li>
{% endfor %}
</ul>
{% endif %}