Coder Social home page Coder Social logo

lpgenerator / django-db-mailer Goto Github PK

View Code? Open in Web Editor NEW
257.0 19.0 79.0 3.47 MB

Django module to easily send emails/sms/tts/push using django templates stored on database and managed through the Django Admin

Home Page: https://github.com/LPgenerator/django-db-mailer

License: GNU General Public License v2.0

Makefile 1.53% Ruby 3.02% Python 93.50% JavaScript 0.97% HTML 0.53% Dockerfile 0.46%

django-db-mailer's Issues

Django >=1.9, broken Test template and Browse vars

From release notes:

The URL of the admin change view has been changed (was at /admin//// by default and is now at /admin////change/)

And static/dbmail/admin/dbmail.js contains hardcoded urls to ./sendmail/ and ./sendmail/apps/ which now results in 404.

Required South

Hi,

In your installation tutorial it says that South is required. The problem is that Django keeps sending me Warnings about South deprecation in Django 1.9. Are you going to do something with it?

Я читал ваш пост на хабре, и у меня еще один личный вопрос:

Смогу ли я использовать вашу батарейку вместе с django-ses?

Best,
Daniyar Yeralin

Как работать с группами

Не могу найти в документацию как работать с группами, в приложении есть группы в группах есть инлайны имя и адрес, какие либо апи для работы с группами?

load_dbmail_base_templates overwrites existing base templates

Do you want to request a feature or report a bug?

Featur request.

What is the current behavior?

If I have a base template with either ID of 1, 2, or 3, my calling manage.py load_dbmail_base_templates will overwrite my base template.

What is the expected behavior?

Should use natural keys.

Which versions of DbMail, Django and which Python / OS are affected by this issue? Did this work in previous versions of DbMail?

All

Base template does not have <html> tag, included template does

Do you want to request a feature or report a bug?
Bug

What is the current behavior?
The base template doesn't have html and head tags but the child template does. This puts the html and head tags in the middle of the document.

If the current behavior is a bug, please provide the steps to reproduce and if possible a minimal demo of the problem
Create a base template and use it in an email template, then print the results (see below).

What is the expected behavior?
If automatically inserting html, head and body tags is expected, the base template should do it and if and only if there is no base template, the child template should insert html, head and body tags.

Which versions of DbMail, Django and which Python / OS are affected by this issue? Did this work in previous versions of DbMail?
django-db-mailer (2.3.13) - this is my first time trying the software.

Look for the html, head and body tags in the generated email:

--===============5259964975024812885==
MIME-Version: 1.0
Content-Type: text/html; charset="utf-8"
Content-Transfer-Encoding: 7bit

<p>This is the start of the <strong>base template.</strong></p>
<p>The content tag will follow this.</p>
<p><html>
<head></head>
<body>
<p>This is the start of the Mail Template.</p>
<p><strong>Hello Jane Doe!</strong></p>
<p>This is the end of the Mail Template.</p>
</body>
</html>
</p>
<p>The content tab was above this.</p>
<p>This is the end of the <strong>base template.</strong></p><table bgcolor="white"><tr><td><font size="-1" color="black"><img src="http://example.com/dbmail/mail_read_tracker/IjE0ODU0Nzg3MzAuMzI5NTMwLTQ2ZDIzMjY5LWQxMWYtNDkyYi04MzY2LTlhYzZiNjRiN2EzMCI:1cWusM:5G8euYXpziXQolvfQv8KEm578hI/" width="16" height="16" alt="" title="" border="0"></font></td></tr></table></center>
--===============5259964975024812885==--

Using celery without djcelery

Hello,
DB mailer works with celery only when djcelery is installed. But with latest version of celery it's possible to use celery with django without this library. How I can use db-mailer with celery without djcelery installed?

Bug when trying to send Context to the Template

I tried in different ways to pass the context to the template but it is not working for me.
When I am trying to do it in such way:

    send_db_mail(slug="account_confirmation_email",
                 recipient = self.user.email,
                 {'username': 'Alexander'},
                 use_celery = True)

I get (Python 3):

SyntaxError: positional argument follows keyword argument

If I am doing it like:

    send_db_mail({'username':'Alexander'},
                 slug="account_confirmation_email",
                 recipient = self.user.email,
                 use_celery = True)

I get:

Exception Type: TypeError
Exception Value: db_sender() got multiple values for argument 'slug'

For me it looks like a bug or if no, then please send me a simple example how to push context to the template. Thank you!

There is always a new migration in dbmail

Whenever I run the command makemigrations, a new migration is created in dbmail.

(migration 0010)

class Migration(migrations.Migration):

    dependencies = [
        ('dbmail', '0009_auto_20161019_1409'),
    ]

    operations = [
        migrations.AlterField(
            model_name='maillog',
            name='backend',
            field=models.CharField(choices=[('mail', 'dbmail.backends.mail'), ('push', 'dbmail.backends.push'), ('tts', 'dbmail.backends.tts'), ('sms', 'dbmail.backends.sms')], db_index=True, default='mail', editable=False, max_length=25, verbose_name='Backend'),
        ),
    ]

The problem is in the backend field. The value choices is BACKEND.items(). In Python <3.6, dictionaries do not maintain their order, and always changes the result with each run.

BACKEND = get_settings('DB_MAILER_BACKEND', {
    'mail': 'dbmail.backends.mail',
    'tts': 'dbmail.backends.tts',
    'sms': 'dbmail.backends.sms',
    'push': 'dbmail.backends.push',
})
...
@python_2_unicode_compatible
class MailLog(models.Model):
    ...
    backend = models.CharField(
        _('Backend'), max_length=25, editable=False, db_index=True,
        choices=BACKEND.items(), default='mail')

This is my workaround in settings.py:

DB_MAILER_BACKEND = {
    'mail': 'dbmail.backends.mail',
    'tts': 'dbmail.backends.tts',
    'sms': 'dbmail.backends.sms',
    'push': 'dbmail.backends.push',
}
DB_MAILER_BACKEND = OrderedDict(sorted(DB_MAILER_BACKEND.items(), key=lambda t: t[0]))

It seems that under python3 celery always disabled

when send_db_mail is called, it calls db_sender which checks if celery should be used the next way:

    if celery_supported() and use_celery is True:

Function celery_supported contains python2 style import (importing tasks module, but in python 3 you have to explicity specify relative import ("from . import tasks") or use fully qualified name ("import dbmail.tasks"). Function's code shown below:

def celery_supported():
    try:
        import tasks

        if not app_installed('djcelery'):
            raise ImportError
        return True
    except ImportError:
        return False

If I change imports to python3 style, my django 1.8 python 3 project works without problems with your packages.

Also if you run 2to3 on that file I can see the next report:

--- dbmail/__init__.py  (original)
+++ dbmail/__init__.py  (refactored)
@@ -21,7 +21,7 @@

 def celery_supported():
     try:
-        import tasks
+        from . import tasks

         if not app_installed('djcelery'):
             raise ImportError
@@ -43,7 +43,7 @@
     backend = kwargs.get('backend', BACKEND['mail'])

     if celery_supported() and use_celery is True:
-        import tasks
+        from . import tasks

         template = MailTemplate.get_template(slug=slug)
         max_retries = kwargs.get('max_retries', None)
RefactoringTool: Files that need to be modified:
RefactoringTool: dbmail/__init__.py

Django 1.10 support?

Hello,

I'm hoping to use django-db-mailer in my project but I am using Django 1.10 and it looks like only 1.8 is supported.

I was wondering if there are plans to add support for 1.10?

I might be able to help with that effort but since I've never used django-db-mailer I don't know if I'm the best person for that.

Thanks!

__init__() got an unexpected keyword argument 'queue'

Unable to send mail when using signals.

I am using django-db-mailer 2.3.13 with Django 1.8.2. After setting the post_save signal for a model and updating the object through the Django Admin, I get this error when I save the model and expect an email to be sent.

__init__() got an unexpected keyword argument 'queue'

in

/dbmail/backends/mail.py in _send_html_message, line 167

Here's the traceback:

Environment:


Request Method: POST
Request URL: http://127.0.0.1:8000/admin/api_v1/paymentgatewayresponse/600/

Django Version: 1.8.2
Python Version: 2.7.10
Installed Applications:
('grappelli',
 'django.contrib.admin',
 'django.contrib.sites',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'simple',
 'rest_framework',
 'rest_framework.authtoken',
 'rest_auth',
 'ajaximage',
 'vote',
 'django_extensions',
 'audit_log',
 'tinymce',
 'taggit',
 'taggit_autosuggest',
 'crispy_forms',
 'rest_framework_swagger',
 'import_export',
 'django_bitly',
 'expirables',
 'totalsum',
 'hvad',
 'user_media',
 'generic_positions',
 'dbmail',
 'quickbooks',
 'rest_framework_docs',
 'storages',
 'push_notifications',
 'oauth2_provider',
 'social.apps.django_app.default',
 'rest_framework_social_oauth2',
 'api_v1',
 'content_display',
 'review')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware',
 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
 'audit_log.middleware.UserLoggingMiddleware')


Traceback:
File "/Users/wayneb/myvirtualenv/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
  132.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/wayneb/myvirtualenv/lib/python2.7/site-packages/django/contrib/admin/options.py" in wrapper
  616.                 return self.admin_site.admin_view(view)(*args, **kwargs)
File "/Users/wayneb/myvirtualenv/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapped_view
  110.                     response = view_func(request, *args, **kwargs)
File "/Users/wayneb/myvirtualenv/lib/python2.7/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
  57.         response = view_func(request, *args, **kwargs)
File "/Users/wayneb/myvirtualenv/lib/python2.7/site-packages/django/contrib/admin/sites.py" in inner
  233.             return view(request, *args, **kwargs)
File "/Users/wayneb/myvirtualenv/lib/python2.7/site-packages/django/contrib/admin/options.py" in change_view
  1519.         return self.changeform_view(request, object_id, form_url, extra_context)
File "/Users/wayneb/myvirtualenv/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapper
  34.             return bound_func(*args, **kwargs)
File "/Users/wayneb/myvirtualenv/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapped_view
  110.                     response = view_func(request, *args, **kwargs)
File "/Users/wayneb/myvirtualenv/lib/python2.7/site-packages/django/utils/decorators.py" in bound_func
  30.                 return func.__get__(self, type(self))(*args2, **kwargs2)
File "/Users/wayneb/myvirtualenv/lib/python2.7/site-packages/django/utils/decorators.py" in inner
  145.                     return func(*args, **kwargs)
File "/Users/wayneb/myvirtualenv/lib/python2.7/site-packages/django/contrib/admin/options.py" in changeform_view
  1467.                 self.save_model(request, new_object, form, not add)
File "/Users/wayneb/myvirtualenv/lib/python2.7/site-packages/django/contrib/admin/options.py" in save_model
  1078.         obj.save()
File "/Users/wayneb/myvirtualenv/lib/python2.7/site-packages/django/db/models/base.py" in save
  710.                        force_update=force_update, update_fields=update_fields)
File "/Users/wayneb/myvirtualenv/lib/python2.7/site-packages/django/db/models/base.py" in save_base
  734.                                   update_fields=update_fields)
File "/Users/wayneb/myvirtualenv/lib/python2.7/site-packages/django/dispatch/dispatcher.py" in send
  201.             response = receiver(signal=self, sender=sender, **named)
File "/Users/wayneb/myvirtualenv/lib/python2.7/site-packages/dbmail/signals.py" in signal_receiver
  158.         SignalReceiver(sender, **kwargs).run()
File "/Users/wayneb/myvirtualenv/lib/python2.7/site-packages/dbmail/signals.py" in run
  131.             self._run()
File "/Users/wayneb/myvirtualenv/lib/python2.7/site-packages/dbmail/signals.py" in _run
  127.             self.send_mail()
File "/Users/wayneb/myvirtualenv/lib/python2.7/site-packages/dbmail/signals.py" in send_mail
  96.                         **self.get_interval()
File "/Users/wayneb/myvirtualenv/lib/python2.7/site-packages/dbmail/__init__.py" in send_db_mail

File "/Users/wayneb/myvirtualenv/lib/python2.7/site-packages/dbmail/__init__.py" in db_sender

File "/Users/wayneb/myvirtualenv/lib/python2.7/site-packages/dbmail/backends/mail.py" in send
  281.             try:
File "/Users/wayneb/myvirtualenv/lib/python2.7/site-packages/dbmail/backends/mail.py" in _try_to_send
  264.         for self._num in range(1, self._template.num_of_retries + 1):
File "/Users/wayneb/myvirtualenv/lib/python2.7/site-packages/dbmail/backends/mail.py" in _send
  249.         if self._provider is not None:
File "/Users/wayneb/myvirtualenv/lib/python2.7/site-packages/dbmail/backends/mail.py" in _send_by_native_provider
  243.     def _send_by_native_provider(self):
File "/Users/wayneb/myvirtualenv/lib/python2.7/site-packages/dbmail/backends/mail.py" in _send_html_message
  167.             self._subject, clean_html(self._message), cc=self._cc,

Exception Type: TypeError at /admin/api_v1/paymentgatewayresponse/600/
Exception Value: __init__() got an unexpected keyword argument 'queue'

I notice that I am not getting this error when I send the mail without using signals, i.e. by directly calling db_mail.

In that case, I can send successfully by calling dbmail.send_db_mail(mail_template, recipient_email, mail_context_vars).

I am not using Celery, and am sending the mail through SMTP.

GeoIP2 in Tracking

Request a feature:

Right now only GeoIP support in this package but since django 1.9 GeoIP is deprecated and now using GeoIP2. I can implement this feature and for backward compatibility I can add new settings for choosing between GeoIP and GeoIP2.

django-db-mailer init breaks Django 1.11

Version
Python==3.6.1
Django==1.11
django-db-mailer=2.3.17

It's an clean install of django-db-mailer following https://github.com/LPgenerator/django-db-mailer#installation (fixed #89 on development)

Trying any command

Eagllus > python manage.py
Traceback (most recent call last):
  File "manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/Users/ronald/.virtualenvs/cc/lib/python3.6/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line
    utility.execute()
  File "/Users/ronald/.virtualenvs/cc/lib/python3.6/site-packages/django/core/management/__init__.py", line 337, in execute
    django.setup()
  File "/Users/ronald/.virtualenvs/cc/lib/python3.6/site-packages/django/__init__.py", line 27, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/Users/ronald/.virtualenvs/cc/lib/python3.6/site-packages/django/apps/registry.py", line 116, in populate
    app_config.ready()
  File "/Users/ronald/.virtualenvs/cc/lib/python3.6/site-packages/dbmail/apps.py", line 16, in ready
    initial_signals()
  File "/Users/ronald/.virtualenvs/cc/lib/python3.6/site-packages/dbmail/__init__.py", line 146, in initial_signals
    from dbmail.signals import initial_signals as init_signals
  File "/Users/ronald/.virtualenvs/cc/lib/python3.6/site-packages/dbmail/signals.py", line 7, in <module>
    from django.contrib.sites.models import Site
  File "/Users/ronald/.virtualenvs/cc/lib/python3.6/site-packages/django/contrib/sites/models.py", line 84, in <module>
    class Site(models.Model):
  File "/Users/ronald/.virtualenvs/cc/lib/python3.6/site-packages/django/db/models/base.py", line 118, in __new__
    "INSTALLED_APPS." % (module, name)
RuntimeError: Model class django.contrib.sites.models.Site doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.

In my development environment I commented line 7 in signals.py from django.contrib.sites.models import Site

Different text and html message

Hi,
it would be very nice to have the possibility to define textual and HTML message separately. You are using the function dbmail.utils.clean_html to strip out the HTML tags but this is insufficient in case you want a rich and nice HTML with images and stuff but your textual message would look weird if those images were removed.

I think that adding another field body next to the HTML message would do the job.

Migrations not working - Thinks table exists that does not

Getting the below error when upgrading from 2.02 to Current stable. Funny thing is, I've searched the table and there is NO dbmail_mailsubscription in the DB. So I don't know why this migration think's it's there.

RHEL 6.6 Python 2.7.10

(site)[bijenkins@bmositedev siteAppsite]$ python manage.py makemigrations --merge
Merging dbmail
  Branch 0002_auto_20151013_1509
    - Alter field message on mailtemplate
  Branch 0007_auto_20150708_2016
    - Alter field email on mailfromemail
    - Alter field email on mailgroupemail
    - Alter field email on maillogemail
    - Alter field context_note on mailtemplate
    - Alter field from_email on mailtemplate
    - Alter field is_html on mailtemplate
    - Add field backend to maillog
    - Add field provider to maillog
    - Alter field backend on maillog
    - Create model MailBaseTemplate
    - Add field base to mailtemplate
    - Create model MailSubscription
    - Change Meta options on mailsubscription
    - Alter field address on mailsubscription
    - Alter field backend on mailsubscription
    - Alter field defer_at_allowed_hours on mailsubscription
    - Alter field end_hour on mailsubscription
    - Alter field is_checked on mailsubscription
    - Alter field is_enabled on mailsubscription
    - Alter field start_hour on mailsubscription

Merging will only work if the operations printed above do not conflict
with each other (working on different fields or models)
Do you want to merge these migration branches? [y/N] y

Created new merge migration /home/site/bijenkins/.pyenv/versions/site/lib/python2.7/site-packages/dbmail/migrations/0008_merge.py
(site)[bijenkins@bmositedev siteAppsite]$ 
(site)[bijenkins@bmositedev siteAppsite]$ python manage.py migrate
DEBUG (0.000) SET SQL_AUTO_IS_NULL = 0; args=None
DEBUG (0.001) SHOW TABLES; args=None
DEBUG (0.001) SELECT `django_migrations`.`app`, `django_migrations`.`name` FROM `django_migrations`; args=()
Operations to perform:
  Synchronize unmigrated apps: allauth, app, tinymce, django_rq, suit
  Apply all migrations: account, explorer, thunderdomeV2, sessions, admin, documentation, sites, auth, thunderdome, contenttypes, dbmail, servicepathtable, socialaccount
Synchronizing apps without migrations:
DEBUG (0.001) SHOW TABLES; args=None
  Creating tables...
  Installing custom SQL...
  Installing indexes...
DEBUG (0.000) SET foreign_key_checks=0; args=None
DEBUG (0.000) SET foreign_key_checks=1; args=None
DEBUG (0.000) SET SQL_AUTO_IS_NULL = 0; args=None
DEBUG (0.000) SET foreign_key_checks=0; args=None
DEBUG (0.000) SET foreign_key_checks=1; args=None
DEBUG (0.000) SET SQL_AUTO_IS_NULL = 0; args=None
DEBUG (0.000) SET foreign_key_checks=0; args=None
DEBUG (0.000) SET foreign_key_checks=1; args=None
DEBUG (0.000) SET SQL_AUTO_IS_NULL = 0; args=None
DEBUG (0.000) SET foreign_key_checks=0; args=None
DEBUG (0.000) SET foreign_key_checks=1; args=None
DEBUG (0.000) SET SQL_AUTO_IS_NULL = 0; args=None
DEBUG (0.000) SET foreign_key_checks=0; args=None
DEBUG (0.000) SET foreign_key_checks=1; args=None
Running migrations:
  Applying dbmail.0002_auto_20150321_1539...DEBUG (0.000) SET SQL_AUTO_IS_NULL = 0; args=None
DEBUG (0.001) 
            SELECT kc.`constraint_name`, kc.`column_name`,
                kc.`referenced_table_name`, kc.`referenced_column_name`
            FROM information_schema.key_column_usage AS kc
            WHERE
                kc.table_schema = 'siteV2' AND
                kc.table_name = 'dbmail_mailtemplate'
        ; args=['siteV2', u'dbmail_mailtemplate']
DEBUG (0.001) 
            SELECT c.constraint_name, c.constraint_type
            FROM information_schema.table_constraints AS c
            WHERE
                c.table_schema = 'siteV2' AND
                c.table_name = 'dbmail_mailtemplate'
        ; args=['siteV2', u'dbmail_mailtemplate']
DEBUG (0.001) SHOW INDEX FROM `dbmail_mailtemplate`; args=None
DEBUG (0.001) SHOW TABLES; args=None
DEBUG (0.001) INSERT INTO `django_migrations` (`app`, `name`, `applied`) VALUES ('dbmail', '0002_auto_20150321_1539', '2015-10-23 00:56:52'); args=['dbmail', u'0002_auto_20150321_1539', u'2015-10-23 00:56:52']
 OK
  Applying dbmail.0003_maillog_backend...DEBUG ALTER TABLE `dbmail_maillog` ADD COLUMN `backend` varchar(25) DEFAULT %s NOT NULL; (params [u'mail'])
DEBUG (0.013) ALTER TABLE `dbmail_maillog` ADD COLUMN `backend` varchar(25) DEFAULT 'mail' NOT NULL; args=[u'mail']
DEBUG ALTER TABLE `dbmail_maillog` ALTER COLUMN `backend` DROP DEFAULT; (params [])
DEBUG (0.003) ALTER TABLE `dbmail_maillog` ALTER COLUMN `backend` DROP DEFAULT; args=[]
DEBUG CREATE INDEX `dbmail_maillog_b43fdd98` ON `dbmail_maillog` (`backend`); (params [])
DEBUG (0.011) CREATE INDEX `dbmail_maillog_b43fdd98` ON `dbmail_maillog` (`backend`); args=[]
DEBUG (0.001) SHOW TABLES; args=None
DEBUG (0.000) INSERT INTO `django_migrations` (`app`, `name`, `applied`) VALUES ('dbmail', '0003_maillog_backend', '2015-10-23 00:56:52'); args=['dbmail', u'0003_maillog_backend', u'2015-10-23 00:56:52']
 OK
  Applying dbmail.0004_auto_20150321_2214...DEBUG ALTER TABLE `dbmail_maillog` ADD COLUMN `provider` varchar(250) NULL; (params [])
DEBUG (0.014) ALTER TABLE `dbmail_maillog` ADD COLUMN `provider` varchar(250) NULL; args=[]
DEBUG CREATE INDEX `dbmail_maillog_9e9f3d70` ON `dbmail_maillog` (`provider`); (params [])
DEBUG (0.013) CREATE INDEX `dbmail_maillog_9e9f3d70` ON `dbmail_maillog` (`provider`); args=[]
DEBUG (0.001) SHOW TABLES; args=None
DEBUG (0.000) INSERT INTO `django_migrations` (`app`, `name`, `applied`) VALUES ('dbmail', '0004_auto_20150321_2214', '2015-10-23 00:56:52'); args=['dbmail', u'0004_auto_20150321_2214', u'2015-10-23 00:56:52']
 OK
  Applying dbmail.0005_auto_20150506_2201...DEBUG CREATE TABLE `dbmail_mailbasetemplate` (`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `name` varchar(100) NOT NULL UNIQUE, `message` longtext NOT NULL, `created` datetime NOT NULL, `updated` datetime NOT NULL); (params [])
DEBUG (0.005) CREATE TABLE `dbmail_mailbasetemplate` (`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `name` varchar(100) NOT NULL UNIQUE, `message` longtext NOT NULL, `created` datetime NOT NULL, `updated` datetime NOT NULL); args=[]
DEBUG ALTER TABLE `dbmail_mailtemplate` ADD COLUMN `base_id` integer NULL; (params [])
DEBUG (0.004) ALTER TABLE `dbmail_mailtemplate` ADD COLUMN `base_id` integer NULL; args=[]
DEBUG ALTER TABLE `dbmail_mailtemplate` ALTER COLUMN `base_id` DROP DEFAULT; (params [])
DEBUG (0.003) ALTER TABLE `dbmail_mailtemplate` ALTER COLUMN `base_id` DROP DEFAULT; args=[]
DEBUG CREATE INDEX `dbmail_mailtemplate_078dce83` ON `dbmail_mailtemplate` (`base_id`); (params [])
DEBUG (0.004) CREATE INDEX `dbmail_mailtemplate_078dce83` ON `dbmail_mailtemplate` (`base_id`); args=[]
DEBUG ALTER TABLE `dbmail_mailtemplate` ADD CONSTRAINT `dbmail_ma_base_id_6971ccd5fcd1b12f_fk_dbmail_mailbasetemplate_id` FOREIGN KEY (`base_id`) REFERENCES `dbmail_mailbasetemplate` (`id`); (params [])
DEBUG (0.004) ALTER TABLE `dbmail_mailtemplate` ADD CONSTRAINT `dbmail_ma_base_id_6971ccd5fcd1b12f_fk_dbmail_mailbasetemplate_id` FOREIGN KEY (`base_id`) REFERENCES `dbmail_mailbasetemplate` (`id`); args=[]
DEBUG (0.001) SHOW TABLES; args=None
DEBUG (0.000) INSERT INTO `django_migrations` (`app`, `name`, `applied`) VALUES ('dbmail', '0005_auto_20150506_2201', '2015-10-23 00:56:53'); args=['dbmail', u'0005_auto_20150506_2201', u'2015-10-23 00:56:53']
 OK
  Applying dbmail.0006_auto_20150708_0714...DEBUG CREATE TABLE `dbmail_mailsubscription` (`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `backend` varchar(50) NOT NULL, `start_hour` varchar(5) NOT NULL, `end_hour` varchar(5) NOT NULL, `is_enabled` bool NOT NULL, `is_checked` bool NOT NULL, `defer_at_allowed_hours` bool NOT NULL, `address` varchar(60) NOT NULL, `user_id` integer NULL); (params [])
DEBUG (0.005) CREATE TABLE `dbmail_mailsubscription` (`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `backend` varchar(50) NOT NULL, `start_hour` varchar(5) NOT NULL, `end_hour` varchar(5) NOT NULL, `is_enabled` bool NOT NULL, `is_checked` bool NOT NULL, `defer_at_allowed_hours` bool NOT NULL, `address` varchar(60) NOT NULL, `user_id` integer NULL); args=[]
DEBUG ALTER TABLE `dbmail_mailsubscription` ADD CONSTRAINT `dbmail_mailsubscription_user_id_440cd6feeb7e77b0_fk_auth_user_id` FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`); (params [])
DEBUG (0.018) ALTER TABLE `dbmail_mailsubscription` ADD CONSTRAINT `dbmail_mailsubscription_user_id_440cd6feeb7e77b0_fk_auth_user_id` FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`); args=[]
Traceback (most recent call last):
  File "manage.py", line 17, in <module>
    execute_from_command_line(sys.argv)
  File "/home/site/bijenkins/.pyenv/versions/site/lib/python2.7/site-packages/django/core/management/__init__.py", line 385, in execute_from_command_line
    utility.execute()
  File "/home/site/bijenkins/.pyenv/versions/site/lib/python2.7/site-packages/django/core/management/__init__.py", line 377, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/home/site/bijenkins/.pyenv/versions/site/lib/python2.7/site-packages/django/core/management/base.py", line 288, in run_from_argv
    self.execute(*args, **options.__dict__)
  File "/home/site/bijenkins/.pyenv/versions/site/lib/python2.7/site-packages/django/core/management/base.py", line 338, in execute
    output = self.handle(*args, **options)
  File "/home/site/bijenkins/.pyenv/versions/site/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 161, in handle
    executor.migrate(targets, plan, fake=options.get("fake", False))
  File "/home/site/bijenkins/.pyenv/versions/site/lib/python2.7/site-packages/django/db/migrations/executor.py", line 68, in migrate
    self.apply_migration(migration, fake=fake)
  File "/home/site/bijenkins/.pyenv/versions/site/lib/python2.7/site-packages/django/db/migrations/executor.py", line 102, in apply_migration
    migration.apply(project_state, schema_editor)
  File "/home/site/bijenkins/.pyenv/versions/site/lib/python2.7/site-packages/django/db/backends/schema.py", line 82, in __exit__
    self.execute(sql)
  File "/home/site/bijenkins/.pyenv/versions/site/lib/python2.7/site-packages/django/db/backends/schema.py", line 102, in execute
    cursor.execute(sql, params)
  File "/home/site/bijenkins/.pyenv/versions/site/lib/python2.7/site-packages/django/db/backends/utils.py", line 81, in execute
    return super(CursorDebugWrapper, self).execute(sql, params)
  File "/home/site/bijenkins/.pyenv/versions/site/lib/python2.7/site-packages/django/db/backends/utils.py", line 65, in execute
    return self.cursor.execute(sql, params)
  File "/home/site/bijenkins/.pyenv/versions/site/lib/python2.7/site-packages/django/db/utils.py", line 94, in __exit__
    six.reraise(dj_exc_type, dj_exc_value, traceback)
  File "/home/site/bijenkins/.pyenv/versions/site/lib/python2.7/site-packages/django/db/backends/utils.py", line 65, in execute
    return self.cursor.execute(sql, params)
  File "/home/site/bijenkins/.pyenv/versions/site/lib/python2.7/site-packages/django/db/backends/mysql/base.py", line 129, in execute
    return self.cursor.execute(query, args)
  File "/home/site/bijenkins/.pyenv/versions/site/lib/python2.7/site-packages/MySQLdb/cursors.py", line 205, in execute
    self.errorhandler(self, exc, value)
  File "/home/site/bijenkins/.pyenv/versions/site/lib/python2.7/site-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler
    raise errorclass, errorvalue
django.db.utils.OperationalError: (1005, "Can't create table 'siteV2.#sql-2187_223e' (errno: 150)")






(ENV)[bijenkins@bmositedev siteAppsite]$ 
(ENV)[bijenkins@server site]$ python manage.py syncdb
DEBUG (0.001) SET SQL_AUTO_IS_NULL = 0; args=None
DEBUG (0.001) SHOW TABLES; args=None
DEBUG (0.001) SELECT `django_migrations`.`app`, `django_migrations`.`name` FROM `django_migrations`; args=()
Operations to perform:
  Synchronize unmigrated apps: allauth, app, tinymce, django_rq, suit
  Apply all migrations: account, explorer, thunderdomeV2, sessions, admin, documentation, sites, auth, thunderdome, contenttypes, dbmail, servicepathtable, socialaccount
Synchronizing apps without migrations:
DEBUG (0.001) SHOW TABLES; args=None
  Creating tables...
  Installing custom SQL...
  Installing indexes...
DEBUG (0.000) SET foreign_key_checks=0; args=None
DEBUG (0.000) SET foreign_key_checks=1; args=None
DEBUG (0.000) SET SQL_AUTO_IS_NULL = 0; args=None
DEBUG (0.000) SET foreign_key_checks=0; args=None
DEBUG (0.000) SET foreign_key_checks=1; args=None
DEBUG (0.000) SET SQL_AUTO_IS_NULL = 0; args=None
DEBUG (0.000) SET foreign_key_checks=0; args=None
DEBUG (0.000) SET foreign_key_checks=1; args=None
DEBUG (0.000) SET SQL_AUTO_IS_NULL = 0; args=None
DEBUG (0.000) SET foreign_key_checks=0; args=None
DEBUG (0.000) SET foreign_key_checks=1; args=None
DEBUG (0.000) SET SQL_AUTO_IS_NULL = 0; args=None
DEBUG (0.000) SET foreign_key_checks=0; args=None
DEBUG (0.000) SET foreign_key_checks=1; args=None
Running migrations:
  Applying dbmail.0006_auto_20150708_0714...DEBUG CREATE TABLE `dbmail_mailsubscription` (`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `backend` varchar(50) NOT NULL, `start_hour` varchar(5) NOT NULL, `end_hour` varchar(5) NOT NULL, `is_enabled` bool NOT NULL, `is_checked` bool NOT NULL, `defer_at_allowed_hours` bool NOT NULL, `address` varchar(60) NOT NULL, `user_id` integer NULL); (params [])
DEBUG (0.000) SET SQL_AUTO_IS_NULL = 0; args=None
DEBUG (0.001) CREATE TABLE `dbmail_mailsubscription` (`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `backend` varchar(50) NOT NULL, `start_hour` varchar(5) NOT NULL, `end_hour` varchar(5) NOT NULL, `is_enabled` bool NOT NULL, `is_checked` bool NOT NULL, `defer_at_allowed_hours` bool NOT NULL, `address` varchar(60) NOT NULL, `user_id` integer NULL); args=[]
Traceback (most recent call last):
  File "manage.py", line 17, in <module>
    execute_from_command_line(sys.argv)
  File "/home/DOMAIN/bijenkins/.pyenv/versions/site/lib/python2.7/site-packages/django/core/management/__init__.py", line 385, in execute_from_command_line
    utility.execute()
  File "/home/DOMAIN/bijenkins/.pyenv/versions/site/lib/python2.7/site-packages/django/core/management/__init__.py", line 377, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/home/DOMAIN/bijenkins/.pyenv/versions/site/lib/python2.7/site-packages/django/core/management/base.py", line 288, in run_from_argv
    self.execute(*args, **options.__dict__)
  File "/home/DOMAIN/bijenkins/.pyenv/versions/site/lib/python2.7/site-packages/django/core/management/base.py", line 338, in execute
    output = self.handle(*args, **options)
  File "/home/DOMAIN/bijenkins/.pyenv/versions/site/lib/python2.7/site-packages/django/core/management/base.py", line 533, in handle
    return self.handle_noargs(**options)
  File "/home/DOMAIN/bijenkins/.pyenv/versions/site/lib/python2.7/site-packages/django/core/management/commands/syncdb.py", line 27, in handle_noargs
    call_command("migrate", **options)
  File "/home/DOMAIN/bijenkins/.pyenv/versions/site/lib/python2.7/site-packages/django/core/management/__init__.py", line 115, in call_command
    return klass.execute(*args, **defaults)
  File "/home/DOMAIN/bijenkins/.pyenv/versions/site/lib/python2.7/site-packages/django/core/management/base.py", line 338, in execute
    output = self.handle(*args, **options)
  File "/home/DOMAIN/bijenkins/.pyenv/versions/site/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 161, in handle
    executor.migrate(targets, plan, fake=options.get("fake", False))
  File "/home/DOMAIN/bijenkins/.pyenv/versions/site/lib/python2.7/site-packages/django/db/migrations/executor.py", line 68, in migrate
    self.apply_migration(migration, fake=fake)
  File "/home/DOMAIN/bijenkins/.pyenv/versions/site/lib/python2.7/site-packages/django/db/migrations/executor.py", line 102, in apply_migration
    migration.apply(project_state, schema_editor)
  File "/home/DOMAIN/bijenkins/.pyenv/versions/site/lib/python2.7/site-packages/django/db/migrations/migration.py", line 108, in apply
    operation.database_forwards(self.app_label, schema_editor, project_state, new_state)
  File "/home/DOMAIN/bijenkins/.pyenv/versions/site/lib/python2.7/site-packages/django/db/migrations/operations/models.py", line 36, in database_forwards
    schema_editor.create_model(model)
  File "/home/DOMAIN/bijenkins/.pyenv/versions/site/lib/python2.7/site-packages/django/db/backends/schema.py", line 261, in create_model
    self.execute(sql, params)
  File "/home/DOMAIN/bijenkins/.pyenv/versions/site/lib/python2.7/site-packages/django/db/backends/schema.py", line 102, in execute
    cursor.execute(sql, params)
  File "/home/DOMAIN/bijenkins/.pyenv/versions/site/lib/python2.7/site-packages/django/db/backends/utils.py", line 81, in execute
    return super(CursorDebugWrapper, self).execute(sql, params)
  File "/home/DOMAIN/bijenkins/.pyenv/versions/site/lib/python2.7/site-packages/django/db/backends/utils.py", line 65, in execute
    return self.cursor.execute(sql, params)
  File "/home/DOMAIN/bijenkins/.pyenv/versions/site/lib/python2.7/site-packages/django/db/utils.py", line 94, in __exit__
    six.reraise(dj_exc_type, dj_exc_value, traceback)
  File "/home/DOMAIN/bijenkins/.pyenv/versions/site/lib/python2.7/site-packages/django/db/backends/utils.py", line 65, in execute
    return self.cursor.execute(sql, params)
  File "/home/DOMAIN/bijenkins/.pyenv/versions/site/lib/python2.7/site-packages/django/db/backends/mysql/base.py", line 129, in execute
    return self.cursor.execute(query, args)
  File "/home/DOMAIN/bijenkins/.pyenv/versions/site/lib/python2.7/site-packages/MySQLdb/cursors.py", line 205, in execute
    self.errorhandler(self, exc, value)
  File "/home/DOMAIN/bijenkins/.pyenv/versions/site/lib/python2.7/site-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler
    raise errorclass, errorvalue
django.db.utils.OperationalError: (1050, "Table 'dbmail_mailsubscription' already exists")


mysql> use DBtest
Database changed
mysql> show tables;
+----------------------------------------+
| Tables_in_DBtest                     |
+----------------------------------------+
| Inventory_Warehouse                    |
| Inventory_Warehouse_copy               |
| Replace_List                           |
| ThunderDome                            |
| ThunderDome_End                        |
| ThunderDome_log                        |
| Waiting_Videos                         |
| account_emailaddress                   |
| account_emailconfirmation              |
| auditor_misc_lines                     |
| auditor_models                         |
| auth_group                             |
| auth_group_permissions                 |
| auth_permission                        |
| auth_user                              |
| auth_user_groups                       |
| auth_user_user_permissions             |
| dbmail_apikey                          |
| dbmail_mailbasetemplate                |
| dbmail_mailbcc                         |
| dbmail_mailcategory                    |
| dbmail_mailfile                        |
| dbmail_mailfromemail                   |
| dbmail_mailfromemailcredential         |
| dbmail_mailgroup                       |
| dbmail_mailgroupemail                  |
| dbmail_maillog                         |
| dbmail_maillogemail                    |
| dbmail_maillogexception                |
| dbmail_maillogtrack                    |
| dbmail_mailsubscription                |
| dbmail_mailtemplate                    |
| dbmail_mailtemplate_bcc_email          |
| dbmail_signal                          |
| dbmail_signaldeferreddispatch          |
| dbmail_signallog                       |
| django_admin_log     

MRO problem using django-modeltranslation

In dbmail/admin.py line 55, the definition of class TranslationModelAdmin causes a method resolution order error.

I am using python 2.7.3, django 1.8.7 and modeltranslation 0.10.2.

TypeError: Error when calling the metaclass bases
    Cannot create a consistent method resolution
order (MRO) for bases ModelAdmin, TabbedDjangoJqueryTranslationAdmin

Delete selected Mail logs 403 Forbidden

при попытке удалить несколько записей из лога получаю 403 Forbidden

при этом если зайти в конкретный лог то по отдельности все удаляется

Is it any requirement of celery to install along with dbmail ?

I have install dbmail , when i try to run the code ,I get this error
'module' object is not callable

and which shows me the error near line
if celery_supported() and use_celery is True: line number 45

and
import dbmail.tasks line number 24

Can anyone tell me what is wrong ?

Шаблонизатора для темы письма

Было бы здорово добавить поддержку шаблонов в теме письма.
Сейчас приходится делать так:

original_mail_template_subject = mail_template.subject
mail_template.subject = _('Mail subject template «%s» [%s, %s]' %
                          (param1, param2, param3))
mail_template.save()
....
mail_template.subject = original_mail_template_subject
mail_template.save()

Проблемы с прикреплением файлов

Приветствую!
Прикрепляю файл к шаблону в коде:

attachment = MailFile.objects.create(
    template=mail_template,
    name='Request for bill')
attachment.filename.save(
    'Request.xlsx',
    ContentFile(output_file_stream.getvalue()))

Есть 2 проблемы:

  1. Ошибка при сохранении вложения
    DataError: value too long for type character varying(100)
    Это ограничение стандартного файлового поля в Django, которая представляет файл в базе в виде varchar(100). Помогло увеличение длины поля в классе MailFile:
filename = models.FileField(_('File'), upload_to=_upload_mail_file, max_length=255)

Я конечно могу просто переопределить этот класс у себя, но мне кажется, проблему можно исправить в Вашем алгоритме генерации имен вложений.
2. Собственно имена вложений.
Вы их программно переопределяете, в результате в письме имя файла а ля d49caadf-c367-4e06-b424-88bd7f0a0aae.xlsx, хотя мне бы хотелось видеть там свое имя, указанное при создании файла.

Ошибка при создание шаблона

Если ранее был создан шаблон с slug=None то класс MailTemplateAdmin ломается до след. перезапуска. Ошибка кроется скорей всего тут, позже покурю и пришлю пул реквест:

    def get_form(self, request, obj=None, **kwargs):
        if obj is not None:
            self.prepopulated_fields = {}
            if defaults.READ_ONLY_ENABLED:
                self.readonly_fields = ['slug', 'context_note']
        else:
            self.prepopulated_fields = {'slug': ('name',)}

        return super(MailTemplateAdmin, self).get_form(
            request, obj=None, **kwargs)

Вообще сама идея что-то менять в рантайме у ModelAdmin крайне опасная затея, так как в райнтайме используется всегда один экземпляр данного класса. Класс инстанциируется один раз и больше новых экземпляров не будет.

How does Mail Base Template and Message(Body) works?

Is there any description or documentation of how to use Mail Base Template and when to use Message or Body instead?
I tried to set a base template but then my message is ignored completely. Should only one of these be used? In what scenario ?What is the purpose of giving both of these fields separately?

Please let me know or link to any documentation
Thanks

mail_read_tracker fails when celery is not installed

Do you want to request a feature or report a bug?
bug

What is the current behavior?

mail_read_tracker view raises exception if celery is not being used and is not installed

If the current behavior is a bug, please provide the steps to reproduce and if possible a minimal demo of the problem

  • Add dbmail.urls to project urls
  • Attempt to go to /dbmail/mail_read_tracker/ENCRYPTION URL
  • notice exception

Full traceback

ImportError for celery

What is the expected behavior?

Should be able to work without celery installed

Which versions of DbMail, Django and which Python / OS are affected by this issue? Did this work in previous versions of DbMail?

Not relevant

Double underscores

Хотелось бы услышать мнение автора на тему обильного использования двойных подчеркиваний особенно интересуют методы классов которые фактически не участвуют в наследование. Чем мотивируется такое желание сделать все методы приватными членами класса?

dbmail/signals.py:149

when set signals and used celery import "import tasks" -> "from dbmail import tasks" ?

Django 2.0 compatibility

Do you want to request a feature or report a bug?
Bug

If the current behavior is a bug, please provide the steps to reproduce and if possible a minimal demo of the problem
After installing with pip and adding dbmail to INSTALLED_APPS, i tried to migrate and got the following error:

Full traceback
Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/Users/imad/.virtualenvs/pr2/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/Users/imad/.virtualenvs/pr2/lib/python3.6/site-packages/django/core/management/__init__.py", line 347, in execute django.setup() File "/Users/imad/.virtualenvs/pr2/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/imad/.virtualenvs/pr2/lib/python3.6/site-packages/django/apps/registry.py", line 112, in populate app_config.import_models() File "/Users/imad/.virtualenvs/pr2/lib/python3.6/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/Users/imad/.virtualenvs/pr2/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 978, in _gcd_import File "<frozen importlib._bootstrap>", line 961, in _find_and_load File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 655, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed File "/Users/imad/.virtualenvs/pr2/lib/python3.6/site-packages/dbmail/models.py", line 106, in <module> class MailFromEmail(models.Model): File "/Users/imad/.virtualenvs/pr2/lib/python3.6/site-packages/dbmail/models.py", line 113, in MailFromEmail blank=True, null=True, default=None) TypeError: __init__() missing 1 required positional argument: 'on_delete'
What is the expected behavior?

Python: 3.6

Thank you for the effort

Текст шаблона

Теоретически, так как есть несколько бекендов (смс, ттс, мыло...) должен быть отдельный текст для каждого из бекендов
т.е. шаблон один, а полей для текста несколько, может инлайнами ?

TypeError when sending push message using APNS

I am attempting to send push notifications using APNS and I am getting an error. I am using Ubuntu 14.04, Python 3.5.2, Django 1.10.3, and DbMail 2.3.12.

Traceback (most recent call last):
  File "./manage.py", line 22, in <module>
    execute_from_command_line(sys.argv)
  File "/home/vagrant/virtualenvs/backend/lib/python3.5/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line
    utility.execute()
  File "/home/vagrant/virtualenvs/backend/lib/python3.5/site-packages/django/core/management/__init__.py", line 359, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/home/vagrant/virtualenvs/backend/lib/python3.5/site-packages/django/core/management/base.py", line 294, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/home/vagrant/virtualenvs/backend/lib/python3.5/site-packages/django/core/management/base.py", line 345, in execute
    output = self.handle(*args, **options)
  File "/vagrant/apps/communication/management/commands/test_push_notif.py", line 26, in handle
    badge=6)
  File "/home/vagrant/virtualenvs/backend/lib/python3.5/site-packages/dbmail/__init__.py", line 102, in send_db_push
    return db_sender(*args, **kwargs)
  File "/home/vagrant/virtualenvs/backend/lib/python3.5/site-packages/dbmail/__init__.py", line 71, in db_sender
    return module.Sender(*args, **kwargs).send(is_celery=False)
  File "/home/vagrant/virtualenvs/backend/lib/python3.5/site-packages/dbmail/backends/mail.py", line 283, in send
    self._try_to_send()
  File "/home/vagrant/virtualenvs/backend/lib/python3.5/site-packages/dbmail/backends/mail.py", line 266, in _try_to_send
    self._send()
  File "/home/vagrant/virtualenvs/backend/lib/python3.5/site-packages/dbmail/backends/push.py", line 34, in _send
    module.send(address, **options)
  File "/home/vagrant/virtualenvs/backend/lib/python3.5/site-packages/dbmail/providers/apple/apns.py", line 60, in send
    payload_length_bin + payload)
TypeError: can't concat bytes to str

Альтернативная DB

Есть ли возможность указать Django-db-mailer какую DB использовать ?
Допустим, если в Django несколько DATABASES, то было бы замечательно иметь возможность выбрать какую из DB использовать.

Собственно проблема лично у нас в следующем: одни и те-же шаблоны используются на разных серверах в разных инстансах одного и того же проекта. Соответственно у них разные базы данных. Основная проблема с Db-mailerом это синхронизация шаблонов писем. Пока было 3-4 сервера делали это вручную, сейчас серверов 10+ и делать это в ручном/полу ручном режиме становится не удобно. Если бы можно было бы указать какой-то отдельный DB backend для mailerа то мы бы вынесли всю базу для этой подсистемы в один сервере и остальные сервера "питались" бы данными оттуда.

https in trackable url

Right now if you're using https on server you still get url with http, there is no checking about protocol.
Problem is here

max_length can exceed 255 for InnoDB/utf8 databases

I follow the install instructions
https://github.com/LPgenerator/django-db-mailer/#installation

at step 3 python manage.py migrate I get the following error.

Full traceback

Traceback (most recent call last):
  File "manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/Users/ronald/.virtualenvs/cc/lib/python3.6/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line
    utility.execute()
  File "/Users/ronald/.virtualenvs/cc/lib/python3.6/site-packages/django/core/management/__init__.py", line 355, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/Users/ronald/.virtualenvs/cc/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/Users/ronald/.virtualenvs/cc/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute
    output = self.handle(*args, **options)
  File "/Users/ronald/.virtualenvs/cc/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 204, in handle
    fake_initial=fake_initial,
  File "/Users/ronald/.virtualenvs/cc/lib/python3.6/site-packages/django/db/migrations/executor.py", line 115, in migrate
    state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
  File "/Users/ronald/.virtualenvs/cc/lib/python3.6/site-packages/django/db/migrations/executor.py", line 145, in _migrate_all_forwards
    state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
  File "/Users/ronald/.virtualenvs/cc/lib/python3.6/site-packages/django/db/migrations/executor.py", line 244, in apply_migration
    state = migration.apply(state, schema_editor)
  File "/Users/ronald/.virtualenvs/cc/lib/python3.6/site-packages/django/db/migrations/migration.py", line 129, in apply
    operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
  File "/Users/ronald/.virtualenvs/cc/lib/python3.6/site-packages/django/db/migrations/operations/fields.py", line 215, in database_forwards
    schema_editor.alter_field(from_model, from_field, to_field)
  File "/Users/ronald/.virtualenvs/cc/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 513, in alter_field
    old_db_params, new_db_params, strict)
  File "/Users/ronald/.virtualenvs/cc/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 674, in _alter_field
    params,
  File "/Users/ronald/.virtualenvs/cc/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 119, in execute
    cursor.execute(sql, params)
  File "/Users/ronald/.virtualenvs/cc/lib/python3.6/site-packages/django/db/backends/utils.py", line 80, in execute
    return super(CursorDebugWrapper, self).execute(sql, params)
  File "/Users/ronald/.virtualenvs/cc/lib/python3.6/site-packages/django/db/backends/utils.py", line 65, in execute
    return self.cursor.execute(sql, params)
  File "/Users/ronald/.virtualenvs/cc/lib/python3.6/site-packages/django/db/utils.py", line 94, in __exit__
    six.reraise(dj_exc_type, dj_exc_value, traceback)
  File "/Users/ronald/.virtualenvs/cc/lib/python3.6/site-packages/django/utils/six.py", line 685, in reraise
    raise value.with_traceback(tb)
  File "/Users/ronald/.virtualenvs/cc/lib/python3.6/site-packages/django/db/backends/utils.py", line 65, in execute
    return self.cursor.execute(sql, params)
  File "/Users/ronald/.virtualenvs/cc/lib/python3.6/site-packages/django/db/backends/mysql/base.py", line 101, in execute
    return self.cursor.execute(query, args)
  File "/Users/ronald/.virtualenvs/cc/lib/python3.6/site-packages/MySQLdb/cursors.py", line 250, in execute
    self.errorhandler(self, exc, value)
  File "/Users/ronald/.virtualenvs/cc/lib/python3.6/site-packages/MySQLdb/connections.py", line 50, in defaulterrorhandler
    raise errorvalue
  File "/Users/ronald/.virtualenvs/cc/lib/python3.6/site-packages/MySQLdb/cursors.py", line 247, in execute
    res = self._query(query)
  File "/Users/ronald/.virtualenvs/cc/lib/python3.6/site-packages/MySQLdb/cursors.py", line 411, in _query
    rowcount = self._do_query(q)
  File "/Users/ronald/.virtualenvs/cc/lib/python3.6/site-packages/MySQLdb/cursors.py", line 374, in _do_query
    db.query(q)
  File "/Users/ronald/.virtualenvs/cc/lib/python3.6/site-packages/MySQLdb/connections.py", line 292, in query
    _mysql.connection.query(self, query)
django.db.utils.OperationalError: (1071, 'Specified key was too long; max key length is 767 bytes')

This is happening because my database is setup as InnoDB / utf8.
When I look at the migration I notice this ... max_length=350, ...
InnoDB / utf8 can only handle max_length of 255.

Changing the max_length to 255 will resolve this problem.

I can create a pull request for this change but this will require the update of the migration file.
(That only effects new installations)

Error: <SimpleLazyObject: <User: xx>> is not JSON serializable

When I call send_db_mail with keyword argument user=request.user and no use_celery, there is error:

TypeError: <SimpleLazyObject: <User: xx>> is not JSON serializable

I think it is because send_db_mail by default handover the task to Celery, and hence, the argument has to be serialized. But while other argument are string and dict, which are serializable, the user is not.

My environment: Django 1.11, django-db-mailer 2.3.17, Python 3.5, Ubuntu 17.04.

Do you think we should let pass user_id instead?

Positional argument after keyword argument ?

send_db_mail( slug='welcome', recipient='[email protected]', { 'username': request.user.username, 'full_name': request.user.get_full_name(), 'signup_date': request.user.date_joined }, MyModel.objects.get(pk=1) )

The above code should be replaced by below one:

send_db_mail({ 'username': request.user.username, 'full_name': request.user.get_full_name(), 'signup_date': request.user.date_joined }, slug='welcome', recipient='[email protected]',, MyModel.objects.get(pk=1) )

But gives the error like
db_sender() got multiple values for keyword argument 'slug'

I am using 'os x el capitan

Environment:

Request Method: POST
Request URL: http://127.0.0.1:8000/api_v1/gateways/p/codrequest/

Django Version: 1.8.2
Python Version: 2.7.10

Traceback:
File "/Users/sagar/pvirtualenv/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response

  1.                 response = wrapped_callback(request, _callback_args, *_callback_kwargs)
    
    File "/Users/sagar/pvirtualenv/lib/python2.7/site-packages/django/views/decorators/csrf.py" in wrapped_view
  2.     return view_func(_args, *_kwargs)
    
    File "/Users/sagar/pvirtualenv/lib/python2.7/site-packages/rest_framework/viewsets.py" in view
  3.         return self.dispatch(request, _args, *_kwargs)
    
    File "/Users/sagar/pvirtualenv/lib/python2.7/site-packages/rest_framework/views.py" in dispatch
  4.         response = self.handle_exception(exc)
    
    File "/Users/sagar/pvirtualenv/lib/python2.7/site-packages/rest_framework/views.py" in dispatch
  5.         response = handler(request, _args, *_kwargs)
    
    File "/Users/sagar/pvirtualenv/lib/python2.7/site-packages/rest_framework/mixins.py" in create
  6.     self.perform_create(serializer)
    
    File "/Users/sagar/pvirtualenv/lib/python2.7/site-packages/rest_framework/mixins.py" in perform_create
  7.     serializer.save()
    
    File "/Users/sagar/pvirtualenv/lib/python2.7/site-packages/rest_framework/serializers.py" in save
  8.         self.instance = self.create(validated_data)
    
    File "/Users/sagar/p/p_api/api_v1/serializers.py" in create
  9.         slug='welcome2', recipient='[email protected], [email protected]')
    
    File "/Users/sagar/pvirtualenv/lib/python2.7/site-packages/dbmail/init.py" in send_db_mail
  10. return db_sender(_args, *_kwargs)
    

Exception Type: TypeError at /api_v1/gateways/p/codrequest/
Exception Value: db_sender() got multiple values for keyword argument 'slug'

I have given the stack trace above.
Please let me know the solution

SyntaxError: non-keyword arg after keyword arg

send_db_mail(
... # slug - which defined on db template
... slug='welcome',
...
... # recipient can be list, or str separated with comma or simple string
... # '[email protected]' or '[email protected], [email protected]' or
... # ['[email protected]', '[email protected]'] or string Mail group slug
... recipient='[email protected]',
...
... # All *args params will be accessible on template context
... {
... 'username': request.user.username,
... 'full_name': request.user.get_full_name(),
... 'signup_date': request.user.date_joined
... },
...
...
... )
File "", line 11
SyntaxError: non-keyword arg after keyword arg

This happens no matter which way, I try to add *args to be pulled into the template context. I tryed data={"test":"This is a test"} with the same result.

Line 11:
... # All args params will be accessible on template context
... { < *
**************************************
... 'username': request.user.username,

Python 2.7.9 Django 1.7.4

send_db_mail arguments for template + template tags

Hi guys,

What is the working example of providing arguments to send_db_mail()?

Following example is not working:

send_db_mail(
    # slug which defined on db template
    slug='welcome',

    # recipient can be list, or str separated with comma or simple string
    # '[email protected]' or '[email protected], [email protected]' or
    # ['[email protected]', '[email protected]'] or string Mail group slug
    recipient='[email protected]',

    **# All *args params will be accessible on template context
    {
        'username': request.user.username,
        'full_name': request.user.get_full_name(),
        'signup_date': request.user.date_joined,
        'prefix': "DbMail",
    },**
)

because:
SyntaxError: positional argument follows keyword argument

Can you please write me how to pass arguments?

Also I have another question. Is it possible to use tags inside of template? I want to render url in the template with something similar to {% url ... %} Thanks!

Can't enable tracking option

I installed redis, django-redis, django-celery, httpagentparser, django-ipware and set DB_MAILER_TRACK_ENABLE and DB_MAILER_ENABLE_LOGGING to true, but when I sent email it doesn't create any record in track table. What did I do wrong? Maybe I missed some settings? I used AWS SES as email backend.

ERROR/MainProcess] Task dbmail.send_db_mail[] raised unexpected: TimeLimitExceeded(30,)

В проекте все настроил, вызываю send_db_mail('test','test',{'test': 'test test test bla bla bla',},)
Celery запускал : python manage.py celeryd --loglevel=info -Q default
Ошибка 2015-04-29 00:59:27,489: ERROR/MainProcess] Task dbmail.send_db_mail[b740194b-d707-44d5-9bc2-8ebc479b6d28] raised unexpected: TimeLimitExceeded(30,)
Traceback (most recent call last):
File "/home/dev/.virtualenvs/portal/lib/python2.7/site-packages/billiard/pool.py", line 641, in on_hard_timeout
raise TimeLimitExceeded(job._timeout)
TimeLimitExceeded: TimeLimitExceeded(30,)
[2015-04-29 00:59:27,490: ERROR/MainProcess] Hard time limit (30s) exceeded for dbmail.send_db_mail[b740194b-d707-44d5-9bc2-8ebc479b6d28]

Перезапустил python manage.py celeryd --time-limit=7200 -E --loglevel=DEBUG
В дебаге на каждую задачу идет запросы ко всем таблицам База очень большая и в итоге сам celery зависает на каждой таск

Базовый шаблон в БД

@AlexDev1, @vosi базовые шаблоны что обсуждали в #12 реализованы в ветке basic-template. просьба посмотреть, оценить, проверить работоспособность всего этого дела. после волью в development. необходимо будет проверить как это дело сочетается с локалью.

Python 3 & Django 1.8

Приветствую!
Планируется ли совместимость с сабжем? И если да, то когда?

Template's subject line length

RFC doesn't really restrict the subject length and there is an issue while trying to use long Django template for subject with multiple if else

django.db.utils.DataError: value too long for type character varying(100)

I suggest using Text field

New release

Hi guys,

would it be possible to get a new release including the new Sendinblue provider?

Cheers

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.