Skip to content

Commit e25a6d4

Browse files
committed
working on code examples
1 parent 701e423 commit e25a6d4

9 files changed

+401
-3
lines changed

content/count.sh

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
#!/bin/bash
2+
wc posts/* pages/*/*.markdown pages/*/*/*.markdown

content/pages/examples/django/django-conf-urls-url.markdown

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ category: page
33
slug: django-conf-urls-url-examples
44
sortorder: 50001
55
toc: False
6-
sidebartitle: django.conf.urls.url Examples
6+
sidebartitle: django.conf.urls.url
77
meta: Python code examples for the url function within the django.conf.urls module of the Django project.
88

99

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
title: django.core.mail.messages.EmailMessage Examples
2+
category: page
3+
slug: django-core-mail-messages-emailmessage-examples
4+
sortorder: 50007
5+
toc: False
6+
sidebartitle: django.core.mail.messages EmailMessage
7+
meta: Python code examples for the EmailMessage function within the django.core.mail module of the Django project.
8+
9+
10+
# django.core.mail.messages.EmailMessage Examples
11+
The
12+
[EmailMessage](https://github.com/django/django/blob/master/django/core/mail/message.py)
13+
class is contained with the
14+
[django.core.mail](https://github.com/django/django/tree/master/django/core/mail)
15+
module within the [Django project](/django.html) code base.
16+
17+
18+
## EmailMessage Example 1 from django-emailmessagetemplate
19+
20+
21+
```python
22+
import copy
23+
24+
from django.core.mail import get_connection
25+
from django.conf import settings
26+
27+
~~from models import EmailMessageTemplate
28+
29+
30+
def send_mail(name, related_object=None, context={}, from_email=None,
31+
recipient_list=[], fail_silently=False, auth_user=None,
32+
auth_password=None, connection=None):
33+
"""
34+
Easy wrapper for sending a single templated message to a recipient list.
35+
The template to use is retrieved from the database based on the name and
36+
related_object (optional) fields.
37+
All members of the recipient list will see the other recipients in the 'To'
38+
field.
39+
If auth_user is None, the EMAIL_HOST_USER setting is used.
40+
If auth_password is None, the EMAIL_HOST_PASSWORD setting is used.
41+
"""
42+
43+
~~ template = EmailMessageTemplate.objects.get_template(name, related_object)
44+
45+
connection = connection or get_connection(username=auth_user,
46+
password=auth_password,
47+
fail_silently=fail_silently)
48+
49+
~~ template.context=context
50+
~~ template.from_email=from_email
51+
~~ template.to=recipient_list
52+
~~ template.connection=connection
53+
54+
~~ return template.send()
55+
```
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
title: django.core.mail.send_mail Examples
2+
category: page
3+
slug: django-core-mail-send-mail-examples
4+
sortorder: 50006
5+
toc: False
6+
sidebartitle: django.core.mail.send_mail
7+
meta: Python code examples for the send_mail function within the django.core.mail module of the Django project.
8+
9+
10+
# django.core.mail.send_mail Examples
11+
[send_mail](https://github.com/django/django/blob/master/django/core/mail/__init__.py)
12+
is a function in [Django](/django.html) that can send an email
13+
using the [EmailMessage](/django-core-mail-messages-emailmessage-examples.html)
14+
class.
15+
16+
17+
## Example 1 from apiserver
18+
19+
20+
[**apiserver/apps/accounts/signals.py**](https://github.com/renjith-tring/apiserver/blob/master/apps/accounts/signals.py)
21+
22+
```python
23+
from django.conf import settings
24+
from django.template import Context, loader
25+
~~from django.core.mail import send_mail,EmailMessage
26+
from django.conf import settings
27+
from django.core.mail import EmailMultiAlternatives
28+
from django.template.loader import render_to_string
29+
from django.utils.html import strip_tags
30+
from django.template.loader import get_template
31+
from django.contrib.auth.decorators import login_required
32+
from django.db.models.signals import post_save
33+
from django.dispatch import receiver
34+
from apps.accounts.models import UserProfile, create_api_key
35+
36+
37+
from django.db import models
38+
models.signals.post_save.connect(create_api_key, sender=UserProfile)
39+
40+
@receiver(post_save,sender=UserProfile)
41+
def send_contact_mail(sender, created, **kwargs):
42+
obj = kwargs['instance']
43+
if created:
44+
subject = "Thank you for registering with us"
45+
to = [obj.email]
46+
verification_code = obj.activation_token
47+
val = {
48+
'site_url': settings.SITE_URL,
49+
'subject':subject,
50+
'verification_code':verification_code,
51+
}
52+
53+
html_content = render_to_string('mails/registration.html',val)
54+
text_content = strip_tags(html_content)
55+
from_email = settings.DEFAULT_FROM_EMAIL
56+
msg_html = render_to_string('mails/registration.html',val)
57+
~~ send_mail(subject, None, from_email,to,html_message=msg_html)
58+
```

content/pages/examples/django/django-db-models-model.markdown

Lines changed: 112 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ category: page
33
slug: django-db-models-model-examples
44
sortorder: 50002
55
toc: False
6-
sidebartitle: django.db.models.Model Examples
6+
sidebartitle: django.db.models.Model
77
meta: Python code examples for the Model class within the django.db.models module of the Django project.
88

99

@@ -14,6 +14,34 @@ class is the superclass for all data stored in [Django](/django.html)
1414
applications.
1515

1616

17+
## Example 1 from django-audit-log
18+
[django-audit-log](https://github.com/vvangelovski/django-audit-log) is a
19+
[code library](https://pypi.org/project/django-audit-log/) that tracks
20+
changes to [Django](/django.html) models. The source code is available
21+
under the
22+
[BSD 3 "New" license](https://github.com/vvangelovski/django-audit-log/blob/master/LICENSE.txt).
23+
24+
[**django-audit-log/audit-log/models/__init__.py**](https://github.com/vvangelovski/django-audit-log/blob/master/audit_log/models/__init__.py)
25+
26+
```python
27+
~~from django.db.models import Model
28+
from django.utils.translation import ugettext_lazy as _
29+
from audit_log.models.fields import CreatingUserField, CreatingSessionKeyField, LastUserField, LastSessionKeyField
30+
31+
~~class AuthStampedModel(Model):
32+
"""
33+
An abstract base class model that provides auth and session information
34+
fields.
35+
"""
36+
created_by = CreatingUserField(verbose_name = _("created by"), related_name = "created_%(app_label)s_%(class)s_set")
37+
created_with_session_key = CreatingSessionKeyField(_("created with session key"))
38+
modified_by = LastUserField(verbose_name = _("modified by"), related_name = "modified_%(app_label)s_%(class)s_set")
39+
modified_with_session_key = LastSessionKeyField(_("modified with session key"))
40+
41+
class Meta:
42+
abstract = True
43+
```
44+
1745

1846
## Example 2 from django-cms
1947
[django-cms](https://github.com/divio/django-cms)
@@ -114,3 +142,86 @@ class Page(models.Model):
114142
on_delete=models.CASCADE,
115143
)
116144
```
145+
146+
147+
## Example 3 from
148+
149+
## Example 4 from mezzanine
150+
151+
152+
[**mezzanine/mezzanine/core/models.py**](https://github.com/stephenmcd/mezzanine/blob/master/mezzanine/core/models.py)
153+
154+
```python
155+
from __future__ import unicode_literals
156+
from future.builtins import str
157+
from future.utils import with_metaclass
158+
159+
from json import loads
160+
try:
161+
from urllib.request import urlopen
162+
from urllib.parse import urlencode
163+
except ImportError:
164+
from urllib import urlopen, urlencode
165+
166+
from django.apps import apps
167+
from django.contrib.contenttypes.fields import GenericForeignKey
168+
~~from django.db import models
169+
from django.db.models.base import ModelBase
170+
from django.template.defaultfilters import truncatewords_html
171+
from django.utils.encoding import python_2_unicode_compatible
172+
from django.utils.html import format_html, strip_tags
173+
from django.utils.timesince import timesince
174+
from django.utils.timezone import now
175+
from django.utils.translation import ugettext, ugettext_lazy as _
176+
177+
from mezzanine.conf import settings
178+
from mezzanine.core.fields import RichTextField, OrderField
179+
from mezzanine.core.managers import DisplayableManager, CurrentSiteManager
180+
from mezzanine.generic.fields import KeywordsField
181+
from mezzanine.utils.html import TagCloser
182+
from mezzanine.utils.models import base_concrete_model, get_user_model_name
183+
from mezzanine.utils.sites import current_site_id, current_request
184+
from mezzanine.utils.urls import admin_url, slugify, unique_slug
185+
186+
187+
user_model_name = get_user_model_name()
188+
189+
190+
def wrapped_manager(klass):
191+
if settings.USE_MODELTRANSLATION:
192+
from modeltranslation.manager import MultilingualManager
193+
194+
class Mgr(MultilingualManager, klass):
195+
pass
196+
return Mgr()
197+
else:
198+
return klass()
199+
200+
201+
~~class SiteRelated(models.Model):
202+
"""
203+
Abstract model for all things site-related. Adds a foreignkey to
204+
Django's ``Site`` model, and filters by site with all querysets.
205+
See ``mezzanine.utils.sites.current_site_id`` for implementation
206+
details.
207+
"""
208+
209+
objects = wrapped_manager(CurrentSiteManager)
210+
211+
class Meta:
212+
abstract = True
213+
214+
~~ site = models.ForeignKey("sites.Site", on_delete=models.CASCADE,
215+
~~ editable=False)
216+
217+
def save(self, update_site=False, *args, **kwargs):
218+
"""
219+
Set the site to the current site when the record is first
220+
created, or the ``update_site`` argument is explicitly set
221+
to ``True``.
222+
"""
223+
if update_site or (self.id is None and self.site_id is None):
224+
self.site_id = current_site_id()
225+
super(SiteRelated, self).save(*args, **kwargs)
226+
```
227+
Lines changed: 115 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
1+
title: django.db.models.signal Examples
2+
category: page
3+
slug: django-db-models-signal-examples
4+
sortorder: 50005
5+
toc: False
6+
sidebartitle: django.db.models.signal
7+
meta: Python code examples for database signals within a Django project.
8+
9+
10+
# django.db.models.signal Examples
11+
The
12+
[Signal](https://github.com/django/django/blob/master/django/db/models/signals.py)
13+
module allows certain senders to notify a set of receivers that some action
14+
has taken place across [Django](/django.html) apps within the same project.
15+
16+
17+
## Example 1 from django-haystack
18+
[django-haystack](https://github.com/django-haystack/django-haystack)
19+
([project website](http://haystacksearch.org/)) is a Python library
20+
for creating search indexes and queries that abstracts the underlying
21+
search engine implementation from your code.
22+
23+
[**django-haystack/haystack/signals.py**](https://github.com/django-haystack/django-haystack/blob/master/haystack/signals.py)
24+
25+
```python
26+
# encoding: utf-8
27+
28+
from __future__ import absolute_import, division, print_function, unicode_literals
29+
30+
~~from django.db import models
31+
32+
from haystack.exceptions import NotHandled
33+
34+
35+
class BaseSignalProcessor(object):
36+
"""
37+
A convenient way to attach Haystack to Django's signals & cause things to
38+
index.
39+
By default, does nothing with signals but provides underlying functionality.
40+
"""
41+
42+
def __init__(self, connections, connection_router):
43+
self.connections = connections
44+
self.connection_router = connection_router
45+
self.setup()
46+
47+
def setup(self):
48+
"""
49+
A hook for setting up anything necessary for
50+
``handle_save/handle_delete`` to be executed.
51+
Default behavior is to do nothing (``pass``).
52+
"""
53+
# Do nothing.
54+
pass
55+
56+
def teardown(self):
57+
"""
58+
A hook for tearing down anything necessary for
59+
``handle_save/handle_delete`` to no longer be executed.
60+
Default behavior is to do nothing (``pass``).
61+
"""
62+
# Do nothing.
63+
pass
64+
65+
def handle_save(self, sender, instance, **kwargs):
66+
"""
67+
Given an individual model instance, determine which backends the
68+
update should be sent to & update the object on those backends.
69+
"""
70+
using_backends = self.connection_router.for_write(instance=instance)
71+
72+
for using in using_backends:
73+
try:
74+
index = self.connections[using].get_unified_index().get_index(sender)
75+
index.update_object(instance, using=using)
76+
except NotHandled:
77+
# TODO: Maybe log it or let the exception bubble?
78+
pass
79+
80+
def handle_delete(self, sender, instance, **kwargs):
81+
"""
82+
Given an individual model instance, determine which backends the
83+
delete should be sent to & delete the object on those backends.
84+
"""
85+
using_backends = self.connection_router.for_write(instance=instance)
86+
87+
for using in using_backends:
88+
try:
89+
index = self.connections[using].get_unified_index().get_index(sender)
90+
index.remove_object(instance, using=using)
91+
except NotHandled:
92+
# TODO: Maybe log it or let the exception bubble?
93+
pass
94+
95+
96+
class RealtimeSignalProcessor(BaseSignalProcessor):
97+
"""
98+
Allows for observing when saves/deletes fire & automatically updates the
99+
search engine appropriately.
100+
"""
101+
102+
def setup(self):
103+
# Naive (listen to all model saves).
104+
~~ models.signals.post_save.connect(self.handle_save)
105+
~~ models.signals.post_delete.connect(self.handle_delete)
106+
# Efficient would be going through all backends & collecting all models
107+
# being used, then hooking up signals only for those.
108+
109+
def teardown(self):
110+
# Naive (listen to all model saves).
111+
~~ models.signals.post_save.disconnect(self.handle_save)
112+
~~ models.signals.post_delete.disconnect(self.handle_delete)
113+
# Efficient would be going through all backends & collecting all models
114+
# being used, then disconnecting signals only for those.
115+
```

0 commit comments

Comments
 (0)