Coder Social home page Coder Social logo

pinax / pinax-notifications Goto Github PK

View Code? Open in Web Editor NEW

This project forked from jtauber-archive/django-notification

743.0 29.0 205.0 443 KB

user notification management for the Django web framework

License: MIT License

Makefile 0.26% Python 99.45% HTML 0.29%

pinax-notifications's Introduction

Pinax Notifications

CircleCi Codecov

Table of Contents

About Pinax

Pinax is an open-source platform built on the Django Web Framework. It is an ecosystem of reusable Django apps, themes, and starter project templates. This collection can be found at http://pinaxproject.com.

Important Links

Where you can find what you need:

pinax-notifications

Overview

pinax-notifications is a user notification management app for the Django web framework. Many sites need to notify users when certain events have occurred and to allow configurable options as to how those notifications are to be received. pinax-notifications serves this need.

Features

  • Submission of notification messages by other apps
  • Notification messages via email (configurable by user)
  • Ability to supply your own backend notification channels
  • Ability to scope notifications at the site level

Supported Django and Python Versions

Django / Python 3.6 3.7 3.8
2.2 * * *
3.0 * * *

Documentation

Installation

To install pinax-notifications:

$ pip install pinax-notifications

Add pinax.notifications to your INSTALLED_APPS setting:

INSTALLED_APPS = [
    # other apps
    "pinax.notifications",
]

Add pinax.notifications.urls to your project urlpatterns:

urlpatterns = [
    # other urls
    url(r"^notifications/", include("pinax.notifications.urls", namespace="pinax_notifications")),
]

Usage

Integrating notification support into your app is a three-step process:

  1. create your notice types
  2. create your notice templates
  3. send notifications

Creating Notice Types

You need to call NoticeType.create(label, display, description) once to create the notice types for your application in the database.

  • label is the internal shortname that will be used for the type
  • display is what the user sees as the name of the notification type
  • description is a short description

For example:

from pinax.notifications.models import NoticeType

NoticeType.create(
    "friends_invite",
    "Invitation Received",
    "you have received an invitation"
)

One way to create notice types is using a custom AppConfig. Here is an example:

# myapp/signals/handlers.py

from django.conf import settings
from django.utils.translation import ugettext_noop as _

def create_notice_types(sender, **kwargs): 
    if "pinax.notifications" in settings.INSTALLED_APPS:
        from pinax.notifications.models import NoticeType
        print("Creating notices for myapp")
        NoticeType.create("friends_invite", _("Invitation Received"), _("you have received an invitation"))
        NoticeType.create("friends_accept", _("Acceptance Received"), _("an invitation you sent has been accepted"))
    else:
        print("Skipping creation of NoticeTypes as notification app not found")

Notice that the code is wrapped in a conditional clause so if pinax-notifications is not installed, your app will proceed anyway.

Note that the display and description arguments are marked for translation by using ugettext_noop. That will enable you to use Django's makemessages management command and use pinax-notifications i18n capabilities.

# myapp/apps.py

from django.apps import AppConfig
from django.db.models.signals import post_migrate

from myapp.signals import handlers

class MyAppConfig(AppConfig):
    name = 'myapp'
    verbose_name = 'My App'

    def ready(self):
        post_migrate.connect(handlers.create_notice_types, sender=self)

This will call the handler to create notices after the application is migrated.

# myapp/__init__.py

default_app_config = 'myapp.apps.MyAppConfig'

Templates

Default templates are provided by the pinax-templates app in the notifications section of that project.

Reference pinax-templates installation instructions to include these templates in your project.

View live pinax-templates examples and source at Pinax Templates!

Customizing Templates

Override the default pinax-templates templates by copying them into your project subdirectory pinax/notifications/ on the template path and modifying as needed.

For example if your project doesn't use Bootstrap, copy the desired templates then remove Bootstrap and Font Awesome class names from your copies. Remove class references like class="btn btn-success" and class="icon icon-pencil" as well as bootstrap from the {% load i18n bootstrap %} statement. Since bootstrap template tags and filters are no longer loaded, you'll also need to update {{ form|bootstrap }} to {{ form }} since the "bootstrap" filter is no longer available.

base.html

Base template for other templates.

notice_settings.html

This template allows the user to specify which notices they want to receive. This template is rendered by the sole view in pinax.notifications.views with the context containing a list of available notice_types as well as the request.user's settings for those notice types.

Backend Templates

Four templates included with pinax-templates support the single email backend that is included with pinax-notifications.

short.txt

Renders to the email subject.

full.txt

Renders to the email body.

email_body.txt

Renders the entire email body. Contains full.txt.

email_subject.txt

Renders the entire email subject. Contains short.txt.

In addition to the extra context supplied via the send call in your site or app, these templates are rendered with the following context variables:

  • default_http_protocol - https if settings.PINAX_USE_SSL is True, otherwise http
  • current_site - Site.objects.get_current()
  • base_url - the default http protocol combined with the current site domain
  • recipient - the user who is getting the notice
  • sender - the value supplied to the sender kwarg of the send method (often this is not set and will be None)
  • notice - display value of the notice type

You can override default templates shipped with pinax-templates by adding alternative templates to a directory on the template path called pinax/notifications/<notice_type_label>/. For the example NoticeType above we might override short.txt to surround the notice with asterisks:

{# pinax/notifications/friends_invite/short.txt #}
{% autoescape off %}{% load i18n %}{% blocktrans %}*** {{ notice }} ***{% endblocktrans %}{% endautoescape %}

If any of the four email backend templates are missing from the alternative directory, the appropriate installed default template is used.

Sending Notifications

There are two different ways of sending out notifications. We have support for blocking and non-blocking methods of sending notifications. The most simple way to send out a notification, for example::

from pinax.notifications.models import send_now, send, queue

send([to_user], "friends_invite", {"from_user": from_user})

One thing to note is that send is a proxy around either send_now or queue. They all have the same signature::

send(users, label, extra_context)

The parameters are:

  • users is an iterable of User objects to send the notification to.
  • label is the label you used in the previous step to identify the notice type.
  • extra_content is a dictionary to add custom context entries to the template used to render to notification. This is optional.
send_now vs. queue vs. send

Lets first break down what each does.

send_now

This is a blocking call that will check each user for elgibility of the notice and actually peform the send.

queue

This is a non-blocking call that will queue the call to send_now to be executed at a later time. To later execute the call you need to use the emit_notices management command.

send

A proxy around send_now and queue. It gets its behavior from a global setting named PINAX_NOTIFICATIONS_QUEUE_ALL. By default it is False. This setting is meant to help control whether you want to queue any call to send.

send also accepts now and queue keyword arguments. By default each option is set to False to honor the global setting which is False. This enables you to override on a per call basis whether it should call send_now or queue.

Optional Notification Support

In case you want to use pinax-notifications in your reusable app, you can wrap the import of pinax-notifications in a conditional clause that tests if it's installed before sending a notice. As a result your app or project still functions without notification.

For example:

from django.conf import settings

if "notification" in settings.INSTALLED_APPS:
    from pinax.notifications import models as notification
else:
    notification = None

and then, later:

if notification:
    notification.send([to_user], "friends_invite", {"from_user": from_user})

Settings

The following allows you to specify the behavior of pinax-notifications in your project. Please be aware of the native Django settings which can affect the behavior of pinax-notifications.

PINAX_NOTIFICATIONS_BACKENDS

Defaults to:

[
    ("email", "pinax.notifications.backends.email.EmailBackend"),
]

Formerly named NOTIFICATION_BACKENDS.

PINAX_USE_SSL

This is a proposed common setting across the Pinax ecosystem. It currently may not be consistant across all apps.

Defaults to False.

This is used to specify the beginning of URLs in the default email_body.txt file. A common use-case for overriding this default might be https for use on more secure projects.

Formerly named DEFAULT_HTTP_PROTOCOL and defaulted to "http".

PINAX_NOTIFICATIONS_LANGUAGE_MODEL

There is not set default for this setting. It allows users to specify their own notification language.

Example model in a languages app::

from django.conf import settings

class Language(models.Model):

    user = models.ForeignKey(User)
    language = models.CharField(max_length=10, choices=settings.LANGUAGES)

Setting this value in settings.py::

PINAX_NOTIFICATIONS_LANGUAGE_MODEL = "languages.Language"

Formerly named NOTIFICATION_LANGUAGE_MODULE.

DEFAULT_FROM_EMAIL

Defaults to webmaster@localhost and is a standard Django setting.

Default e-mail address to use for various automated correspondence from pinax.notifications.backends.email.

LANGUAGES

Defaults to a tuple of all available languages and is a standard Django setting.

The default for this is specifically used for things like the Django admin. However, if you need to specify a subset of languages for your site's front end you can use this setting to override the default. In which case this is the definated pattern of usage::

gettext = lambda s: s

LANGUAGES = (
    ("en", gettext("English")),
    ("fr", gettext("French")),
)

PINAX_NOTIFICATIONS_QUEUE_ALL

It defaults to False.

By default, calling notification.send will send the notification immediately, however, if you set this setting to True, then the default behavior of the send method will be to queue messages in the database for sending via the emit_notices command.

Formerly named NOTIFICATION_QUEUE_ALL.

PINAX_NOTIFICATIONS_LOCK_WAIT_TIMEOUT

It defaults to -1.

It defines how long to wait for the lock to become available. Default of -1 means to never wait for the lock to become available. This only applies when using crontab setup to execute the emit_notices management command to send queued messages rather than sending immediately.

Formerly named NOTIFICATION_LOCK_WAIT_TIMEOUT.

Scoping Notifications

Sometimes you have a site that has groups or teams. Perhaps you are using pinax-teams. If this is the case you likely want users who might be members of multiple teams to be able to set their notification preferences on a per team or group basis.

You will need to to simply override NoticeSettingsView to provide your own scoping object.

Override NoticeSettingsView

I think it's best if we just demonstrate via code:

# views.py

from pinax.notifications.views import NoticeSettingsView


class TeamNoticeSettingsView(NoticeSettingsView):
    
    @property
    def scoping(self):
        return self.request.team

Then override the url:

# urls.py

from django.conf.urls import url

from .views import TeamNoticeSettingsView


urlpatterns = [
    # other urls
    url(r"^notifications/settings/$", TeamNoticeSettingsView.as_view(), name="notification_notice_settings"),
]

Change Log

6.0.0

  • Drop Django 1.11, 2.0, and 2.1, and Python 2,7, 3.4, and 3.5 support
  • Add Django 2.2 and 3.0, and Python 3.6, 3.7, and 3.8 support
  • Update packaging configs
  • Direct users to community resources

5.0.2

  • Remove unneeded compatibility

5.0.1

  • Fix bytestring decoding bug
  • Update django>=1.11 in requirements
  • Update CI config
  • Add sorting guidance for 3rd-party app imports
  • Improve documentation and markup

5.0.0

  • Standardize documentation layout
  • Drop Django v1.8, v1.10 support

4.1.2

  • Fix another silly documentation error

4.1.1

  • Fix installation documentation

4.1.0

  • Add Django 2.0 compatibility testing
  • Drop Django 1.9 and Python 3.3 support
  • Move documentation into README
  • Convert CI and coverage to CircleCi and CodeCov
  • Add PyPi-compatible long description

4.0

  • BI: To support changes to render_to_string in Django 1.10 and above, your notice full.txt and short.txt plain text templates must now be autoescaped explicitly using the {% autoescape %} tag. (#68)

3.0.1

  • initial support for Django 1.10

3.0

  • fix compatability with Django migrations

2.1.0

  • add Django migrations

2.0

  • renamed app as pinax-notifications
  • added the ability to override NoticeSetting model
  • added documentation on scoping notifications

1.1.1

  • fixed a deprecation warning

1.1

  • added Russian locale
  • added travis integration for tests/lints
  • added created_notice_type wrapper
  • cleaned up some small bugs identified by pylint

1.0

  • removed unused message.py module
  • removed captureas templatetag
  • added notice_settings.html template
  • other minor fixes and tweaks, mostly to code style

0.3

  • pluggable backends

0.2.0

  • BI: renamed Notice.user to Notice.recipient
  • BI: renamed {{ user }} context variable in notification templates to {{ recipient }}
  • BI: added nullable Notice.sender and modified send_now and queue to take an optional sender
  • added received and sent methods taking a User instance to Notice.objects
  • New default behavior: single notice view now marks unseen notices as seen
  • no longer optionally depend on mailer; use django.core.mail.send_mail and we now encourge use of Django 1.2+ for mailer support
  • notifications are not sent to inactive users
  • users which do not exist when sending notification are now ignored
  • BI: split settings part of notices view to its own view notice_settings

0.1.5

  • added support for DEFAULT_HTTP_PROTOCOL allowing https absolute URLs

BI = backward incompatible change

History

This app was originally named django-notification but was renamed to bring a common package name like notification under the pinax namespace to avoid conflicts with other like named packages.

In addition, we wanted to take the opportunity to rename it to the plural form, notifications to be in line with the convention we've adopted across the ecosystem.

Contribute

Contributing information can be found in the Pinax community health file repo.

Code of Conduct

In order to foster a kind, inclusive, and harassment-free community, the Pinax Project has a Code of Conduct. We ask you to treat everyone as a smart human programmer that shares an interest in Python, Django, and Pinax with you.

Connect with Pinax

For updates and news regarding the Pinax Project, please follow us on Twitter @pinaxproject and check out our Pinax Project blog.

License

Copyright (c) 2012-present James Tauber and contributors under the MIT license.

pinax-notifications's People

Contributors

aert avatar arthur-wsw avatar brosner avatar dmzio avatar empty avatar frewsxcv avatar giff-h avatar grahamu avatar jacobwegner avatar jantoniomartin avatar katherinemichel avatar nrb avatar paltman avatar penguinvasion avatar psychok7 avatar sherzberg avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pinax-notifications's Issues

Migration fails with Django-1.7.x

When running python manage.py migrate with Django-1.7.8, an exception is thrown and the migration fails. The relevant part of the traceback is this:

ValueError: Lookup failed for model referenced by field notifications.NoticeSetting.scoping_content_type: contenttypes.ContentType

account.models.Account doesn't declare an explicit app_label

I've encountered

RuntimeError: Model class account.models.Account doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.

after upgrading Django to 1.11.

This can be resolved by adding 'account' to INSTALLED_APPS but I don't think that should be needed.

Can you suggest what might be wrong? Thank you

GenericRelation for user in NoticeSetting

Is there a way to create notifications for multiple type of users (using different models for each one)?

in NoticeSetting the user FK is AUTH_USER_MODEL so it just point to one type of user :/

migrate failing: Cannot add foreign key constraint

I'm upgrading from django 1.6.x to 1.8.x and upgrading from the pre-pinax notification app to the pinax.notifications app. I have all my migrations set and applied. The last is to migrate the notifications. It fails when trying to add the constraint on noticesetting.scoping_content_type. It just says django.db.utils.IntegrityError: (1215, 'Cannot add foreign key constraint')

The django_content_type table has already been migrated but it doesn't seem to want to add this constraint. It's weird because I have many other models that have a ForeignKey to ContentType. I've even tried completely removing notifications and just running the full migrate and I get the same error. Any other ideas?

Connection refused error

Whenever I submit form and send the notification I always get connection refused error error111

Two questions

This looks like a great project! Would you mind answering a couple questions?

  1. What is a typical way to schedule notificaitons being sent (cron job to emit_notices?)
  2. Can a user "unsubscribe" from email notifications but still get web notifications?
  3. Can some notifications be scheduled every hour and others each day?

Thanks!

Migration error when used with condottieri_notification

condottieri_notification app migration file 0001_initial dependencies reference nonexistent parent node ('pinax_notifications', '0002_auto_20180118_0138')

Any ideas?

raise NodeNotFoundError(self.error_message, self.key, origin=self.origin)
django.db.migrations.exceptions.NodeNotFoundError: Migration condottieri_notification.0001_initial dependencies reference nonexistent parent node ('pinax_notifications', '0002_auto_20180118_0138')

Incompatable with Custom user models with migrations in Django 1.8

After upgrading to Django 1.8 I am not able to initialize a new database with syncdb/migrate .

The problem is with unmigrated models that depend on migrated models, in this case pinax.notifications. NoticeSetting and a custom user model that is migrated.

According to a ticket in the Django bug tracker this is not due to a bug in django, but due to a bug that was fixed, where previously constraints on non-existant tables where silently ingored, they now cause an error.

Django bug https://code.djangoproject.com/ticket/24311
Test case https://github.com/JesseCrocker/testcase-django-1.8-customuser-migration-order

No more ObservedItem?

Hi,

I am not sure if it is the correct place to ask for this but here it is. I upgraded django-notification through pip from version 0.2 to version 1.0 and models.ObservedItem disappeared. I wanted to understand why but this new "official" repository was initialized recently without any previous history.
Is there a new Django-way that makes the models.ObservedItem unnecessary? Why did it get dropped from the repo?

Thanks,
Seb.

Fix django3.2 deprecated / dropped features

Issue: running django 3.2 causes several deprecation warnings for features removed in django4.0

pull request coming to:

  • fix deprecation issues;
  • add tox tests for versions python3.9 and django3.2, removed unsupported versions: python3.6 and django3.0

I note a couple of these are fixed as individual items in 2 PR's in queue - packaging all required changes together here.

Make it possible to use a language field stored on the user model directly

Currently it is not possible to put the language field directly on the user model because the get_default_language() function expects to find it on a related model of the one specified in PINAX_NOTIFICATIONS_LANGUAGE_MODEL. I'm referring to this part of the code:

language = model._default_manager.get(user__id__exact=user.id)

While I understand the reasoning for this, I think it would be useful to also look for the language in the user model directly. Something like:

model = settings.PINAX_NOTIFICATIONS_GET_LANGUAGE_MODEL()
try:
    language = model._default_manager.get(user__id__exact=user.id)
except FieldError:  # maybe we're using custom a user model?
    language = getattr(model, "language", None)

If this is not acceptable, adding FieldError to the tuple of exceptions which are caught would at least allow the function to still complete without error.

This would cater for use cases where the user model has been extended with additional fields.

Call for Maintainers

Looking for maintainers!

There is a lot of pull requests and open issues that the current maintainers, myself included, are just not finding the time to properly get to.

Maybe you've submitted some PRs and are frustrated with the lack of attention. Maybe you use this project in one or more of your projects and want to see that it is properly carried forward.

Whatever you reasons may be, let me know if you have interest and I'll add you to the repo and to PyPI (will need your PyPI name).

Preference will go to those who have commits on this repo and/or have shown an active interest in the issues.

Thanks!
Patrick

Documentation create_notice_type

Hi,

In the documentation we are referring to a method/function create_notice_type.
Looking at the code in model, it seems that now this is called send_now or send.

Next release?

Any plans on making the recent changes available via pip? Will be nice to see the custom user support there.

Incompatibility with Django 1.10 (render_to_string changed)

I'm getting an exception when trying to call send().

  File "/home/vagrant/.pyenv/versions/eoi/lib/python2.7/site-packages/pinax/notifications/models.py", line 187, in send
    return send_now(*args, **kwargs)
  File "/home/vagrant/.pyenv/versions/eoi/lib/python2.7/site-packages/pinax/notifications/models.py", line 161, in send_now
    backend.deliver(user, sender, notice_type, extra_context)
  File "/home/vagrant/.pyenv/versions/eoi/lib/python2.7/site-packages/pinax/notifications/backends/email.py", line 36, in deliver
    }, context).splitlines())
  File "/home/vagrant/.pyenv/versions/eoi/lib/python2.7/site-packages/django/template/loader.py", line 68, in render_to_string
    return template.render(context, request)
  File "/home/vagrant/.pyenv/versions/eoi/lib/python2.7/site-packages/django/template/backends/django.py", line 66, in render
    return self.template.render(context)
  File "/home/vagrant/.pyenv/versions/eoi/lib/python2.7/site-packages/django/template/base.py", line 206, in render
    with context.bind_template(self):
  File "/home/vagrant/.pyenv/versions/2.7.12/lib/python2.7/contextlib.py", line 17, in __enter__
    return self.gen.next()
  File "/home/vagrant/.pyenv/versions/eoi/lib/python2.7/site-packages/django/template/context.py", line 236, in bind_template
    updates.update(processor(self.request))
  File "/home/vagrant/.pyenv/versions/eoi/lib/python2.7/site-packages/django/template/context_processors.py", line 43, in debug
    if settings.DEBUG and request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS:

The dictionary and context_instance parameters were removed from django.template.loader.render_to_string() in Django 1.10 (https://docs.djangoproject.com/en/1.10/releases/1.10/). The new docs on render_to_string are here: http://django.readthedocs.io/en/latest/topics/templates.html#django.template.loader.render_to_string).

However, pinax/notifications/backends/email.py calls it like so:

        subject = "".join(render_to_string("pinax/notifications/email_subject.txt", {
            "message": messages["short.txt"],
        }, context).splitlines())

the lock in send_all() [engine.py Line 41] doesn't work

not sure it's a pinax.notifications issue:

In the function send_all() of file engine.py ,
the lock seems have no effect.
when lock is None, the code below can still run.

def send_all(*args):
    lock = acquire_lock(*args)
    batches, sent, sent_actual = 0, 0, 0
    start_time = time.time()
    ……

Did I use it in the wrong way ? Thank you.

Why is NoticeType not just a simple Enum?

Hey guys,

loving the idea of the package so far. I found the installation steps for the NoticeTypes quite interesting, though. I'd be curious to learn why you choose for saving the NoticeTypes in the DB while there is a need to hardcode them in the rest of the code?

Why did you not go for a simple Enum or object which a) doesn't need DB access b) is much easier to set up?

I'd be happy to provide a pull-request in case this is something you were contemplating. I understand that this could mean a breaking change with a new version of pinax-notifications.

Extending missing "account/base.html"

Notifications settings page is extending base template account/base.html which does not come with Django. (It comes with pinax themes though.)
This should either be documented or extend a template that exists by default.

TemplateDoesNotExist at /notifications/settings/
account/base.html

[Enhancement] NoticeSettingsView queryset

Thanks for this handy app!

Here is a suggestion for improving(?) the settings view:
Right now when users access settings view, they can update their settings for all NoticeTypes.
A project might have some notices which are important and must be sent and it is better not to let users to opt out of those.
One way to handle this situation is using default field to filter NoticeType queryset in NoticeSettingsView. For example:

# views.NoticeSettingsView
def settings_table(self):
        notice_types = NoticeType.objects.filter(default__lt=settings.FILTER_THRESHOLD)

Or if there is any other built-in solution, please let me know! :)

Notifications in HTML format

Thank you for this great app,

I am having a problem sending notification in HTML format. The notifications are sent successfully, but always sent using the full.txt file instead of notice.html.

Need your help, thank you

Apps aren't loaded yet.

I'm using django 1.11.18 and every time I try to makemigrations this error comes up
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.

migrations with OneToOneField to NoticeType fail

not sure it's a pinax.notifications issue, I have this problem:

one of my models has a field defined as

notice_type = models.OneToOneField(
    'notifications.NoticeType',
    on_delete=models.CASCADE)

when running ./manage.py makemigrations the following dependency is created

# note the date following 0002_auto_ depending on when makemigrations was invoked
('notifications', '0002_auto_20160513_1548'),

all works fine if I run ./manage.py migrate on the same machine where I created migrations, but on another machine I get the following:

django.db.migrations.exceptions.NodeNotFoundError: Migration core.0001_initial dependencies reference nonexistent parent node (u'notifications', u'0002_auto_20160513_1548')

any advise and/or workaround would be great

thanks

Migration fails with Django-1.8.2 and MariaDB

After trying to solve issue #48 without success, I decided to try with Django-1.8.2 and a new, empty database. When running python manage.py migrate, this is the exception I get:

django.db.utils.OperationalError: (1005, 'Can\'t create table `app_dev`.`#sql-903_12fd` (errno: 150 "Foreign key constraint is incorrectly formed")')

Then I have tried a new sqlite3 database and the migration runs correctly.

Django 1.5 user model problem

Unhandled exception in thread started by <bound method Command.inner_run of <django.contrib.staticfiles.management.commands.runserver.Command object at 0x108798bd0>>
Traceback (most recent call last):
File "/Library/Python/2.7/site-packages/django/core/management/commands/runserver.py", line 92, in inner_run
self.validate(display_num_errors=True)
File "/Library/Python/2.7/site-packages/django/core/management/base.py", line 284, in validate
raise CommandError("One or more models did not validate:\n%s" % error_text)
django.core.management.base.CommandError: One or more models did not validate:
notification.noticesetting: 'user' defines a relation with the model 'auth.User', which has been swapped out. Update the relation to point at settings.AUTH_USER_MODEL.

No way to view notices on signing in

The README.rst says:

The project aims to provide a Django app for this sort of functionality. This includes:

* notification messages on signing in

I think this functionality used to be provided by the notices view, which was removed by a2fd330.

I can't find any issue or message explaining why this functionality (which seems like a really good idea) was removed.

Therefore, I guess this is either:

  • an issue with that view notices functionality, if it is still part of the scope of the app
  • or an issue with the documentation, if it is no longer part of the current or future functionality

Migration error with django 1.7

I am using Django 1.7 with pinax-notifications 2.1.0 and i get an error when i try to do a migrate:

Traceback:

(test)vagrant@vagrant:/vagrant$ python manage.py migrate --settings=test.settings.local
Traceback (most recent call last):
  File "manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/home/vagrant/.virtualenvs/test/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 385, in execute_from_command_line
    utility.execute()
  File "/home/vagrant/.virtualenvs/test/local/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/vagrant/.virtualenvs/test/local/lib/python2.7/site-packages/django/core/management/base.py", line 288, in run_from_argv
    self.execute(*args, **options.__dict__)
  File "/home/vagrant/.virtualenvs/test/local/lib/python2.7/site-packages/django/core/management/base.py", line 338, in execute
    output = self.handle(*args, **options)
  File "/home/vagrant/.virtualenvs/test/local/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 63, in handle
    executor = MigrationExecutor(connection, self.migration_progress_callback)
  File "/home/vagrant/.virtualenvs/test/local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 17, in __init__
    self.loader = MigrationLoader(self.connection)
  File "/home/vagrant/.virtualenvs/test/local/lib/python2.7/site-packages/django/db/migrations/loader.py", line 48, in __init__
    self.build_graph()
  File "/home/vagrant/.virtualenvs/test/local/lib/python2.7/site-packages/django/db/migrations/loader.py", line 245, in build_graph
    self.graph.add_dependency(migration, key, parent)
  File "/home/vagrant/.virtualenvs/test/local/lib/python2.7/site-packages/django/db/migrations/graph.py", line 46, in add_dependency
    "Migration %s dependencies reference nonexistent parent node %r" % (migration, parent)
KeyError: u"Migration notifications.0001_initial dependencies reference nonexistent parent node (u'contenttypes', u'0002_remove_content_type_name')"

WORKAROUND: Downgrade to pinax-notifications==2.0.1

pinax-notifications 4.x won't install templates and locales

Notifications won't install templates data (templates/pinax/notifications/*) in recent version, when installed through pypi. I believe this is caused by:
07076ff#diff-2eeaed663bd0d25b7e608891384b7298 :

4.0:

cezio@gburek [tmp $]>mkvirtualenv blank
New python executable in /home/cezio/.virtualenvs/blank/bin/python2.7
Also creating executable in /home/cezio/.virtualenvs/blank/bin/python
Installing setuptools, pip, wheel...done.
virtualenvwrapper.user_scripts creating /home/cezio/.virtualenvs/blank/bin/predeactivate
virtualenvwrapper.user_scripts creating /home/cezio/.virtualenvs/blank/bin/postdeactivate
virtualenvwrapper.user_scripts creating /home/cezio/.virtualenvs/blank/bin/preactivate
virtualenvwrapper.user_scripts creating /home/cezio/.virtualenvs/blank/bin/postactivate
virtualenvwrapper.user_scripts creating /home/cezio/.virtualenvs/blank/bin/get_env_details
 
cezio@gburek [tmp $]>pip install pinax-notifications
Collecting pinax-notifications
  Using cached pinax_notifications-4.0.0-py2.py3-none-any.whl
Collecting django-appconf>=1.0.1 (from pinax-notifications)
  Using cached django_appconf-1.0.2-py2.py3-none-any.whl
Installing collected packages: django-appconf, pinax-notifications
Successfully installed django-appconf-1.0.2 pinax-notifications-4.0.0

cezio@gburek [tmp $]>find /home/cezio/.virtualenvs/blank/lib/python2.7/site-packages/pinax/notifications/ -type d
/home/cezio/.virtualenvs/blank/lib/python2.7/site-packages/pinax/notifications/
/home/cezio/.virtualenvs/blank/lib/python2.7/site-packages/pinax/notifications/migrations
/home/cezio/.virtualenvs/blank/lib/python2.7/site-packages/pinax/notifications/management
/home/cezio/.virtualenvs/blank/lib/python2.7/site-packages/pinax/notifications/management/commands
/home/cezio/.virtualenvs/blank/lib/python2.7/site-packages/pinax/notifications/backends
/home/cezio/.virtualenvs/blank/lib/python2.7/site-packages/pinax/notifications/tests

3.x:

cezio@gburek [tmp $]>pip install 'pinax-notifications<4.0'
Collecting pinax-notifications<4.0
  Using cached pinax_notifications-3.0.1-py2.py3-none-any.whl
Requirement already satisfied: django-appconf>=1.0.1 in /home/cezio/.virtualenvs/blank/lib/python2.7/site-packages (from pinax-notifications<4.0)
Installing collected packages: pinax-notifications
  Found existing installation: pinax-notifications 4.0.0
    Uninstalling pinax-notifications-4.0.0:
      Successfully uninstalled pinax-notifications-4.0.0
Successfully installed pinax-notifications-3.0.1
 
cezio@gburek [tmp $]>find /home/cezio/.virtualenvs/blank/lib/python2.7/site-packages/pinax/notifications/ -type d
/home/cezio/.virtualenvs/blank/lib/python2.7/site-packages/pinax/notifications/
/home/cezio/.virtualenvs/blank/lib/python2.7/site-packages/pinax/notifications/migrations
/home/cezio/.virtualenvs/blank/lib/python2.7/site-packages/pinax/notifications/templates
/home/cezio/.virtualenvs/blank/lib/python2.7/site-packages/pinax/notifications/templates/pinax
/home/cezio/.virtualenvs/blank/lib/python2.7/site-packages/pinax/notifications/templates/pinax/notifications
/home/cezio/.virtualenvs/blank/lib/python2.7/site-packages/pinax/notifications/locale
/home/cezio/.virtualenvs/blank/lib/python2.7/site-packages/pinax/notifications/locale/es_AR
/home/cezio/.virtualenvs/blank/lib/python2.7/site-packages/pinax/notifications/locale/es_AR/LC_MESSAGES
/home/cezio/.virtualenvs/blank/lib/python2.7/site-packages/pinax/notifications/locale/ru
/home/cezio/.virtualenvs/blank/lib/python2.7/site-packages/pinax/notifications/locale/ru/LC_MESSAGES
/home/cezio/.virtualenvs/blank/lib/python2.7/site-packages/pinax/notifications/locale/fr
/home/cezio/.virtualenvs/blank/lib/python2.7/site-packages/pinax/notifications/locale/fr/LC_MESSAGES
/home/cezio/.virtualenvs/blank/lib/python2.7/site-packages/pinax/notifications/management
/home/cezio/.virtualenvs/blank/lib/python2.7/site-packages/pinax/notifications/management/commands
/home/cezio/.virtualenvs/blank/lib/python2.7/site-packages/pinax/notifications/backends
/home/cezio/.virtualenvs/blank/lib/python2.7/site-packages/pinax/notifications/tests

Additional backends

I need to recover the possibility to show notices on the website, so I want to make a new backend to get this functionality.
Which is the best approach to do this?

My first try has been to make a separated app with the new backend and a Notice model. However, this creates a new migration in pinax-notifications because of pinax.notifications.utils.load_media_defaults, which alters the field NoticeSetting.medium.

A different approach would be adding this new backend directly to pinax-notifications, but I don't know if this is something that could be eventually accepted.

And a last possibility would be adding it to my own fork.

Maybe @paltman could shed some light on this subject before I take one of the options.

cannot send iterable users list to send notification

From the docs:

notification.send([to_user], "friends_invite", {"from_user": from_user})
users is an iterable of User objects to send the notification to.

I'm not sure to understand, a list [] in python is an iterable right? If I pass a list of users to the send function I get:

TypeError: int() argument must be a string or a number, not 'list'

but if I pass only one user the function keeps going.

Is it a bug or did I miss something?

What's the difference between notice_type and medium?

Thanks for this package once again and the great work with it.

I have another question about the code. This time about this part of the NoticeSetting-model:

    notice_type = models.ForeignKey(
        NoticeType,
        verbose_name=_("notice type"),
        on_delete=models.CASCADE
    )
    medium = models.CharField(_("medium"), max_length=1, choices=NOTICE_MEDIA)

Medium gets its choice values from load_media_defaults() which basically refers to the PINAX_NOTIFICATION_BACKENDS setting. This setting should contain the same values as the created model instances of NoticeTypes if I'm not mistaken.

So that's why I wonder what medium is supposed to mean or do here that's different from the notice_type field? Is there a difference to notice_type or is it literally just a reference to the same data just once packaged as a tuple in settings, and once as a database entry?

Does it have something to do with the spam sensitivity perhaps? I couldn't find any info on how that works.

Thanks for your help in this matter.

Pinax conflicting with django-notifications-hq

I've been using django-notifications-hq (https://github.com/django-notifications/django-notifications) along with the old version of pinax-notifications (i.e. when it was still django-notification). The problem now is that I cannot upgrade to pinax-notifications because of an application name conflict.

Traceback (most recent call last):
  File "./manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/code/.pyenv/versions/testapp-2.7/lib/python2.7/site-packages/django/core/management/__init__.py", line 354, in execute_from_command_line
    utility.execute()
  File "/code/.pyenv/versions/testapp-2.7/lib/python2.7/site-packages/django/core/management/__init__.py", line 328, in execute
    django.setup()
  File "/code/.pyenv/versions/testapp-2.7/lib/python2.7/site-packages/django/__init__.py", line 18, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/code/.pyenv/versions/testapp-2.7/lib/python2.7/site-packages/django/apps/registry.py", line 89, in populate
    "duplicates: %s" % app_config.label)
django.core.exceptions.ImproperlyConfigured: Application labels aren't unique, duplicates: notifications

Any easy way to resolve this?

Deletion of stale content types raises ProgrammingError

When there are stale content types to be deleted I am getting bellow error. I am not able to proceed with yes option. Any help? Thanks!

(venv) F:\Freelancer\company\project>fab manage:migrate,notifications
[localhost] local: python manage.py migrate notifications
Operations to perform:
  Apply all migrations: notifications
Running migrations:
  No migrations to apply.
The following content types are stale and need to be deleted:

    lp_settings | shortnotifications
    lp_settings | notification

Any objects related to these content types by a foreign key will also
be deleted. Are you sure you want to delete these content types?
If you're unsure, answer 'no'.

    Type 'yes' to continue, or 'no' to cancel: yes
Traceback (most recent call last):
  File "manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "F:\Freelancer\company\project\venv\lib\site-packages\django\core\management\__init__.py", line 385, in execute_from_command_line
    utility.execute()
  File "F:\Freelancer\company\project\venv\lib\site-packages\django\core\management\__init__.py", line 377, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "F:\Freelancer\company\project\venv\lib\site-packages\django\core\management\base.py", line 288, in run_from_argv
    self.execute(*args, **options.__dict__)
  File "F:\Freelancer\company\project\venv\lib\site-packages\django\core\management\base.py", line 338, in execute
    output = self.handle(*args, **options)
  File "F:\Freelancer\company\project\venv\lib\site-packages\django\core\management\commands\migrate.py", line 165, in handle
    emit_post_migrate_signal(created_models, self.verbosity, self.interactive, connection.alias)
  File "F:\Freelancer\company\project\venv\lib\site-packages\django\core\management\sql.py", line 268, in emit_post_migrate_signal
    using=db)
  File "F:\Freelancer\company\project\venv\lib\site-packages\django\dispatch\dispatcher.py", line 198, in send
    response = receiver(signal=self, sender=sender, **named)
  File "F:\Freelancer\company\project\venv\lib\site-packages\django\contrib\contenttypes\management.py", line 84, in update_contenttypes
    ct.delete()
  File "F:\Freelancer\company\project\venv\lib\site-packages\django\db\models\base.py", line 739, in delete
    collector.delete()
  File "F:\Freelancer\company\project\venv\lib\site-packages\django\db\models\deletion.py", line 262, in delete
    qs._raw_delete(using=self.using)
  File "F:\Freelancer\company\project\venv\lib\site-packages\django\db\models\query.py", line 569, in _raw_delete
    sql.DeleteQuery(self.model).delete_qs(self, using)
  File "F:\Freelancer\company\project\venv\lib\site-packages\django\db\models\sql\subqueries.py", line 85, in delete_qs
    self.get_compiler(using).execute_sql(NO_RESULTS)
  File "F:\Freelancer\company\project\venv\lib\site-packages\django\db\models\sql\compiler.py", line 787, in execute_sql
    cursor.execute(sql, params)
  File "F:\Freelancer\company\project\venv\lib\site-packages\django\db\backends\utils.py", line 81, in execute
    return super(CursorDebugWrapper, self).execute(sql, params)
  File "F:\Freelancer\company\project\venv\lib\site-packages\django\db\backends\utils.py", line 65, in execute
    return self.cursor.execute(sql, params)
  File "F:\Freelancer\company\project\venv\lib\site-packages\django\db\utils.py", line 94, in __exit__
    six.reraise(dj_exc_type, dj_exc_value, traceback)
  File "F:\Freelancer\company\project\venv\lib\site-packages\django\db\backends\utils.py", line 65, in execute
    return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: column notifications_noticesetting.scoping_content_type_id does not exist
LINE 1: DELETE FROM "notifications_noticesetting" WHERE "notificatio...
                                                        ^

Error updating to 1.3.1 from 1.2.0

Hello, I have this issue (on mac OS 10.10, Yosemite, Python 2.7.8 - on a virtualenv):

pip install django-notification --upgrade
DEPRECATION: --download-cache has been deprecated and will be removed in the future. Pip now automatically uses and configures its cache.
Collecting django-notification from https://pypi.python.org/packages/source/d/django-notification/django-notification-1.3.tar.gz#md5=a21de916c7d803c82e83d2b6b38cb37f
  Using cached django-notification-1.3.tar.gz
    /usr/local/Cellar/python/2.7.8_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/distutils/dist.py:267: UserWarning: Unknown distribution option: 'install_required'
      warnings.warn(msg)
Installing collected packages: django-notification
  Found existing installation: django-notification 1.2.0
    Uninstalling django-notification-1.2.0:
      Successfully uninstalled django-notification-1.2.0
  Running setup.py install for django-notification
    /usr/local/Cellar/python/2.7.8_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/distutils/dist.py:267: UserWarning: Unknown distribution option: 'install_required'
      warnings.warn(msg)
    error: can't copy 'notification/templates/notification': doesn't exist or not a regular file

full trace on pastebin

I have no idea how to circumvent/fix this issue. It seems that setup.py is unable to find the contents of the templates folder. pip and setuptools are updated to the latest version. If you need any other info please do not hesitate to ask me,
Thanks in advance!
Stefano

Question - Showing the notifications in app, when user sign-in.

Thanks for providing this app. It seems very useful. After reading the functionality at various places (e.g. stack overflow, and few blogs), I included this app to show the notifications in the app (not via email.) However, I don't see any documentation to do the same.

Can someone please provide comment on it? Is it possible with this app, or the 4 points from documentation are outdated?
https://django-notification.readthedocs.org/en/latest/index.html#welcome-to-django-notification-s-documentation

Pass send_mail return values through backend.deliver

Problem:
backend.deliver returns True when backend.can_send, regardless of potential issues in, e.g., smtp backend
For example, if the SMTP connection fails, backend.deliver still returns True.

This means I can't detect and handle cases where an important notification is not sent.

Proposed Solution:
backend.deliver currently returns nothing, so could be adapted to pass along value from underlying backend (e.g., send_mail)
models.send_now (and other send functions) returns True or False. I'd recommend returning True only if notification was successfully sent by at least one backend.

Have not considered alternatives nor looked too deeply into the implications for other backend types. Wanted to ask if this is something you'd consider a pull-request for before going further?

emit_notices management command and send_all have several errors

I've just recently started experimenting with emit_notices in pinax-notifications and I have been facing several issues. I am unsure if I am running something incorrectly.

When I run emit_notices management command, I immediately receive the error :

  File "manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 364, in execute_from_command_line
    utility.execute()
  File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 356, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "C:\Python27\lib\site-packages\django\core\management\base.py", line 283, in run_from_argv
    self.execute(*args, **cmd_options)
  File "C:\Python27\lib\site-packages\django\core\management\base.py", line 330, in execute
    output = self.handle(*args, **options)
  File "C:\Python27\lib\site-packages\pinax\notifications\management\commands\emit_notices.py", line 14, in handle
    send_all(*args)
  File "C:\Python27\lib\site-packages\pinax\notifications\engine.py", line 41, in send_all
    lock = acquire_lock(*args)
  File "C:\Python27\lib\site-packages\pinax\notifications\engine.py", line 29, in acquire_lock
    lock.acquire(settings.PINAX_NOTIFICATIONS_LOCK_WAIT_TIMEOUT)
  File "C:\Python27\lib\site-packages\pinax\notifications\lockfile.py", line 354, in acquire
    self.attempt_acquire(self, timeout, end_time, wait)
TypeError: attempt_acquire() takes exactly 4 arguments (5 given)

This error is seems to be due to "self" being passed in to another class method when I believe "self" is passed in to all methods by default by the class so "self" gets passed twice.

If I remove "self" from being passed into "attempt_acquire" in lockfile.py, line 354, the lockfile gets stuck in the while loop in lockfile.py, line 353 and loops infinitely even after a lockfile is created.

while True:
    self.attempt_acquire(timeout, end_time, wait)

Note : I am using PINAX_NOTIFICATIONS_LOCK_WAIT_TIMEOUT = -1 (default). I have also tried setting it to 1, but the lock is never acquired either way.

And finally, I faced this issue as well.

Am I doing something wrong here? I am currently using Windows 10 with Python 2.7 but I have also tried with Linux machines and got the same results (I have not tried Python 3.x). Pinax packages have always been very solid for me so I am surprised about all the problems I am facing with emit_notices.

Any help is appreciated! Thank you.

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.