"""
WSGI config for mymezzanine project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
from mezzanine.utils.conf import real_project_name
from dj_static import Cling
os.environ.setdefault("DJANGO_SETTINGS_MODULE",
"%s.settings" % real_project_name("mymezzanine"))
application = Cling(get_wsgi_application())
# system time zone.
TIME_ZONE = 'Asia/Taipei' (約104列)
# If you set this to True, Django will use timezone-aware datetimes.
USE_TZ = True
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = "zh-tw" (約111列)
# Supported languages
LANGUAGES = (
('en', _('English')),
('zh-tw', _('繁體中文')), (約116列)
)
# A boolean that turns on/off debug mode. When set to ``True``, stack traces
# are displayed for error pages. Should always be set to ``False`` in
# production. Best set to ``True`` in local_settings.py
DEBUG = False
# Whether a user's session cookie expires when the Web browser is closed.
SESSION_EXPIRE_AT_BROWSER_CLOSE = True
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True (約 131列, 將False 改為 True)
from__future__import unicode_literals
fromdjango.conf.urlsimport include, url
fromdjango.conf.urls.i18nimport i18n_patterns
fromdjango.contribimport admin
fromdjango.views.i18nimport set_language
frommezzanine.core.viewsimport direct_to_templatefrommezzanine.confimport settings
# Uncomment to use blog as home page. See also urlpatterns section below.# from mezzanine.blog import views as blog_views
admin.autodiscover()
# Add the urlpatterns for any custom Django applications here.# You can also change the ``home`` view to add your own functionality# to the project's homepage.
urlpatterns = i18n_patterns(
# Change the admin prefix here to use an alternate URL for the# admin interface, which would be marginally more secure.
url("^admin/", include(admin.site.urls)),
)
if settings.USE_MODELTRANSLATION:
urlpatterns += [
url('^i18n/$', set_language, name='set_language'),
]
urlpatterns += [
# We don't want to presume how your homepage works, so here are a# few patterns you can use to set it up.# HOMEPAGE AS STATIC TEMPLATE# ---------------------------# This pattern simply loads the index.html template. It isn't# commented out like the others, so it's the default. You only need# one homepage pattern, so if you use a different one, comment this# one out.
url("^$", direct_to_template, {"template": "index.html"}, name="home"),
# HOMEPAGE AS AN EDITABLE PAGE IN THE PAGE TREE# ---------------------------------------------# This pattern gives us a normal ``Page`` object, so that your# homepage can be managed via the page tree in the admin. If you# use this pattern, you'll need to create a page in the page tree,# and specify its URL (in the Meta Data section) as "/", which# is the value used below in the ``{"slug": "/"}`` part.# Also note that the normal rule of adding a custom# template per page with the template name using the page's slug# doesn't apply here, since we can't have a template called# "/.html" - so for this case, the template "pages/index.html"# should be used if you want to customize the homepage's template.# NOTE: Don't forget to import the view function too!# url("^$", mezzanine.pages.views.page, {"slug": "/"}, name="home"),# HOMEPAGE FOR A BLOG-ONLY SITE# -----------------------------# This pattern points the homepage to the blog post listing page,# and is useful for sites that are primarily blogs. If you use this# pattern, you'll also need to set BLOG_SLUG = "" in your# ``settings.py`` module, and delete the blog page object from the# page tree in the admin if it was installed.# NOTE: Don't forget to import the view function too!# url("^$", blog_views.blog_post_list, name="home"),# MEZZANINE'S URLS# ----------------# ADD YOUR OWN URLPATTERNS *ABOVE* THE LINE BELOW.# ``mezzanine.urls`` INCLUDES A *CATCH ALL* PATTERN# FOR PAGES, SO URLPATTERNS ADDED BELOW ``mezzanine.urls``# WILL NEVER BE MATCHED!# If you'd like more granular control over the patterns in# ``mezzanine.urls``, go right ahead and take the parts you want# from it, and use them directly below instead of using# ``mezzanine.urls``.
url("^", include("mezzanine.urls")),
# MOUNTING MEZZANINE UNDER A PREFIX# ---------------------------------# You can also mount all of Mezzanine's urlpatterns under a# URL prefix if desired. When doing this, you need to define the# ``SITE_PREFIX`` setting, which will contain the prefix. Eg:# SITE_PREFIX = "my/site/prefix"# For convenience, and to avoid repeating the prefix, use the# commented out pattern below (commenting out the one above of course)# which will make use of the ``SITE_PREFIX`` setting. Make sure to# add the import ``from django.conf import settings`` to the top# of this file as well.# Note that for any of the various homepage patterns above, you'll# need to use the ``SITE_PREFIX`` setting as well.# ("^%s/" % settings.SITE_PREFIX, include("mezzanine.urls"))
]
# Adds ``STATIC_URL`` to the context of error pages, so that error# pages can use JS, CSS and images.
handler404 ="mezzanine.core.views.page_not_found"
handler500 ="mezzanine.core.views.server_error"
from__future__import absolute_import, unicode_literals
fromfuture.builtinsimportint, open, strimportosimportmimetypesfromjsonimport dumps
fromdjango.template.responseimport TemplateResponse
try:
fromurllib.parseimport urljoin, urlparse
exceptImportError:
fromurlparseimport urljoin, urlparse
fromdjango.appsimport apps
fromdjango.contribimport admin
fromdjango.contrib.admin.views.decoratorsimport staff_member_required
fromdjango.contrib.admin.optionsimport ModelAdmin
fromdjango.contrib.staticfilesimport finders
fromdjango.core.exceptionsimport PermissionDenied
fromdjango.core.urlresolversimport reverse
fromdjango.httpimport (HttpResponse, HttpResponseServerError,
HttpResponseNotFound)
fromdjango.shortcutsimport redirect
fromdjango.template.loaderimport get_template
fromdjango.utils.translationimport ugettext_lazy as _
fromdjango.views.decorators.csrfimport requires_csrf_token
frommezzanine.confimport settings
frommezzanine.core.formsimport get_edit_form
frommezzanine.core.modelsimport Displayable, SitePermission
frommezzanine.utils.viewsimport is_editable, paginate
frommezzanine.utils.sitesimport has_site_permission
frommezzanine.utils.urlsimport next_url
mimetypes.init()
@staff_member_requireddefset_site(request):
""" Put the selected site ID into the session - posted to from the "Select site" drop-down in the header of the admin. The site ID is then used in favour of the current request's domain in ``mezzanine.core.managers.CurrentSiteManager``. """
site_id =int(request.GET["site_id"])
ifnot request.user.is_superuser:
try:
SitePermission.objects.get(user=request.user, sites=site_id)
except SitePermission.DoesNotExist:
raise PermissionDenied
request.session["site_id"] = site_id
admin_url = reverse("admin:index")
next= next_url(request) or admin_url
# Don't redirect to a change view for an object that won't exist# on the selected site - go to its list view instead.ifnext.startswith(admin_url):
parts =next.split("/")
iflen(parts) >4and parts[4].isdigit():
next="/".join(parts[:4])
return redirect(next)
defdirect_to_template(request, template, extra_context=None, **kwargs):
""" Replacement for Django's ``direct_to_template`` that uses ``TemplateResponse`` via ``mezzanine.utils.views.render``. """
context = extra_context or {}
context["params"] = kwargs
for (key, value) in context.items():
ifcallable(value):
context[key] = value()
return TemplateResponse(request, template, context)@staff_member_requireddefedit(request):
""" Process the inline editing form. """
model = apps.get_model(request.POST["app"], request.POST["model"])
obj = model.objects.get(id=request.POST["id"])
form = get_edit_form(obj, request.POST["fields"], data=request.POST,
files=request.FILES)
ifnot (is_editable(obj, request) and has_site_permission(request.user)):
response = _("Permission denied")
elif form.is_valid():
form.save()
model_admin = ModelAdmin(model, admin.site)
message = model_admin.construct_change_message(request, form, None)
model_admin.log_change(request, obj, message)
response =""else:
response =list(form.errors.values())[0][0]
return HttpResponse(response)
defsearch(request, template="search_results.html", extra_context=None):
""" Display search results. Takes an optional "contenttype" GET parameter in the form "app-name.ModelName" to limit search results to a single model. """
query = request.GET.get("q", "")
page = request.GET.get("page", 1)
per_page = settings.SEARCH_PER_PAGE
max_paging_links = settings.MAX_PAGING_LINKS
try:
parts = request.GET.get("type", "").split(".", 1)
search_model = apps.get_model(*parts)
search_model.objects.search # Attribute checkexcept (ValueError, TypeError, LookupError, AttributeError):
search_model = Displayable
search_type = _("Everything")
else:
search_type = search_model._meta.verbose_name_plural.capitalize()
results = search_model.objects.search(query, for_user=request.user)
paginated = paginate(results, page, per_page, max_paging_links)
context = {"query": query, "results": paginated,
"search_type": search_type}
context.update(extra_context or {})
return TemplateResponse(request, template, context)
@staff_member_requireddefstatic_proxy(request):
""" Serves TinyMCE plugins inside the inline popups and the uploadify SWF, as these are normally static files, and will break with cross-domain JavaScript errors if ``STATIC_URL`` is an external host. URL for the file is passed in via querystring in the inline popup plugin template, and we then attempt to pull out the relative path to the file, so that we can serve it locally via Django. """
normalize =lambda u: ("//"+ u.split("://")[-1]) if"://"in u else u
url = normalize(request.GET["u"])
host ="//"+ request.get_host()
static_url = normalize(settings.STATIC_URL)
for prefix in (host, static_url, "/"):
if url.startswith(prefix):
url = url.replace(prefix, "", 1)
response =""
(content_type, encoding) = mimetypes.guess_type(url)
if content_type isNone:
content_type ="application/octet-stream"
path = finders.find(url)
if path:
ifisinstance(path, (list, tuple)):
path = path[0]
if url.endswith(".htm"):
# Inject <base href="{{ STATIC_URL }}"> into TinyMCE# plugins, since the path static files in these won't be# on the same domain.
static_url = settings.STATIC_URL + os.path.split(url)[0] +"/"ifnot urlparse(static_url).scheme:
static_url = urljoin(host, static_url)
base_tag ="<base href='%s'>"% static_url
withopen(path, "r") as f:
response = f.read().replace("<head>", "<head>"+ base_tag)
else:
try:
withopen(path, "rb") as f:
response = f.read()
exceptIOError:
return HttpResponseNotFound()
return HttpResponse(response, content_type=content_type)
defdisplayable_links_js(request):
""" Renders a list of url/title pairs for all ``Displayable`` subclass instances into JSON that's used to populate a list of links in TinyMCE. """
links = []
if"mezzanine.pages"in settings.INSTALLED_APPS:
frommezzanine.pages.modelsimport Page
is_page =lambda obj: isinstance(obj, Page)
else:
is_page =lambda obj: False# For each item's title, we use its model's verbose_name, but in the# case of Page subclasses, we just use "Page", and then sort the items# by whether they're a Page subclass or not, then by their URL.for url, obj in Displayable.objects.url_map(for_user=request.user).items():
title =getattr(obj, "titles", obj.title)
real =hasattr(obj, "id")
page = is_page(obj)
if real:
verbose_name = _("Page") if page else obj._meta.verbose_name
title ="%s: %s"% (verbose_name, title)
links.append((not page and real, {"title": str(title), "value": url}))
sorted_links =sorted(links, key=lambda link: (link[0], link[1]['value']))
return HttpResponse(dumps([link[1] for link in sorted_links]))
@requires_csrf_tokendefpage_not_found(request, *args, **kwargs):
""" Mimics Django's 404 handler but with a different template path. """
context = {
"STATIC_URL": settings.STATIC_URL,
"request_path": request.path,
}
t = get_template(kwargs.get("template_name", "errors/404.html"))
return HttpResponseNotFound(t.render(context, request))
@requires_csrf_tokendefserver_error(request, template_name="errors/500.html"):
""" Mimics Django's error handler but adds ``STATIC_URL`` to the context. """
context = {"STATIC_URL": settings.STATIC_URL}
t = get_template(template_name)
return HttpResponseServerError(t.render(context, request))
4.找出npf/moderna/views.py,只有一行指令。
1
2
3
fromdjango.shortcutsimport render
# Create your views here.
5.把步驟3的程式第67-77行,複製到步驟4的程式
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
fromdjango.shortcutsimport render
fromdjango.template.responseimport TemplateResponse# Create your views here.defdirect_to_template(request, template, extra_context=None, **kwargs):
""" Replacement for Django's ``direct_to_template`` that uses ``TemplateResponse`` via ``mezzanine.utils.views.render``. """
context = extra_context or {}
context["params"] = kwargs
for (key, value) in context.items():
ifcallable(value):
context[key] = value()
return TemplateResponse(request, template, context)
from__future__import unicode_literals
fromdjango.conf.urlsimport include, url
fromdjango.conf.urls.i18nimport i18n_patterns
fromdjango.contribimport admin
fromdjango.views.i18nimport set_language
frommoderna.viewsimport direct_to_templatefrommezzanine.confimport settings
# Uncomment to use blog as home page. See also urlpatterns section below.# from mezzanine.blog import views as blog_views
admin.autodiscover()
# Add the urlpatterns for any custom Django applications here.# You can also change the ``home`` view to add your own functionality# to the project's homepage.
urlpatterns = i18n_patterns(
# Change the admin prefix here to use an alternate URL for the# admin interface, which would be marginally more secure.
url("^admin/", include(admin.site.urls)),
)
if settings.USE_MODELTRANSLATION:
urlpatterns += [
url('^i18n/$', set_language, name='set_language'),
]
urlpatterns += [
# We don't want to presume how your homepage works, so here are a# few patterns you can use to set it up.# HOMEPAGE AS STATIC TEMPLATE# ---------------------------# This pattern simply loads the index.html template. It isn't# commented out like the others, so it's the default. You only need# one homepage pattern, so if you use a different one, comment this# one out.
url("^$", direct_to_template, {"template": "index.html"}, name="home"),
# HOMEPAGE AS AN EDITABLE PAGE IN THE PAGE TREE# ---------------------------------------------# This pattern gives us a normal ``Page`` object, so that your# homepage can be managed via the page tree in the admin. If you# use this pattern, you'll need to create a page in the page tree,# and specify its URL (in the Meta Data section) as "/", which# is the value used below in the ``{"slug": "/"}`` part.# Also note that the normal rule of adding a custom# template per page with the template name using the page's slug# doesn't apply here, since we can't have a template called# "/.html" - so for this case, the template "pages/index.html"# should be used if you want to customize the homepage's template.# NOTE: Don't forget to import the view function too!# url("^$", mezzanine.pages.views.page, {"slug": "/"}, name="home"),# HOMEPAGE FOR A BLOG-ONLY SITE# -----------------------------# This pattern points the homepage to the blog post listing page,# and is useful for sites that are primarily blogs. If you use this# pattern, you'll also need to set BLOG_SLUG = "" in your# ``settings.py`` module, and delete the blog page object from the# page tree in the admin if it was installed.# NOTE: Don't forget to import the view function too!# url("^$", blog_views.blog_post_list, name="home"),# MEZZANINE'S URLS# ----------------# ADD YOUR OWN URLPATTERNS *ABOVE* THE LINE BELOW.# ``mezzanine.urls`` INCLUDES A *CATCH ALL* PATTERN# FOR PAGES, SO URLPATTERNS ADDED BELOW ``mezzanine.urls``# WILL NEVER BE MATCHED!# If you'd like more granular control over the patterns in# ``mezzanine.urls``, go right ahead and take the parts you want# from it, and use them directly below instead of using# ``mezzanine.urls``.
url("^", include("mezzanine.urls")),
# MOUNTING MEZZANINE UNDER A PREFIX# ---------------------------------# You can also mount all of Mezzanine's urlpatterns under a# URL prefix if desired. When doing this, you need to define the# ``SITE_PREFIX`` setting, which will contain the prefix. Eg:# SITE_PREFIX = "my/site/prefix"# For convenience, and to avoid repeating the prefix, use the# commented out pattern below (commenting out the one above of course)# which will make use of the ``SITE_PREFIX`` setting. Make sure to# add the import ``from django.conf import settings`` to the top# of this file as well.# Note that for any of the various homepage patterns above, you'll# need to use the ``SITE_PREFIX`` setting as well.# ("^%s/" % settings.SITE_PREFIX, include("mezzanine.urls"))
]
# Adds ``STATIC_URL`` to the context of error pages, so that error# pages can use JS, CSS and images.
handler404 ="mezzanine.core.views.page_not_found"
handler500 ="mezzanine.core.views.server_error"