[英]django-registration passing extra_context to Registration Form
[英]Passing context to django-registration's views
我將django-registration與在Github上找到的一組預制模板結合使用,以使用HMAC進行兩步(注冊-激活)工作流程。
我想將像我的網站名稱這樣的全局變量(在上下文處理器中定義)傳遞給django-registration發送的電子郵件。 例如,發送給新注冊人的激活電子郵件或更改了一個密碼。
“問題”是我沒有直接訪問這些視圖的權限。 這就是django-registration的重點,您將其路徑包含在urls.py
文件中,並且一切正常:
urlpatterns = [
url(r'^', include('core.urls')),
url(r'^admin/', admin.site.urls),
url(r'^accounts/', include('registration.backends.hmac.urls')),
]
向這些視圖添加上下文的最省力方法是什么? 我已經創建並成功將上下文傳遞到我自己的視圖中的電子郵件中 (使用上下文處理器):
def send_some_email_view(request):
msg_plain = render_to_string('email_change_email.txt', context, request=request)
msg_html = render_to_string('email_change_email.html', context, request=request)
但是我沒有創建的視圖呢?
編輯:所以我取得了一些進展,找到了django-registration的注冊視圖,並且在其中有此方法:
def send_activation_email(self, user):
"""
Send the activation email. The activation key is simply the
username, signed using TimestampSigner.
"""
activation_key = self.get_activation_key(user)
context = self.get_email_context(activation_key)
context.update({
'user': user
})
subject = render_to_string(self.email_subject_template,
context)
# Force subject to a single line to avoid header-injection
# issues.
subject = ''.join(subject.splitlines())
message = render_to_string(self.email_body_template,
context)
user.email_user(subject, message, settings.DEFAULT_FROM_EMAIL)
我不想在源代碼中覆蓋它,因為那樣會阻止我進行更新。 所以現在的問題變成了:我唯一的出路是編寫一個對該視圖進行子類化並覆蓋該方法的視圖嗎? 這意味着我為django-registartion提供的每個需要發送電子郵件的視圖編寫單獨的視圖...
首先根據供應商視圖創建自己的視圖,然后覆蓋所需的方法:
from registration.backends.hmac.views import RegistrationView
class CustomRegistrationView(RegistrationView):
def get_email_context(self, user):
context = super().get_email_context(user)
return RequestContext(self.request, context)
比看看registration.backends.hmac.urls.py
( 源 )。 他們只是在那里定義了一堆網址。
您可以在添加應用中的一個之前 ,通過添加自己的一個輕松覆蓋其中的一個。
from yourapp import views
urlpatterns = [
# [...]
url(r'^accounts/register/$', views.CustomRegistrationView.as_view(), name='registration_register'),
url(r'^accounts/', include('registration.backends.hmac.urls')),
# [...]
]
在更改必要的內容的同時,您還可以洞悉第三方應用程序中發生的事情,這始終是一個優勢。 這適用於大多數第三方應用程序,而不僅僅是您當前正在使用的應用程序。
這就是我最終要做的事情,這要歸功於達倫斯的回答將我定向到:
# myapp/processors.py
def get_website_name(request):
website_name = 'ExcitingWebsiteThatsComingSoon'
return {'mysite_name': website_name}
# some views.py file
from myapp.processors import get_website_name
class RegistrationViewWithContext(RegistrationView):
def get_email_context(self, user):
context = super().get_email_context(user)
context['req'] = get_website_name(self.request)
return context
基本上,我只是使用我的自定義處理器來注入網站的名稱。 它不像我希望的那樣干凈:雖然在模板中我可以簡單地使用{{ mysite_name}}
,但是在電子郵件模板中我必須使用{{req.mysite_name}}
。 但這確實具有我要實現的DRY風格:如果函數中的變量發生更改,則所有模板都會相應更新。
我會暫時將我的答案標記為正確,如果有新答案,它將相應地進行更新。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.