完全なソリューションの例を次に示します。すべてこの優れた投稿から派生したものです。
これは、同じことを繰り返すことなく、サイトの複数のページに招待フォームを含めたいというシナリオに基づいています。
招待状.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>