Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # -*- coding: utf-8 -*-
- from django import forms
- from django.core.validators import EmailValidator
- from django.core.exceptions import NON_FIELD_ERRORS
- from main.models import Profile
- # для кастомного Field:
- from django.forms import BoundField, Field, ImageField
- from django.utils.translation import ugettext_lazy as _
- from django.utils.html import format_html
- from django.forms.utils import flatatt
- from django.utils.safestring import mark_safe
- from django.middleware.csrf import get_token
- class ViewImageField(BoundField):
- def __init__(self, form, field, name, textvalue = 'textvalue', css_cls = 'upload_image'):
- if textvalue == 'textvalue': textvalue = 'Define ' + textvalue + ' in ' + self.__class__.__name__
- self.text = textvalue
- self.css_class = 'class=' + css_cls
- super(ViewImageField, self).__init__(form, field, name)
- def label_tag(self, contents=None, attrs=None, label_suffix=None):
- contents = contents or self.label
- if label_suffix is None:
- label_suffix = (self.field.label_suffix if self.field.label_suffix is not None
- else self.form.label_suffix)
- if label_suffix and contents and contents[-1] not in _(':?.!'):
- contents = format_html(u'{}{}', contents, label_suffix)
- widget = self.field.widget
- id_ = widget.attrs.get('id') or self.auto_id
- if id_:
- id_for_label = widget.id_for_label(id_)
- if id_for_label:
- attrs = dict(attrs or {}, **{'for': id_for_label})
- if self.field.required and hasattr(self.form, 'required_css_class'):
- attrs = attrs or {}
- if 'class' in attrs:
- attrs['class'] += ' ' + self.form.required_css_class
- else:
- attrs['class'] = self.form.required_css_class
- attrs = flatatt(attrs) if attrs else ''
- contents = format_html(u'<label {}>{} <span {}>{}</span> </label>', attrs, contents, self.css_class, self.text)
- else:
- contents = conditional_escape(contents)
- return mark_safe(contents)
- class CustomImageField(ImageField):
- """
- отвечает за представление поля в шаблоне через методы класса BoundField, т.к.
- BoundField - отвечает за представление поля в шаблоне
- Нам надо переопределить label_tag, поэтому возвращаем свой класс BoundField с переопределенным методом label_tag
- """
- def get_bound_field(self, form, field_name):
- return ViewImageField(form, self, field_name, "Выбрать") #css_cls =
- """
- в конструкторе добавили поле parent - если он не None, тогда с него берем некоторые заданные параметры
- """
- def __init__(self,
- parent = None, #FileInput
- required=True,
- widget=None,
- label=None,
- initial=None,
- help_text='',
- error_messages=None,
- show_hidden_initial=False,
- validators=(),
- localize=False,
- disabled=False,
- label_suffix=None):
- # если он не None, тогда с него берем некоторые заданные параметры
- if parent:
- label = parent.label
- widget = parent.widget
- self.textvalue = ''
- # так же надо задать некоторые параметры для label
- super(CustomImageField, self).__init__(
- required,
- widget,
- label,
- initial,
- help_text,
- error_messages,
- show_hidden_initial,
- validators,
- localize,
- disabled,
- label_suffix)
- class CreatePersonHTML(forms.ModelForm):
- def __init__(self, sub = 'def', cssclass = '',*args, **kwargs):
- super(CreatePersonHTML, self).__init__(*args, **kwargs)
- self.request = kwargs.pop('request', None)
- self.submit = sub
- self.css_class = cssclass
- def as_h(self):
- csrf_t = 'None'
- submit = self.submit
- cssclass = format_html(u'class="{}"', self.css_class) if len(self.css_class) > 0 else ''
- if self.request != None:
- csrf_t = '<input type="hidden" name="csrfmiddlewaretoken" value="' + get_token(self.request) + '">'
- if self.submit == 'def':
- submit = 'in_' + self.__class__.__name__ + '_notdefined'
- html = '<form method="post" '+ cssclass + '>' + csrf_t + self.as_p() + '<input type="submit" value=' + submit + '></form>'
- return mark_safe(html)
- def __unicode__(self):
- return self.as_h()
- class CreatePerson(CreatePersonHTML):
- #required_css_class = 'required_fields'
- error_css_class = 'error_class' #работает, но не востребовано
- class Meta(object):
- model = Profile
- fields = ('username', 'password', 'first_name', 'last_name', 'email', 'City', 'Sex', 'Age', 'Image') # exclude
- #exclude = ('username',)
- labels = {
- 'username': 'Введите желаемый логин',
- 'password': 'Пароль',
- 'first_name': 'Имя',
- 'last_name': 'Фамилия либо Отчество',
- 'email': 'Почта',
- 'Image':'Изображение',
- }
- help_texts = {
- 'username': (''),
- }
- widgets = {
- 'password': forms.PasswordInput(attrs={'placeholder': u'Пароль'}),
- 'email': forms.EmailInput(attrs={'placeholder':'mail@example.ru'}),
- 'Image': forms.FileInput(
- attrs={
- 'accept':"image/jpeg,image/png",
- 'style':'visibility:hidden',
- 'onchange': 'file_upload(this, event)'}),#'style': display:none
- }
- error_messages = {
- NON_FIELD_ERRORS: {
- 'unique_together': "%(model_name)s's %(field_labels)s are not unique.", #если нужны будут два уникальных поля
- },
- 'username': {
- 'unique': u"Пользователь с таким именем уже существует",
- },
- }
- def __init__(self, *args, **kwargs):
- super(CreatePerson, self).__init__(*args, **kwargs)
- self.submit = u'Присоединиться'
- self.css_class = ''
- self.fields['email'].validators=[EmailValidator(message="Некорректный адрес электронной почты")]
- self.fields['Image'] = CustomImageField(self.fields['Image'])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement