class EditPageForm(forms.Form): name = forms.CharField(label=_("PAGE_NAME")) content = SanitizedCharField( label=_("CONTENT"), widget=forms.Textarea, max_length=50000, allowed_tags=SANITIZER_ALLOWED_TAGS, allowed_attributes=SANITIZER_ALLOWED_ATTRIBUTES, strip=False) order = forms.IntegerField(label=_("ORDER"), required=False) def __init__(self, *args, **kwargs): self.page = kwargs.pop("page") super(EditPageForm, self).__init__(*args, **kwargs) self.fields["name"].initial = self.page.name self.fields["content"].initial = self.page.content self.fields["order"].initial = self.page.order def clean(self): cleaned_data = super(EditPageForm, self).clean() name = cleaned_data.get("name").strip() link = uslugify(name) if len(link) < 3: raise forms.ValidationError(_("ERROR_NAME_TO_SHORT")) if link in _RESERVED_NAMES: raise forms.ValidationError(_("ERROR_NAME_RESERVED")) if len(Page.objects.filter(name=name, team=self.page.team)) > 1: raise forms.ValidationError(_("ERROR_NAME_USED")) if len(Page.objects.filter(link=link, team=self.page.team)) > 1: raise forms.ValidationError(_("ERROR_NAME_USED")) return cleaned_data
class UserProfileForm(forms.ModelForm): class Meta: model = UserProfile exclude = ('user','favourite_questions','favourite_exams',) first_name = forms.CharField(max_length=30) last_name = forms.CharField(max_length=30) email = forms.EmailField() language = forms.ChoiceField(choices=[(x,y) for y,x in settings.GLOBAL_SETTINGS['NUMBAS_LOCALES']]) bio = SanitizedCharField( widget=Textarea, allowed_tags=settings.SANITIZER_ALLOWED_TAGS, allowed_attributes=settings.SANITIZER_ALLOWED_ATTRIBUTES, required=False ) def __init__(self, *args, **kw): super(UserProfileForm, self).__init__(*args, **kw) self.profile = self.get_profile() self.fields['language'].initial = self.profile.language self.fields['bio'].initial = self.profile.bio def get_profile(self): return UserProfile.objects.get(user=self.instance) def save(self,*args,**kwargs): self.profile.language = self.cleaned_data.get('language') self.profile.bio = self.cleaned_data.get('bio') self.profile = self.profile.save() super(UserProfileForm,self).save(self,*args,**kwargs)
class Create(forms.Form): name = forms.CharField(label=_("TITLE")) content = SanitizedCharField( label=_("CONTENT"), widget=forms.Textarea, max_length=50000, allowed_tags=SANITIZER_ALLOWED_TAGS, allowed_attributes=SANITIZER_ALLOWED_ATTRIBUTES, strip=False)
class UserProfileForm(forms.ModelForm): class Meta: model = UserProfile fields = ('first_name', 'last_name', 'email', 'bio', 'language', 'avatar','wrap_lines','mathjax_url') widgets = { 'mathjax_url': forms.TextInput(attrs={'class':'form-control','placeholder':settings.MATHJAX_URL}) } help_texts = { 'mathjax_url': 'This will be used in all questions and exams you compile. Leave blank to use the default.' } first_name = forms.CharField(max_length=30, widget=forms.TextInput(attrs={'class':'form-control'})) last_name = forms.CharField(max_length=30, widget=forms.TextInput(attrs={'class':'form-control'})) email = forms.EmailField(widget=forms.TextInput(attrs={'class':'form-control'})) language = forms.ChoiceField(choices=[(x, y) for y, x in settings.GLOBAL_SETTINGS['NUMBAS_LOCALES']], widget=forms.Select(attrs={'class':'form-control'})) bio = SanitizedCharField( widget=Textarea, allowed_tags=settings.SANITIZER_ALLOWED_TAGS, allowed_attributes=settings.SANITIZER_ALLOWED_ATTRIBUTES, required=False ) def clean_mathjax_url(self): url = self.cleaned_data['mathjax_url'] bits = urlparse(url) if bits.scheme=='http': raise forms.ValidationError("Loading MathJax over HTTP can cause problems when the exam is loaded over HTTPS. If you're absolutely sure you want to do this, use // instead of http://") path = re.sub(r'/(MathJax.js)?$','',bits.path) return urlunparse((bits.scheme,bits.netloc,path,'','','')) def __init__(self, *args, **kw): super(UserProfileForm, self).__init__(*args, **kw) self.profile = self.get_profile() self.fields['language'].initial = self.profile.language self.fields['bio'].initial = self.profile.bio self.fields['wrap_lines'].initial = self.profile.wrap_lines self.fields['mathjax_url'].initial = self.profile.mathjax_url def get_profile(self): return UserProfile.objects.get(user=self.instance) def save(self, *args, **kwargs): self.profile.language = self.cleaned_data.get('language') self.profile.bio = self.cleaned_data.get('bio') self.profile.wrap_lines = self.cleaned_data.get('wrap_lines') self.profile.mathjax_url = self.cleaned_data.get('mathjax_url') if self.cleaned_data.get('avatar'): self.profile.avatar = self.cleaned_data.get('avatar') self.profile = self.profile.save() super(UserProfileForm, self).save(self, *args, **kwargs)
class Edit(forms.Form): name = forms.CharField(label=_("TITLE")) content = SanitizedCharField( label=_("CONTENT"), widget=forms.Textarea, max_length=50000, allowed_tags=SANITIZER_ALLOWED_TAGS, allowed_attributes=SANITIZER_ALLOWED_ATTRIBUTES, strip=False) def __init__(self, *args, **kwargs): blog = kwargs.pop("blog") super(Edit, self).__init__(*args, **kwargs) self.fields["name"].initial = blog.name self.fields["content"].initial = blog.content
class EventForm(CrispyFormMixin): description = SanitizedCharField( allowed_tags=settings.ALLOWED_HTML_TAGS_INPUT, allowed_attributes=settings.ALLOWED_HTML_ATTRIBUTES_INPUT, strip=False, widget=SummernoteInplaceWidget()) start_at = forms.DateTimeField( required=True, input_formats=['%d/%m/%Y %H:%M:%S'], label=_('Comienza'), widget=DateTimePicker(options={"format": "DD/MM/YYYY HH:ss:mm"})) end_at = forms.DateTimeField( required=True, input_formats=['%d/%m/%Y %H:%M:%S'], label=_('Finaliza'), widget=DateTimePicker(options={"format": "DD/MM/YYYY HH:ss:mm"})) def get_crispy_fields(self): return self.Meta.fields class Meta: model = Event fields = ('name', 'description', 'place', 'address', 'slug', 'url', 'start_at', 'end_at', 'registration_enabled', 'has_sponsors') crispy_fields = fields help_texts = { 'registration_enabled': REGISTRATION_ENABLED_HELP_TEXT, 'has_sponsors': HAS_SPONSORS_HELP_TEXT, } def clean(self): cleaned_data = super(EventForm, self).clean() start_at = cleaned_data.get('start_at') end_at = cleaned_data.get('end_at') if start_at is not None and end_at is not None: if start_at > end_at: msg = 'La fecha de inicio es menor a la fecha de finalizacion' self._errors['start_at'] = [_(msg)] self._errors['end_at'] = [_(msg)] return cleaned_data def save(self, *args, **kwargs): super(EventForm, self).save(*args, **kwargs) self.instance.save()
class Blog(forms.ModelForm): post_tittle = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'class': 'form-control', 'pattern': '.{10,}'}), required=True) post_content = SanitizedCharField(label='content', allowed_tags=['b', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'i'], max_length=2000, required=True, widget=forms.Textarea(attrs={'class': 'form-control', 'placeholder': 'content', 'min_length': '10'}), help_text='Write here your message!' ) class Meta: model = Post fields = ["post_tittle", "post_content"] def clean(self): super().clean() title = self.cleaned_data.get('post_tittle') body = self.cleaned_data.get('post_content') if title and body and len(title) > len(body): raise forms.ValidationError("body should be longer than title")
class JobForm(forms.ModelForm): """A PyAr Jobs form.""" description = SanitizedCharField( allowed_tags=settings.ALLOWED_HTML_TAGS_INPUT, allowed_attributes=settings.ALLOWED_HTML_ATTRIBUTES_INPUT, strip=False, widget=SummernoteInplaceWidget()) def __init__(self, *args, **kwargs): super(JobForm, self).__init__(*args, **kwargs) company_help_text = ''.join( ('Opcionalmente elija la empresa que ofrece el puesto. ', 'Si la empresa no aparece en el listado, puede registrarla ', 'haciendo click {0}'.format('<a href="{0}">aquí</a>').format( reverse('companies:add')))) title_help_text = ''.join( ('Título del empleo, por ejemplo: {0}'.format( choice([ 'Backend Developer', 'Django Developer', 'Frontend Developer', 'Senior Django Developer', 'Full Stack Python Developer', ])))) tags_help_text = ''.join( ('Agregue algunos tags / etiquetas ', 'que esten relacionadas con el puesto de trabajo. ' 'Los tags deben estar separados por comas, por ejemplo: ', 'Django, Python, MySQL, Linux')) seniority_help_text = ''.join( ('Opcionalmente puede especificar la experiencia requerida ', 'para el puesto.')) remote_work_help_text = ''.join( ('Se permite la modalidad de trabajo desde casa (homeworking).')) self.fields['title'].label = 'Título de la oferta' self.fields['tags'].label = 'Etiquetas / Tags / Tecnologías' self.fields['tags'].required = False self.fields['title'].help_text = title_help_text self.fields['tags'].help_text = tags_help_text self.fields['seniority'].help_text = seniority_help_text self.fields['company'].help_text = company_help_text self.fields['remote_work'].help_text = remote_work_help_text self.fields['description'].label = 'Descripción' self.helper = FormHelper() self.helper.layout = Layout( 'title', 'company', 'location', 'email', 'seniority', 'remote_work', 'tags', 'description', ) self.helper.add_input(Submit('job_submit', _('Guardar'))) self.helper.add_input( Reset('job_reset', _('Limpiar'), css_class='btn-default')) def clean_tags(self): tags = self.cleaned_data.get('tags') self.cleaned_data['tags'] = utils.normalize_tags(tags) return self.cleaned_data['tags'] class Meta: model = Job exclude = ('owner', 'is_active')