Skip to content

Instantly share code, notes, and snippets.

@SalahAdDin
Created October 20, 2014 19:49
Show Gist options
  • Save SalahAdDin/fcbe0bdccafda28477ea to your computer and use it in GitHub Desktop.
Save SalahAdDin/fcbe0bdccafda28477ea to your computer and use it in GitHub Desktop.
Aquí está el modelo de mi app.
from django.core.mail import send_mail, mail_admins
from django.db import models
from django.template.defaultfilters import slugify
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
from ckeditor.fields import RichTextField
from subtopic.models import Subtopic
from topic.models import Topic
from keywords.models import KeyWord
#Global Vars
# Create your models here.
class New(models.Model):
author = models.ForeignKey(User, verbose_name='Autor', related_name='news')
content = RichTextField(verbose_name='Contenido')
created_date = models.DateTimeField(auto_now_add=True, verbose_name='Fecha y Hora')
is_published = models.BooleanField(verbose_name='Publicada', default=False,) #Nueva, para verificar si se publica o no
keywords = models.ManyToManyField(KeyWord, blank=True, verbose_name='Palabras Clave', related_name='news')
place = models.CharField(max_length=255, verbose_name='Lugar')
source = models.URLField(verbose_name='Fuente', blank=True)
subtopic = models.ForeignKey(Subtopic, verbose_name='Subtema', related_name='news') #Filtramos por Opinion para sacar todas las columnas
times_viewed = models.PositiveIntegerField(default=0, editable=False, verbose_name='Veces Vista' )
title = models.CharField(verbose_name='Título', max_length=255, unique=True)
slug = models.SlugField(verbose_name='Slug', max_length=100, unique=True)
topic = models.ForeignKey(Topic, verbose_name='Tema', related_name='news', )
class Meta:
ordering = ['-created_date']
verbose_name_plural = 'Noticias'
verbose_name = 'Noticia'
permissions = (
("can_publish", "Puede publicar noticias"), #Can publish news
)
#@models.permalink
#def get_absolute_url(self):
# return ('news.views.New_view', None, {'year': self.dateTime.year,
# 'month': self.dateTime.strftime('%m'),
# 'day': self.dateTime.strftime('%d'),
# 'slug': self.slug})
def first_image(self):
return self.images.first() # Siendo images el related_name en Image
def first_video(self):
return self.videos #Devuelve el video de la imagen
def get_absolute_url(self):
return reverse ('NewsDefaultView', args = [str(self.created_date.strftime("%Y")), str(self.created_date.strftime("%m")), str(self.created_date.strftime("%d")), str(self.slug)])
def get_all_keys(self):
keys_list = self.keywords.values_list('name', flat=True)
return str(keys_list).strip("'[]'").replace("'",'')
#def is_published(self): devuelve si la noticia ha sido pulicada para que salga en la lista de noticias
def __str__(self):
return self.title
def save(self): #Definir metodo para guardar, validar y otros metodos del Slug
super(New, self).save() #Solo con este me funciona correctamente
if not self.id:
self.slug = slugify(self.title)
super(New, self).save()
from django.db.models.signals import post_save
from django.template.loader import get_template
from django.template import Context
admin = User.objects.get(is_superuser=True).get_full_name()
def send_created_notification(sender, instance, created, **kwargs):
admin = User.objects.get(is_superuser=True).get_full_name()
#Bueno, hay dos problemas aquí,
# aquí obtenemos el nombre directamente, luego, a que superusiarios enviará el mail?
# Ordenamos alfabéticamente? le enviamos un user personalizado y creamos un mètodo que haga esta misma opción?
# Creo que esto lo puede hacer con x número de destinatarios, el problema es que el correo llegue con el nombre del destinatario
if created:
return mail_admins('Nueva noticia espera por edición',
get_template('email_new_news_template.html').render(
Context({
'user': admin,
'author': instance.author,
'title': instance.title,
'date': instance.created_date
})
),)
else:
pass
post_save.connect(send_created_notification, sender=New) #Reactivar en servidor
def send_published_notification(sender, instance, created, **kwargs):
if instance.is_published:
return send_mail('Tu noticia fue publicada!',
get_template('email_publish_news_template.html').render(
Context({
'author': instance.author,
'title': instance.title,
'date': instance.created_date
})
),
'[email protected]',[instance.author.email],fail_silently = True)
else:
pass
post_save.connect(send_published_notification, sender=New)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment