some work on questions
[prawokultury.git] / questions / models.py
1 # -*- coding: utf-8
2 from datetime import datetime
3 from django.contrib.sites.models import Site
4 from django.core.mail import EmailMultiAlternatives
5 from django.db import models
6 from django.template import loader, Context
7 from django.utils.translation import ugettext_lazy as _
8 from markupfield.fields import MarkupField
9
10 class Question(models.Model):
11     email = models.EmailField(_('contact e-mail'), null=True, blank=True)
12     question = models.TextField(_('question'), db_index=True)
13     created_at = models.DateTimeField(_('created at'), auto_now_add=True)
14     approved = models.BooleanField(_('approved'), default=False)
15     edited_question = models.TextField(_('edited question'), db_index=True, null=True, blank=True,
16             help_text=_("Leave empty if question doesn't need editing."))
17     answer = MarkupField(_('answer'), markup_type='textile_pl', blank=True,
18             help_text=_('Use <a href="http://textile.thresholdstate.com/">Textile</a> syntax.'))
19     answered = models.BooleanField(_('answered'), db_index=True, default=False,
20             help_text=_('Check to send the answer to user.'))
21     answered_at = models.DateTimeField(_('answered at'), null=True, blank=True, db_index=True)
22     published = models.BooleanField(_('published'), db_index=True, default=False,
23         help_text=_('Check to display answered question on site.'))
24     published_at = models.DateTimeField(_('published at'), null=True, blank=True, db_index=True)
25
26     class Meta:
27         ordering = ['-created_at']
28
29     def __unicode__(self):
30         return self.edited_question or self.question
31
32     @models.permalink
33     def get_absolute_url(self):
34         return ('questions_question', (self.pk,))
35
36     def notify_author(self):
37         if not self.email:
38             return
39         site = Site.objects.get_current()
40         context = Context({
41                 'question': self,
42                 'site': site,
43             })
44         text_content = loader.get_template('questions/answered_mail.txt'
45             ).render(context)
46         html_content = loader.get_template('questions/answered_mail.html'
47             ).render(context)
48         msg = EmailMultiAlternatives(
49             u'Odpowiedź na Twoje pytanie w serwisie %s.' % site.domain,
50             text_content, settings.SERVER_EMAIL, [self.email])
51         msg.attach_alternative(html_content, "text/html")
52         msg.send()
53
54     def save(self, *args, **kwargs):
55         now = datetime.now()
56         if self.answered and not self.answered_at:
57             self.notify_author()
58             self.answered_at = now
59         if self.published and not self.published_at:
60             self.published_at = now
61         super(Question, self).save(*args, **kwargs)