使用这个中间件:
class BetaForm(Form):
beta_pass = CharField(required=True)
def clean_beta_pass(self):
data = self.cleaned_data['beta_pass']
if data != settings.BETA_PASS:
raise forms.ValidationError("Invalid Beta pass!")
return data
class BetaView(FormView):
form_class = BetaForm
template_name = "beta.html"
def form_valid(self, form):
response = HttpResponseRedirect(self.request.GET.get("next", "/"))
response.set_cookie(settings.BETA_PASS, '')
return response
def beta_middleware(get_response):
def middleware(request):
if request.path == reverse("beta"):
return get_response(request)
else:
if settings.BETA_PASS in request.COOKIES:
return get_response(request)
else:
return HttpResponseRedirect(
'%s?%s' % (reverse("beta"), urlencode({"next": request.get_full_path()})))
return middleware
这个模板:
<!doctype html>
<title>Welcome to the beta!</title>
<style>
body { text-align: center; padding: 150px; }
h1 { font-size: 50px; }
body { font: 20px Helvetica, sans-serif; color: #333; }
article { display: block; text-align: left; width: 650px; margin: 0 auto; }
a { color: #dc8100; text-decoration: none; }
a:hover { color: #333; text-decoration: none; }
</style>
<article>
<h1>>Welcome to the beta lucky user!</h1>
<div>
<form method="POST">
{% csrf_token %}
{{form}}
<input type="submit">
</form>
</div>
</article>
这个设置:
BETA_PASS="beta"
这条路:
path("beta",BetaView.as_view(),name="beta"),