""" Created on 04.10.2011 @author: christian """ from django import forms from django.template.defaultfilters import slugify from django.utils.translation import gettext as _ from . import models class ArticleForm(forms.ModelForm): """ Django form for adding and editing news articles. """ error_css_class = 'error' required_css_class = 'required' class Meta(object): """Only the content should be visible, hide the meta data.""" fields = ( 'headline_de', 'content_de', 'headline_en', 'content_en', 'category', 'image' ) model = models.Article def save(self, commit=True): """ slugify the german headline and set is as slug before saving. :param commit: Save this form's self.instance object if True :return: self.instance object.""" self.instance.slug = slugify(self.instance.headline_de)[:50] return super(ArticleForm, self).save(commit=commit) class PageForm(forms.ModelForm): """ Django form for adding and editing static pages.""" error_css_class = 'error' required_css_class = 'required' content_type = forms.ChoiceField( choices=models.CONTENT_CHOICES, widget=forms.RadioSelect ) class Meta(object): """Only the content should be visible, hide the meta data.""" exclude = ('position',) model = models.Page def clean(self): """Check if a file has been uploaded if the page is marked as PDF.""" cleaned_data = super(PageForm, self).clean() content_type = cleaned_data.get("content_type") if content_type == "2" and not cleaned_data.get("pdf_de"): msg = _('Please upload a PDF-File to this PDF-Page.') self._errors["content_type"] = self.error_class([msg]) self._errors["pdf_de"] = self.error_class([msg]) # These fields are no longer valid. Remove them from the # cleaned data. del cleaned_data["content_type"] del cleaned_data["pdf_de"] # Always return the full collection of cleaned data. return cleaned_data