1
# -*- coding: utf-8 -*-
4
from django import forms
5
from django.contrib.contenttypes.models import ContentType
6
from django.utils.translation import ugettext_lazy as _
8
from wiki.models import Article
9
from wiki.models import ChangeSet
10
from settings import WIKI_WORD_RE
12
from notification import models as notification
17
wikiword_pattern = re.compile('^' + WIKI_WORD_RE + '$')
20
class ArticleForm(forms.ModelForm):
22
summary = forms.CharField(widget=forms.Textarea)
24
comment = forms.CharField(required=False)
26
content_type = forms.ModelChoiceField(
27
queryset=ContentType.objects.all(),
29
widget=forms.HiddenInput)
30
object_id = forms.IntegerField(required=False,
31
widget=forms.HiddenInput)
33
action = forms.CharField(widget=forms.HiddenInput)
37
exclude = ('creator', 'group', 'created_at', 'last_update')
39
def clean_title(self):
40
"""Check for some errors regarding the title:
42
1. Check for bad characters
43
2. Check for already used titles
45
Immediately trying to change the title of a new article to an existing title
46
is handled on the database level.
50
title = self.cleaned_data['title']
51
if not wikiword_pattern.match(title):
52
raise forms.ValidationError(
53
_('Only alphanumeric characters, blank spaces and the underscore are allowed in a title.'))
55
# 'self.initial' contains the prefilled values of the form
56
pre_title = self.initial.get('title', None)
57
if pre_title != title or not pre_title:
58
# Check if the new name has been used already
59
cs = ChangeSet.objects.filter(old_title=title)
61
raise forms.ValidationError(
62
_('The title %(title)s is already in use, maybe an other article used to have this name.'), params={'title': title},)
64
# title not changed, no errors
68
super(ArticleForm, self).clean()
71
if self.cleaned_data['action'] == 'create':
73
kw['title'] = self.cleaned_data['title']
74
kw['content_type'] = self.cleaned_data['content_type']
75
kw['object_id'] = self.cleaned_data['object_id']
77
pass # some error in this fields
79
return self.cleaned_data
81
def cache_old_content(self):
82
if self.instance.id is None:
83
self.old_title = self.old_content = self.old_markup = ''
86
self.old_title = self.instance.title
87
self.old_content = self.instance.content
88
self.old_markup = self.instance.markup
91
def save(self, *args, **kwargs):
93
comment = self.cleaned_data['comment']
95
# 2 - Save the Article
96
article = super(ArticleForm, self).save(*args, **kwargs)
98
# 3 - Set creator and group
99
editor = getattr(self, 'editor', None)
100
group = getattr(self, 'group', None)
102
if editor is not None:
103
article.creator = editor
104
article.group = group
105
article.save(*args, **kwargs)
107
notification.observe(article, editor, 'wiki_observed_article_changed')
109
# 4 - Create new revision
110
changeset = article.new_revision(
111
self.old_content, self.old_title, self.old_markup,
114
return article, changeset