IPN is not received anymore - django

I have a problem with my IPN sandbox PayPal. A few days ago it sent the ipn after a test-purchase but since a few days ago it doesn’t sent them anymore. What can I do to fix that error?
signals.py
from django.shortcuts import get_object_or_404
from .models import CourierPayment
from paypal.standard.ipn.signals import valid_ipn_received
from django.dispatch import receiver
#receiver(valid_ipn_received)
def payment_notification(sender, **kwargs):
ipn = sender
if ipn.payment_status == 'Completed':
# payment was successful
payment = get_object_or_404(CourierPayment, id=ipn.invoice)
if payment.price == ipn.mc_gross:
# mark the order as paid
payment.paid = True
payment.save()
apps.py
from django.apps import AppConfig
class CourierConfig(AppConfig):
name = 'courier'
def ready(self):
# import signal handlers
import courier.signals
init.py
default_app_config = 'courier.apps.CourierConfig'

Related

ImportError: cannot import name 'Users' from partially initialized module tasks file

ImportError: cannot import name 'Users' from partially initialized module 'users.models
from .models import Users
from celery import shared_task
from django.core.mail import send_mail
from server import settings
#shared_task()
def send_mail_task(user_id):
user = Users.objects.get(id=user_id)
send_mail(
subject='Congratulations!',
message=f'Congratulations {user.username}',
from_email=settings.EMAIL_HOST_USER,
recipient_list=["waelelsafty07#gmail.com", ],
fail_silently=False,
)
print('Email sent successfully')
return f'Email sent successfully'
checking installing celery
I import my model in this way:
model = apps.get_model(app_label='users', model_name='users')
when the users is name the folder
could you post your working directory so i can see where is the files are
if you didnt customize the user model then use
from django.contrib.auth.models import User

Catch post_save signal

Django 3.0.5.
apps.py
from django.apps import AppConfig
from django.db.models.signals import post_save
from django.dispatch import receiver
class NewsConfig(AppConfig):
name = 'news'
def ready(self):
from .models import News # Breakpoint 0
#receiver(post_save, sender=News)
def handle_news_save(sender, **kwargs):
print("Working")
a = 0 # Breakpoint 1
models.py
class News(models.Model):
news_text = models.TextField()
settings.py
INSTALLED_APPS = [
...
'news.apps.NewsConfig',
]
The problem
At Breakpoint 0 the interpreter stops when I run the application. That is at the next line Django gets to know that I'm catching the signal.
But when I save an instance of News in admin site, at Breakpoint 1 the interpreter doesn't stop. And, of course, no printing happens.
Could you help me catch the signal?
Ok i tried it out and played with signals a little, here's what i found out:
As the question state this way of defining does not work it seems to not register the signal correctly. I have no clue why it doesn't.
I guess the convention about signals would be anyways to move them to a signals.py file and then in the apps.py you only import them.
signals.py:
from .models import News # Breakpoint 0
from django.db.models.signals import post_save
from django.dispatch import receiver
#receiver(post_save, sender=News)
def handle_news_save(sender, **kwargs):
print("Working")
a = 0 # Breakpoint 1
apps.py:
from django.apps import AppConfig
from django.db.models.signals import post_save
from django.dispatch import receiver
class PollsConfig(AppConfig):
name = 'polls'
def ready(self):
import polls.signals
and then it works

Sending Email With Celery Using Django Default Email Backend

I am trying to send confirmation email to my registered user using Django and Celery. I am using RabbitMQ as the Broker. Whenever I'm executing the code, the celery log shows it is receiving the task and executing successfully, But I am not receiving any emails.
tasks.py
from celery.task import Task
from django.core.mail import send_mail
from django.template import loader
from django.utils.html import strip_tags
from config.celery import app
from config.settings import default
class SendConfirmationEmail(Task):
def __init__(self, *args, **kwargs):
self.user_name = kwargs.get('username')
self.user_id = kwargs.get('id')
self.user_hash = kwargs.get('hash')
self.user_email = kwargs.get('email')
def send_email(self):
confirm_mail = loader.render_to_string('mail/confirmation.html',
{'user': self.user_name, 'id': self.user_id,
'hash': self.user_hash,
'domain': default.SITE_URL})
text_email = strip_tags(confirm_mail)
send_mail(
subject='Confirm Your E-mail',
message=text_email,
from_email='no-reply#mysite.com',
recipient_list=[self.user_email],
fail_silently=False,
html_message=confirm_mail
)
def run(self, *args, **kwargs):
self.send_email()
app.register_task(SendConfirmationEmail())
signals.py
from django.db.models.signals import post_save
from django.dispatch import receiver
from apps.siteuser.models import User
from apps.siteuser.tasks import SendConfirmationEmail
#receiver(post_save, sender=User)
def create_employee_details(sender, instance, created, **kwargs):
if created:
task = SendConfirmationEmail(username=instance.first_name, id=instance.id, hash=instance.hash,
email=instance.email)
task.delay()
settings for Email & Celery:
CELERY_BROKER_URL = 'amqp://username:password#localhost:5672/vhost'
EMAIL_HOST = 'smtp.mailtrap.io'
EMAIL_HOST_USER = MY_USERNAME
EMAIL_HOST_PASSWORD = MY_PASSWORD
EMAIL_PORT = 2525
Celery log:
[2018-05-09 11:50:41,191: INFO/MainProcess] Received task: apps.user.tasks.SendConfirmationEmail[e63c0f5f-7b81-4065-85c1-9ef87acc792a]
[2018-05-09 11:50:41,197: INFO/ForkPoolWorker-1] Task apps.user.tasks.SendConfirmationEmail[e63c0f5f-7b81-4065-85c1-9ef87acc792a] succeeded in 0.004487647999667388s: None
NOTE: I have sent mail without Celery and it was working fine. But The Problem started after trying with Celery.I am using Mailtrap for development purpose.
This is how I generally call a celery task
Task.py
from celery import shared_task
#shared_task
def task1(*args,**kwargs):
pass
Caller.py
from task import task1
task1.delay(a,b,c...)
Is celery discovery configured correctly?

Emails won't send after upgrading from Django 1.6.x to Django > 1.7.x

I am currently using Django Allauth and a modified version of Django Invitations (https://github.com/bee-keeper/django-invitations). The only thing added is a field for which group to add the user to, and the application works perfectly when Django 1.6.x is being used. I would like to upgrade to Django 1.7.x or 1.8 but this somehow breaks the emailing feature.
The specific piece of code is here:
'import datetime
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.utils import timezone
from django.utils.crypto import get_random_string
from django.utils.encoding import python_2_unicode_compatible
from django.contrib.sites.models import Site
from django.core.urlresolvers import reverse
from allauth.account.adapter import DefaultAccountAdapter
from allauth.account.adapter import get_adapter
from .managers import InvitationManager
from . import app_settings
from . import signals
...(other code)
def send_invitation(self, request, **kwargs):
current_site = (kwargs['site'] if 'site' in kwargs
else Site.objects.get_current())
invite_url = reverse('invitations:accept-invite',
args=[self.key])
invite_url = request.build_absolute_uri(invite_url)
ctx = {
'invite_url': invite_url,
'current_site': current_site,
'email': self.email,
'key': self.key,
}
email_template = 'invitations/email/email_invite'
get_adapter().send_mail(email_template,
self.email,
ctx)
self.sent = timezone.now()
self.save()
signals.invite_url_sent.send(
sender=self.__class__,
instance=self,
invite_url_sent=invite_url)'
found here (https://github.com/bee-keeper/django-invitations/blob/master/invitations/models.py)
This also references the code from allauth here:
from __future__ import unicode_literals import re
import warnings
import json
from django.conf import settings
from django.http import HttpResponse
from django.template.loader import render_to_string
from django.template import TemplateDoesNotExist
from django.contrib.sites.models import Site
from django.core.mail import EmailMultiAlternatives, EmailMessage
from django.utils.translation import ugettext_lazy as _
from django import forms
from django.contrib import messages
try:
from django.utils.encoding import force_text
except ImportError:
from django.utils.encoding import force_unicode as force_text
from ..utils import (import_attribute, get_user_model,
generate_unique_username,
resolve_url)
from . import app_settings
USERNAME_REGEX = re.compile(r'^[\w.#+-]+$', re.UNICODE)
........ (other code)
def render_mail(self, template_prefix, email, context):
"""
Renders an e-mail to `email`. `template_prefix` identifies the
e-mail that is to be sent, e.g. "account/email/email_confirmation"
"""
subject = render_to_string('{0}_subject.txt'.format(template_prefix),
context)
# remove superfluous line breaks
subject = " ".join(subject.splitlines()).strip()
subject = self.format_email_subject(subject)
bodies = {}
for ext in ['html', 'txt']:
try:
template_name = '{0}_message.{1}'.format(template_prefix, ext)
bodies[ext] = render_to_string(template_name,
context).strip()
except TemplateDoesNotExist:
if ext == 'txt' and not bodies:
# We need at least one body
raise
if 'txt' in bodies:
msg = EmailMultiAlternatives(subject,
bodies['txt'],
settings.DEFAULT_FROM_EMAIL,
[email])
if 'html' in bodies:
msg.attach_alternative(bodies['html'], 'text/html')
else:
msg = EmailMessage(subject,
bodies['html'],
settings.DEFAULT_FROM_EMAIL,
[email])
msg.content_subtype = 'html' # Main content is now text/html
return msg
def send_mail(self, template_prefix, email, context):
msg = self.render_mail(template_prefix, email, context)
msg.send()'
found at (allauth/account/adapter.py)
The form always saves an invitation element into the database but breaks at the sending email line. (all infor stored is correct, so that isn't breaking it). If the email is removed, all code afterwards runs fine. I have even tried to just send a basic email like such in place:
from django.core.mail import EmailMessage
msg = EmailMessage("TEST", "HELLO", my_email, [some_email])
msg.send()
but this, too does not send emails.
I am hoping this is super simple, but any help would be appreciated.
I had the same problem, the execution just hung when running this code in a django shell (Django 1.7):
from django.core.mail import send_mail
send_mail('Subject here', 'Here is the message.', 'from#example.com',
['to#example.com'], fail_silently=False)
Following the Django docs on email settings, I used in settings.py:
EMAIL_USE_TLS = False
EMAIL_USE_SSL = True
EMAIL_PORT = 465
This worked.

How to create a django-allauth regular and social account for testing purposes?

I managed to create a regular user as happens when signing in with Django-allauth.
I've been trying to do the same for a social account (Github) but I am really struggling. I assume there must be people out here that had to make a social account for testing purposes. Could anyone show how they did that?
Also, if you know a better way to create a regular user this is highly appreciated.
The following snippet from the django-allauth tests shows how to do this:
from allauth.account import app_settings as account_settings
from allauth.account.models import EmailAddress
from allauth.account.utils import user_email
from allauth.socialaccount.helpers import complete_social_login
from allauth.socialaccount.models import SocialApp, SocialAccount, SocialLogin
from allauth.utils import get_user_model
from django.contrib.auth.models import AnonymousUser
from django.contrib.auth.models import User
from django.contrib.messages.middleware import MessageMiddleware
from django.contrib.sessions.middleware import SessionMiddleware
from django.test import TestCase
from django.test.client import Client
from django.test.client import RequestFactory
from django.test.utils import override_settings
class SocialAccountTests(TestCase):
#override_settings(
SOCIALACCOUNT_AUTO_SIGNUP=True,
ACCOUNT_SIGNUP_FORM_CLASS=None,
ACCOUNT_EMAIL_VERIFICATION=account_settings.EmailVerificationMethod.NONE # noqa
)
def test_email_address_created(self):
factory = RequestFactory()
request = factory.get('/accounts/login/callback/')
request.user = AnonymousUser()
SessionMiddleware().process_request(request)
MessageMiddleware().process_request(request)
User = get_user_model()
user = User()
setattr(user, account_settings.USER_MODEL_USERNAME_FIELD, 'test')
setattr(user, account_settings.USER_MODEL_EMAIL_FIELD, 'test#test.com')
account = SocialAccount(user=user, provider='openid', uid='123')
sociallogin = SocialLogin(account)
complete_social_login(request, sociallogin)
user = User.objects.get(
**{account_settings.USER_MODEL_USERNAME_FIELD: 'test'}
)
self.assertTrue(
SocialAccount.objects.filter(user=user, uid=account.uid).exists()
)
self.assertTrue(
EmailAddress.objects.filter(user=user,
email=user_email(user)).exists()
)