这是一个完整解决方案的示例。一切都源于这篇优秀的帖子。
这是基于您希望在网站的多个页面上包含邀请表单而不重复自己的情况。
邀请.widgets.py:
from invitations.forms import InvitationForm
from django.middleware.csrf import get_token
from django.template.loader import render_to_string
def invitation_widget_function (request):
# ... blah blah blah
# ... stuff I don't want
# ... to repeat in every view
invitation_form = InvitationForm ()
csrf_token_value = get_token(request)
context = { 'invitation_form': invitation_form,
'csrf_token_value': csrf_token_value }
return render_to_string ( 'invitation_widget_template.html', context )
邀请小部件模板.html:
<form action="/whatever/" method="post">
{% csrf_token %} {# don't do this because it won't work in streamed output #}
{# do this instead: #}
<div style='display:none'>
<input type='hidden' name='csrfmiddlewaretoken value='{{ csrf_token_value }}'/>
</div>
{{ invitation_form }}
<button type="submit">Invite Someone</button>
</form>
视图.py:
from invitations.widgets import invitation_widget_function
from django.shortcuts import render
def page_view (request):
invitation_widget = invitation_widget_function(request)
context = { 'invitation_widget': invitation_widget }
return render (request, 'page_template.html', context )
page_template.html:
<body>
<div>
{% include "some_normal_template.html" %} {# takes context from page_view() #}
{{ invitation_widget }} {# not an include, but a fully rendered string #}
{# took context from invitation_widget_function() -- has csrf token included #}
</div>
</body>