I'm trying to setup notifications on the django comments framework. I've gone through the documentation here -
https://docs.djangoproject.com/en/dev/ref/contrib/comments/moderation/#django.contrib.comments.moderation.CommentModerator
I've added all of the code into my noticeboard app which is where the comments are currently being posted. When posting a comment to the site it works fine. However when i click the 'enable comments' field which is meant to allow the notifications, i'm not receiving any emails.
**UPDATE:
Just to add the site has a built in mailer so it records all emails being sent out from the website and it's not picked up any of the comments. If i also untick the 'enable comments' box I get an error message like so - comment_will_be_posted receiver 'pre_save_moderation' killed the comment
So i know the functionality is working ok.
Here is the code I've got so far:
//SNIPPET OF MODELS
from django.contrib.comments.moderation import CommentModerator, moderator
class Notice(models.Model):
class Meta:
ordering = ['-date']
content_type = 'noticeboard'
title = models.CharField(max_length=255)
sector = models.ForeignKey(BusinessSector, verbose_name="Sector", related_name='notices')
date = models.DateTimeField(auto_now_add=True, verbose_name="Date posted")
copy = models.TextField()
owner = models.ForeignKey('auth.User', related_name='notices')
owner_company = models.ForeignKey('directory.Company', verbose_name='Company')
enable_comment = models.BooleanField()
class EntryModerator(CommentModerator):
email_notification = True
enable_field = 'enable_comment'
moderator.register(Notice, EntryModerator)
I've also uploaded the file 'comment_notification_email.txt' into templates/contact.
The above code has been included into an exisiting app called noticeboard as this is where the comments are being posted.
Feel free to ask any questions if you think something would be of use to you.
Am I missed anything!?
Thanks!
I had to add an If statement in the code to say if mailer was being used then send the email. Otherwise it wouldn't send the email.
if "mailer" in settings.INSTALLED_APPS:
from mailer import send_mail
else:
from django.core.mail import send_mail
Related
I have a model that holds emails of users who signed up for emails that notify about new articles on the site. Articles are added from the admin panel. I want to figure out how to trigger some function on object addition by admin.
MailingList model
class MailingList(models.Model):
email = models.CharField(max_length=50)
def __str__(self):
return 'email: ' + str(self.email)
Thank you!
Depending on your needs you can use or Django signals to do something after new article is added (post_save signal, for example). Or, if you'd like to do something exactly when new article is saved only from admin, you can override ModelAdmin.save_model.
I am currently integrating exchange server email to my application. I am able to retrieve attachments from my emails using exchangelib. I am trying to save the attachments into my Django model filefield. However, it is not working with different errors based on different solutions I tried. Any help is appreciated. Thank you. Below are some of my code:
models.py
class Attachments(models.Model):
name = models.CharField(max_length=255)
attachment = models.FileField(upload_to="attachments/")
views.py
for attachment in item.attachments:
if isinstance(attachment, FileAttachment):
attachmentlist.append(attachment.name)
saveattachments = Attachments(
name=attachment.name,
attachment=(attachment.content)
)
saveattachments.save()
Please look an following snippet and try to do same in you code
from django.core.files.base import ContentFile
...
saveattachments = Attachments(name=attachment.name)
saveattachments.attachment.save(attachment.name, ContentFile(attachment.content))
saveattachments.save()
I'm looking at implementing user authentication to a Django project. I'm reading through the documentation. It mostly seems straightforward, but there's one thing that I don't understand.
Apparently the authentication includes eight views:
accounts/login/ [name='login']
accounts/logout/ [name='logout']
accounts/password_change/ [name='password_change']
accounts/password_change/done/ [name='password_change_done']
accounts/password_reset/ [name='password_reset']
accounts/password_reset/done/ [name='password_reset_done']
accounts/reset/<uidb64>/<token>/ [name='password_reset_confirm']
accounts/reset/done/ [name='password_reset_complete']
When implementing a password reset I assume that what I want to do implement accounts/password_reset/, which forwards the user an email. Then, I need to implement accounts/reset/<uidb64>/<token>/, which is where the user is directed to via the email. What I'm not clear on is what that should do when the user has updated their password successfully.
What's the difference between accounts/reset/done/ (or password_resest_complete) and accounts/password_reset/done/ (or password_reset_done)?
password_reset_done shows a success message when email is sent (after email is entered in password_reset). password_reset_complete shows a success message when password is successfully changed.
If you look at the source code for these views, there is a comment explaining the process. Lines 237 - 242:
# 4 views for password reset:
# - password_reset sends the mail
# - password_reset_done shows a success message for the above
# - password_reset_confirm checks the link the user clicked and
# prompts for a new password
# - password_reset_complete shows a success message for the above
Good question. This is how they look like:
class PasswordResetCompleteView(PasswordContextMixin, TemplateView):
template_name = 'registration/password_reset_complete.html'
title = _('Password reset complete')
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['login_url'] = resolve_url(settings.LOGIN_URL)
return context
class PasswordResetDoneView(PasswordContextMixin, TemplateView):
template_name = 'registration/password_reset_done.html'
title = _('Password reset sent')
The main difference is that PasswordResetCompleteView passes the LOGIN_URL to your template context.
Maybe I am not asking the right question in the search area, but I can't find an answer for this. I am pretty sure that many people have this use case, but as a beginner in Django + Python, I need to ask it.
I have user that fills up a form and the data is stored in the database. Basically this form asks for an access to a Database and after the form is submitted I want my program to send an email to the user's manager and to the DBA to APPROVE or DENY it. Very simple, right?
My idea is that in this e-mail I send two URL's, one for approving and one for denying the request. When the URL the is clicked I send a response to the server with an update in the manager_approval field.
Has anyone implemented this solution, or could point me to something that could help me?
I am doing everything using Django + Python.
Regards,
Marcos Freccia
Basically this technique used in email verification. This is where you should look into.
Let's say you have model, named request, which has field like username to identify the person who requested access, database name, well, everything. But it will also have two "password-like" fields which will be used to determine if request was declined or not.
class Request(models.Model):
user = models.ForeignKey ...
databasename =
date =
...
access_granted = models.BooleanField(default=False)
deny_token = models.CharField()
allow_token = models.CharField()
The point is to generate those tokens on saving request in the View:
if request.method == POST:
form = RequestForm(request.POST)
if form.is_valid():
data['user'] = form.cleaned_data['user'])
data['databasename'] = form.cleaned_data['databasename'])
...
data['access_token'] = GENERATE_USING_HASH_FUNCTION()
data['deny_token'] = GENERATE_USING_HASH_FUNCTION()
form.save(data)
Then you can use module EmailMultiAlternatives to send html email like so:
subject, from_email, to = 'Request', 'admin#example.com', form.cleaned_data['manager_email']
html_content = render_to_string(HTML_TEMPLATE, CONTEXT) # Just as any regular templates
text_content = strip_tags(html_content)
msg = EmailMultiAlternatives(subject, text_content, from_email, [to], reply_to=["admin#example.com"])
msg.attach_alternative(html_content, "text/html")
msg.send()
And inside that template you construct reverse url:
{% url 'app:grant_access' allow_token=token %} # "token" you get from context
{% url 'app:deny_access' deny_token=token %} # will become example.com/deny_access/7ea3c95, where 7ea3c95 is token
Then add lines to urls.py of your app like that:
url(r'^allow_access/(?P<allow_token>[0-9]+)$', CheckAcessView.as_view(), name="app:grant_access"),
url(r'^deny_access/(?P<deny_token>[0-9]+)$', CheckAcessView.as_view(), name="app:deny_access"),]
Then create CheckAcessView view. Where you access request stored in your database and check if, for example, parameter of url "allow_token" is equal stored allow_token. If so, change request status to allowed.
I have some Django app, in which you can add tagged objects. There's sth like
auto_tags = TagAutocompleteField(_(u'Tags'), default='', blank=True)
in models.py file.
How can I create a newsletter which will send an e-mail notification when a new object tagged with one of subscribed tags is created?
Thanks in advance :D
I would do this using django's built-in signals. You can register a function to be called when an object is saved, and then send emails to subscibers in that function. The code would looks something like this
from django.db.signals import post_save
from my_app.models import MyModel
def my_function(sender, instance, created, *args, **kwargs):
if not created:
return # break if it's being edited
# check tags for subscribers
# send email to subscribers
post_save.connect(my_function, sender=MyModel)