Пример #1
0
class StudentForm(CDCModelForm):
    first_name = forms.CharField(
        widget=forms.TextInput(attrs={
            'placeholder': 'Jane',
            'class': 'form-control'
        }),
        label='First Name')

    last_name = forms.CharField(widget=forms.TextInput(attrs={
        'placeholder': 'Doe',
        'class': 'form-control'
    }),
                                label='Last Name')

    gender = forms.CharField(widget=forms.TextInput(attrs={
        'placeholder': '',
        'class': 'form-control'
    }),
                             label='Gender')

    school_name = forms.CharField(
        widget=forms.TextInput(attrs={'class': 'form-control'}),
        label='School Name',
        required=False)

    school_type = forms.ChoiceField(widget=forms.RadioSelect,
                                    choices=SCHOOL_TYPE_CHOICES,
                                    required=False)

    race_ethnicity = forms.ModelMultipleChoiceField(
        widget=forms.CheckboxSelectMultiple,
        queryset=RaceEthnicity.objects.filter(visible=True),
        required=False)

    birthday = forms.CharField(widget=html5_widgets.DateInput(
        attrs={'class': 'form-control'}))

    medications = forms.CharField(
        widget=forms.Textarea(
            attrs={
                'placeholder': 'List any medications currently being taken.',
                'class': 'form-control hidden',
                'rows': 5
            }),
        label=format_html(
            u"{0} {1}", "Medications",
            mark_safe(
                '<span class="btn btn-xs btn-link js-expand-student-form">expand</span>'
            )),
        required=False)

    medical_conditions = forms.CharField(
        widget=forms.Textarea(
            attrs={
                'placeholder': 'List any medical conditions.',
                'class': 'form-control hidden',
                'rows': 5
            }),
        label=format_html(
            u"{0} {1}", "Medical Conditions",
            mark_safe(
                '<span class="btn btn-xs btn-link js-expand-student-form">expand</span>'
            )),
        required=False)

    photo_release = forms.BooleanField(
        widget=forms.CheckboxInput(attrs={'required': 'required'}),
        label=
        'I hereby give permission to CoderDojoChi to use the student\'s image and/or likeness in promotional materials.'
    )

    consent = forms.BooleanField(
        widget=forms.CheckboxInput(attrs={'required': 'required'}),
        label=
        'I hereby give consent for the student signed up above to participate in CoderDojoChi.'
    )

    class Meta:
        model = Student
        exclude = ('guardian', 'created_at', 'updated_at', 'active')
Пример #2
0
class EditForm(CreateForm):
    is_active = forms.BooleanField(required=False, widget=forms.CheckboxInput())
Пример #3
0
    class Meta:
        model = House
        fields = ['title', 'country', 'city', 'address', 'type',
                  'rooms', 'sleeper', 'price', 'activity', 'about']

        widgets = {
            'title': forms.TextInput(attrs={

                'required': True,
                'class': 'form-control mb-2',
                'placeholder': _('Title'),
                'title': _('Enter title of advertisement'),
                'maxlength': 100,

            }),

            'country': forms.TextInput(attrs={
                'name': 'city',
                'class': 'form-control mb-2',
                'placeholder': _('Country'),
                'title': _('Select a country'),
                'list': 'countries',
            }),

            # pattern = "[\+]\d{1}\s[\(]\d{3}[\)]\s\d{3}[\-]\d{2}[\-]\d{2}"
            'city': forms.TextInput(attrs={
                'name': 'city',
                'class': 'form-control mb-2',
                'placeholder': _('City'),
                'title': _('Enter city: only alphabet character valid'),
                'maxlength': 40,
                # 'pattern': '[A-Za-zА-ЯЙйЁёЫыъьІіЄєЇї]*[ -`][A-Za-zА-ЯЙйЁёЫыъьІіЄєЇї]*',

            }),
            'address': forms.TextInput(attrs={
                'name': 'Address',
                'class': 'form-control mb-2',
                'placeholder': _('Street, 1, 1'),
                'full_title': _('Enter address: Street name, House number, Apartment number'),
                'short_title': _('Enter address: Street name, House number'),
                'title': _('Enter address: Street name, House number'),
                'maxlength': 100,

            }),
            'type': forms.Select(choices=House.HOUSE_TYPE,
                                 attrs={
                                     'class': 'form-control mb-2',
                                     'name': 'type',
                                     'title': 'Select house-type',
                                 }),
            'rooms': forms.NumberInput(attrs={
                'name': 'rooms',
                'class': 'form-control mb-2',
                'title': _('Enter rooms count'),
                'min': 1,
                'max': MAX_ROOMS,
            }),

            'price': forms.NumberInput(attrs={
                'name': 'price',
                'class': 'form-control',
                'title': _('Enter rental price per day'),
                'value': 10,
                'min': 1,
                'max': MAX_PRICE,
                'step': 1,
            }),
            'sleeper': forms.NumberInput(attrs={
                'name': 'sleeper',
                'class': 'form-control mb-2',
                'required': False,
                'title': _('Enter sleeper count'),
                'min': 1,
                'max': MAX_SLEEPER,

            }),

            'about': forms.Textarea(attrs={
                'name': 'about',
                'class': 'form-control mb-2',
                'title': _('Tell about house'),
                'placeholder': _('Tell about house...'),
            }),

            'activity': forms.CheckboxInput(attrs={
                'class': 'custom-control-input',
            }),
        }
Пример #4
0
 class Meta:
     model = Lead
     fields = [
         "team",
         "assigned_to",
         "source",
         "title",
         "first_name",
         "last_name",
         "date_of_birth",
         "age",
         "work_org_name",
         "work_address1",
         "work_address2",
         "work_address3",
         "work_address4",
         "work_address_city",
         "work_address_state_county",
         "work_address_postcode",
         "work_address_country",
         "phone_number",
         "work_Role",
         "website",
         "mobile_number",
         "preferred_contact_preference",
         "preferred_contact_time",
         "email",
         "secondary_email",
         "social_media_1",
         "social_media_2",
         "social_media_3",
         "profile_picture",
         "status",
         "lead_Ratings",
         "description",
         "closeReason",
         "external_ref1",
         "external_ref2",
         "external_ref3",
         "emailOptIn",
         "nbr_of_employees",
         "industry",
         "annual_revenue",
         "currency",
         "preferred_communication_language",
     ]
     exclude = [
         "id",
         "created_by",
         "dateTimeModified",
         "dateTimeCreated",
         "emailOptInStatusChangeDate",
     ]
     autocomplete_fields = ["status", "industry", "assigned_to"]
     widgets = {
         "team": forms.Select(attrs={"class": "form-control"}),
         "assigned_to": forms.Select(attrs={"class": "form-control"}),
         "source": forms.TextInput(attrs={"class": "form-control"}),
         "title": forms.Select(attrs={"class": "form-control"}),
         "first_name": forms.TextInput(attrs={"class": "form-control"}),
         "last_name": forms.TextInput(attrs={"class": "form-control"}),
         "date_of_birth": forms.DateInput(
             attrs={"class": "form-control", "type": "date"}
         ),
         "age": forms.NumberInput(attrs={"class": "form-control"}),
         "work_org_name": forms.TextInput(attrs={"class": "form-control"}),
         "work_address1": forms.TextInput(attrs={"class": "form-control"}),
         "work_address2": forms.TextInput(attrs={"class": "form-control"}),
         "work_address3": forms.TextInput(attrs={"class": "form-control"}),
         "work_address4": forms.TextInput(attrs={"class": "form-control"}),
         "work_address_city": forms.TextInput(attrs={"class": "form-control"}),
         "work_address_state_county": forms.TextInput(
             attrs={"class": "form-control"}
         ),
         "work_address_postcode": forms.TextInput(
             attrs={"class": "form-control", "placeholder": "PostCode"}
         ),
         "work_address_country": forms.Select(attrs={"class": "form-control"}),
         "phone_number": forms.NumberInput(attrs={"class": "form-control"}),
         "work_Role": forms.TextInput(attrs={"class": "form-control"}),
         "website": forms.URLInput(attrs={"class": "form-control"}),
         "mobile_number": forms.NumberInput(attrs={"class": "form-control"}),
         "preferred_contact_preference": forms.Select(
             attrs={"class": "form-control"}
         ),
         "preferred_contact_time": forms.Select(attrs={"class": "form-control"}),
         "email": forms.EmailInput(attrs={"class": "form-control"}),
         "secondary_email": forms.EmailInput(attrs={"class": "form-control"}),
         "social_media_1": forms.URLInput(attrs={"class": "form-control"}),
         "social_media_2": forms.URLInput(attrs={"class": "form-control"}),
         "social_media_3": forms.URLInput(attrs={"class": "form-control"}),
         "profile_picture": forms.widgets.ClearableFileInput(
             attrs={"class": "form-control-file"}
         ),
         "status": forms.Select(attrs={"class": "form-control"}),
         "lead_Ratings": forms.TextInput(attrs={"class": "form-control"}),
         "description": forms.Textarea(attrs={"class": "form-control"}),
         "closeReason": forms.Textarea(attrs={"class": "form-control"}),
         "external_ref1": forms.TextInput(attrs={"class": "form-control"}),
         "external_ref2": forms.TextInput(attrs={"class": "form-control"}),
         "external_ref3": forms.TextInput(attrs={"class": "form-control"}),
         "industry": forms.Select(attrs={"class": "form-control"}),
         "emailOptIn": forms.CheckboxInput(attrs={"class": "form-check-input"}),
         "annual_revenue": forms.NumberInput(attrs={"class": "form-control"}),
         "nbr_of_employees": forms.NumberInput(attrs={"class": "form-control"}),
         "currency": forms.Select(attrs={"class": "form-control"}),
         "preferred_communication_language": forms.Select(
             attrs={"class": "form-control"}
         ),
     }
Пример #5
0
class PropEdit(forms.Form):
    choiceprop = [
        "Property Type", "Apartment", "Cottage", "Condonium", "Cottage",
        "Flat", "House"
    ]
    Property_type = forms.ChoiceField(choices=[(o, str(o))
                                               for o in choiceprop])

    choize = [
        "Towns", "Chadiza", "Chama", "Chambeshi", "Chavuma", "Chembe",
        "Chibombo", "Chiengi", "Chilubi", "Chinsali", "Chinyingi", "Chirundu",
        "Chisamba", "Choma", "Gwembe", "Isoka", "Kabompo", "Kafue", "Kafulwe",
        "Kalabo", "Kalene Hill", "Kalomo", "Kalulushi", "Kanyembo", "Kaoma",
        "Kapiri Mposhi", "Kasempa", "Kashikishi", "Kataba", "Katete",
        "Kawambwa", "Kazembe", "Kazungula", "Kibombomene", "Luangwa",
        "Lufwanyama", "Lukulu", "Lundazi", "Macha Mission", "Makeni"
        "Maliti", "Mansa", "Mazabuka", "Mbala", "Mbereshi", "Mfuwe", "Milenge",
        "Misisi", "Mkushi", "Mongu", "Monze", "Mpika", "Mporokoso", "Mpulungu",
        "Mumbwa", "Muyombe", "Mwinilunga", "Nchelenge", "Ngoma", "Nkana",
        "Nseluka", "Pemba", "Petauke", "Samfya", "Senanga", "Serenje",
        "Sesheke", "Shiwa Ngandu", "Siavonga", "Sikalongo", "Sinazongwe",
        "Zambezi", "Zimba"
    ]
    town = forms.ChoiceField(choices=[(o, str(o)) for o in choize])

    choize = [
        "provinces", "Copperbelt", "Luapula", "Muchinga", "North-Western",
        "Western", "Southern", "Central", "Lusaka", "Eastern", "Northern"
    ]
    provinces = forms.ChoiceField(choices=[(o, str(o)) for o in choize])
    choice = [
        "City", "Lusaka", "Ndola", "Kitwe", "Kabwe", "Chingola", "Mufulira",
        "Livingstone", "Luanshya", "Kasama", "Chipata"
    ]
    # js.index()
    city = forms.ChoiceField(choices=[(o, str(o)) for o in choice])
    #prop_id = forms.IntegerField(widget=forms.NumberInput())
    video = forms.CharField(required=False,
                            widget=forms.TextInput(attrs={
                                'class': 'form-control',
                            }))
    myfile = forms.ImageField(required=False,
                              widget=forms.FileInput(
                                  attrs={
                                      'visibility': 'hidden',
                                      'position': 'absolute',
                                      'top': '-9999px',
                                      'left': '-9999px',
                                      'onchange': 'showImage()',
                                      'data-show-upload': 'false',
                                      'data-show-caption': 'false',
                                      'data-show-remove': 'false',
                                      'data-browse-class': 'btn btn-default',
                                      'data-browse-label': 'Browse Images',
                                      'accept': 'image/jpeg,image/png',
                                  }))

    title = forms.CharField(max_length=30,
                            widget=forms.TextInput(attrs={
                                'class': 'form-control',
                            }))
    price = forms.IntegerField(widget=forms.NumberInput(
        attrs={
            'class': 'form-control',
        }))
    address = forms.CharField(max_length=255,
                              widget=forms.TextInput(attrs={
                                  'class': 'form-control',
                              }))
    baths = forms.IntegerField()
    beds = forms.IntegerField()
    area = forms.IntegerField()
    garages = forms.IntegerField(required=False)

    description = forms.CharField(
        max_length=2000,
        widget=forms.Textarea(attrs={
            'class': 'form-control',
        }),
    )

    tags = forms.CharField(
        required=False,
        max_length=2000,
        widget=forms.Textarea(attrs={
            'class': 'form-control',
            'rows': '2',
            'onkeyup': 'tag()',
        }))

    choice = ["sale", "rent"]
    # js.index()
    status = forms.ChoiceField(choices=[(o, str(o)) for o in choice])
    choice = ["Cash", "Debit"]
    # js.index()
    payment_option = forms.ChoiceField(choices=[(o, str(o)) for o in choice])

    choiceprop = [
        "Apartment", "Cottage", "Condonium", "Cottage", "Flat", "House"
    ]
    Property_type = forms.ChoiceField(choices=[(o, str(o))
                                               for o in choiceprop])
    CHOICES = (
        ("True", "True"),
        ("False", "False"),
    )
    Allow_User_rating = forms.ChoiceField(
        choices=CHOICES,
        required=False,
        widget=forms.CheckboxInput(attrs={
            #'style': 'position: absolute; opacity: 0;'
        }))

    def clean(self):
        cleaned_data = super(PropEdit, self).clean()
        name = cleaned_data.get('title')
        email = cleaned_data.get('price')
        message = cleaned_data.get('baths')
        if not name and not email and not message:
            raise forms.ValidationError('You have to write something!')
Пример #6
0
class CreateLearningUnitYearForm(BootstrapForm):
    acronym = forms.CharField(widget=forms.TextInput(attrs={
        'maxlength': "15",
        'required': True
    }))
    academic_year = forms.ModelChoiceField(
        queryset=mdl.academic_year.find_academic_years(),
        required=True,
        empty_label=_('all_label'))
    status = forms.CharField(required=False, widget=forms.CheckboxInput())
    internship_subtype = forms.ChoiceField(
        choices=((None, EMPTY_FIELD), ) +
        mdl.enums.internship_subtypes.INTERNSHIP_SUBTYPES,
        required=False)
    credits = forms.DecimalField(decimal_places=2)
    title = forms.CharField(widget=forms.TextInput(attrs={'required': True}))
    title_english = forms.CharField(required=False, widget=forms.TextInput())
    session = forms.ChoiceField(
        choices=((None, EMPTY_FIELD), ) +
        mdl.enums.learning_unit_year_session.LEARNING_UNIT_YEAR_SESSION,
        required=False)
    subtype = forms.CharField(widget=forms.HiddenInput())
    first_letter = forms.CharField(
        required=False,
        widget=forms.TextInput(attrs={
            'class': 'text-center',
            'maxlength': "1",
            'readonly': 'readonly'
        }))
    container_type = forms.ChoiceField(
        choices=lazy(create_learning_container_year_type_list, tuple),
        widget=forms.Select(
            attrs={'onchange': 'showInternshipSubtype(this.value)'}))
    faculty_remark = forms.CharField(required=False,
                                     widget=forms.Textarea(attrs={'rows': 2}))
    other_remark = forms.CharField(required=False,
                                   widget=forms.Textarea(attrs={'rows': 2}))
    periodicity = forms.CharField(widget=forms.Select(
        choices=PERIODICITY_TYPES))
    quadrimester = forms.CharField(widget=forms.Select(
        choices=((None, EMPTY_FIELD), ) + LEARNING_UNIT_YEAR_QUADRIMESTERS),
                                   required=False)
    campus = forms.ModelChoiceField(
        queryset=find_administration_campuses(),
        widget=forms.Select(attrs={'onchange': 'setFirstLetter()'}))

    requirement_entity = EntitiesVersionChoiceField(
        find_main_entities_version().none(),
        widget=forms.Select(
            attrs={
                'onchange':
                'showAdditionalEntity(this.value, "id_additional_entity_1")'
            }))

    allocation_entity = EntitiesVersionChoiceField(
        find_main_entities_version(),
        required=False,
        widget=forms.Select(attrs={
            'class': 'form-control',
            'id': 'allocation_entity'
        }))
    additional_entity_1 = EntitiesVersionChoiceField(
        find_main_entities_version(),
        required=False,
        widget=forms.Select(
            attrs={
                'onchange':
                'showAdditionalEntity(this.value, "id_additional_entity_2")',
                'disable': 'disable'
            }))

    additional_entity_2 = EntitiesVersionChoiceField(
        find_main_entities_version(),
        required=False,
        widget=forms.Select(attrs={'disable': 'disable'}))

    language = forms.ModelChoiceField(find_all_languages(), empty_label=None)

    acronym_regex = "^[BLMW][A-Z]{2,4}\d{4}$"

    def __init__(self, person, *args, **kwargs):
        super(CreateLearningUnitYearForm, self).__init__(*args, **kwargs)
        # When we create a learning unit, we can only select requirement entity which are attached to the person
        self.fields[
            "requirement_entity"].queryset = find_main_entities_version_filtered_by_person(
                person)

    def clean_acronym(self):
        data_cleaned = self.data.get('first_letter') + self.cleaned_data.get(
            'acronym')
        if data_cleaned:
            return data_cleaned.upper()

    def is_valid(self):
        if not super().is_valid():
            return False
        try:
            academic_year = mdl.academic_year.find_academic_year_by_id(
                self.data.get('academic_year'))
        except ObjectDoesNotExist:
            return False
        learning_unit_years = mdl.learning_unit_year.find_gte_year_acronym(
            academic_year, self.data['acronym'])
        learning_unit_years_list = [
            learning_unit_year.acronym.lower()
            for learning_unit_year in learning_unit_years
        ]
        if self.data['acronym'] in learning_unit_years_list:
            self.add_error('acronym', _('existing_acronym'))
        elif not re.match(self.acronym_regex, self.cleaned_data['acronym']):
            self.add_error('acronym', _('invalid_acronym'))
        elif self.cleaned_data["container_type"] == INTERNSHIP \
                and not (self.cleaned_data['internship_subtype']):
            self._errors['internship_subtype'] = _('field_is_required')
        else:
            return True
Пример #7
0
class RegistrationForm(forms.Form):
    """The basic account registration form."""
    title = forms.CharField(max_length=30, label=_('Title'), required=False)
    email = forms.EmailField(label=_('Email address'),
                             max_length=75,
                             required=True)
    password2 = forms.CharField(label=_('Password (again)'),
                                max_length=30,
                                widget=forms.PasswordInput(),
                                required=True)
    password1 = forms.CharField(label=_('Password'),
                                max_length=30,
                                widget=forms.PasswordInput(),
                                required=True)
    first_name = forms.CharField(label=_('First name'),
                                 max_length=30,
                                 required=True)
    last_name = forms.CharField(label=_('Last name'),
                                max_length=30,
                                required=True)
    next = forms.CharField(max_length=200,
                           required=False,
                           widget=forms.HiddenInput())
    username = forms.RegexField(
        regex=r'^[\w.@+-]+$',
        required=False,
        max_length=30,
        widget=forms.TextInput(attrs=attrs_dict),
        label=_(u'Username'),
        error_messages={
            'invalid': _('Please use only letters, numbers and @/./+/-/_')
        })

    def __init__(self, *args, **kwargs):
        contact = kwargs.get('contact', None)
        initial = kwargs.get('initial', {})
        self.contact = contact
        form_initialdata.send(RegistrationForm,
                              form=self,
                              contact=contact,
                              initial=initial)

        kwargs['initial'] = initial
        super(RegistrationForm, self).__init__(*args, **kwargs)
        form_init.send(RegistrationForm, form=self, contact=contact)

    newsletter = forms.BooleanField(label=_('Newsletter'),
                                    widget=forms.CheckboxInput(),
                                    required=False)

    def clean_password1(self):
        """Enforce that password and password2 are the same."""
        p1 = self.cleaned_data.get('password1')
        p2 = self.cleaned_data.get('password2')
        if not (p1 and p2 and p1 == p2):
            raise forms.ValidationError(
                ugettext("The two passwords do not match."))

        # note, here is where we'd put some kind of custom
        # validator to enforce "hard" passwords.
        return p1

    def clean_username(self):
        """Validate username is unique
        """
        username = self.cleaned_data.get('username', None)
        if username and User.objects.filter(
                username__iexact=username).count() > 0:
            raise forms.ValidationError(
                ugettext("That username is already in use."))
        return username

    def clean_email(self):
        """Prevent account hijacking by disallowing duplicate emails."""
        email = self.cleaned_data.get('email', None)
        if email and User.objects.filter(email__iexact=email).count() > 0:
            raise forms.ValidationError(
                ugettext("That email address is already in use."))

        return email

    def save(self, request=None, force_new=False, **kwargs):
        """Create the contact and user described on the form.  Returns the
        `contact`.
        """
        if self.contact:
            log.debug('skipping save, already done')
        else:
            self.save_contact(request, force_new_contact=force_new)

        return self.contact

    def save_contact(self, request, force_new_contact=False):
        log.debug("Saving contact")
        data = self.cleaned_data
        password = data['password1']
        email = data['email']
        first_name = data['first_name']
        last_name = data['last_name']
        allow_nickname = config_value('SHOP', 'ALLOW_NICKNAME_USERNAME')
        if allow_nickname and data['username']:
            username = data['username']
        else:
            username = generate_id(first_name, last_name, email)
        verify = (config_value('SHOP', 'ACCOUNT_VERIFICATION') == 'EMAIL')

        if verify:
            site = Site.objects.get_current()
            from registration.models import RegistrationProfile
            # TODO:
            # In django-registration trunk this signature has changed.
            # Satchmo is going to stick with the latest release so I'm changing
            # this to work with 0.7
            # When 0.8 comes out we're going to have to refactor to this:
            #user = RegistrationProfile.objects.create_inactive_user(
            #    username, email, password, site)
            # See ticket #1028 where we checked in the above line prematurely
            user = RegistrationProfile.objects.create_inactive_user(
                username, password, email)
        else:
            user = User.objects.create_user(username, email, password)

        user.first_name = first_name
        user.last_name = last_name
        user.save()

        # If the user already has a contact, retrieve it.
        # Otherwise, create a new one.
        contact = None
        if not force_new_contact:
            try:
                contact = Contact.objects.from_request(request, create=False)
            except Contact.DoesNotExist:
                pass

        if contact is None:
            contact = Contact()

        contact.user = user
        contact.first_name = first_name
        contact.last_name = last_name
        contact.email = email
        contact.role = ContactRole.objects.get(pk='Customer')
        contact.title = data.get('title', '')
        contact.save()

        if 'newsletter' not in data:
            subscribed = False
        else:
            subscribed = data['newsletter']

        signals.satchmo_registration.send(self,
                                          contact=contact,
                                          subscribed=subscribed,
                                          data=data)

        if not verify:
            user = authenticate(username=username, password=password)
            login(request, user)
            send_welcome_email(email, first_name, last_name)
            signals.satchmo_registration_verified.send(self, contact=contact)

        self.contact = contact

        return contact
Пример #8
0
class PostAndBookForm(forms.Form):
    # Post
    post_title = forms.CharField(
        label="Post Title*",
        max_length=100,
        widget=forms.TextInput(attrs={"class": " form-spacing"}),
    )
    post_contents = forms.CharField(
        label="Post Contents*", widget=forms.Textarea(attrs={"class": " form-spacing"})
    )
    image = forms.ImageField(
        label="Image (Optional)",
        required=False,
        widget=forms.ClearableFileInput(attrs={"class": " form-spacing-file"}),
    )
    # Book-Check
    book_check = forms.BooleanField(
        required=False,
        label="This post isn't about a book",
        label_suffix="",
        widget=forms.CheckboxInput(attrs={"class": "book-check"}),
    )
    # Book
    author = forms.CharField(
        required=False,
        label="Author*",
        max_length=50,
        widget=forms.TextInput(attrs={"class": " form-spacing"}),
    )
    title = forms.CharField(
        required=False,
        label="Book's Title*",
        max_length=100,
        widget=forms.TextInput(attrs={"class": " form-spacing"}),
    )
    isbn = forms.CharField(
        required=False,
        max_length=20,
        widget=forms.TextInput(attrs={"class": " form-spacing"}),
    )
    
    synopsis = forms.CharField(
        required=False,
        label="Synopsis",
        widget=forms.Textarea(attrs={"class": " form-spacing"}),
    )
    rating = forms.CharField(
        required=False,
        label="Rating",
        widget=forms.Select(
            choices=((1, 1), (2, 2), (3, 3), (4, 4), (5, 5)),
            attrs={"class": " form-spacing"},
        ),
    )

    # Form Validation, Cleaning, and DB Subitting
    def clean(self):
        cleaned_data = super().clean()
        print(self.cleaned_data["book_check"])
        if self.cleaned_data["book_check"] == False and no_book_check(
            form=self.cleaned_data
        ):
            raise forms.ValidationError(
                "You need to either check the 'This post isn't about a book' box or include book informaiton."
            )
Пример #9
0
class CreateTariffForm(forms.Form):
    identifier = forms.CharField(widget=forms.HiddenInput, required=False)
    tariffNameUzb = forms.CharField(
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': 'NameUzb'
        }),
        label='NameUzb',
        max_length=255,
        required=True)
    tariffNameRus = forms.CharField(
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': 'NameRus'
        }),
        label='NameRus',
        max_length=255,
        required=True)
    tariffNameEng = forms.CharField(
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': 'NameEng'
        }),
        label='NameEng',
        max_length=255,
        required=True)
    tariffNameFra = forms.CharField(
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': 'NameFra'
        }),
        label='NameFra',
        max_length=255,
        required=True)
    tariffNameEsp = forms.CharField(
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': 'NameEsp'
        }),
        label='NameEsp',
        max_length=255,
        required=True)
    show = forms.BooleanField(
        widget=forms.CheckboxInput(attrs={'class': 'flat'}),
        initial=True,
        label='Show')

    def as_dict(self, tariff_id=False):
        if tariff_id:
            return {
                'tariffNameUzb': self['tariffNameUzb'].value(),
                'tariffNameRus': self['tariffNameRus'].value(),
                'tariffNameEng': self['tariffNameEng'].value(),
                'tariffNameFra': self['tariffNameFra'].value(),
                'tariffNameEsp': self['tariffNameEsp'].value(),
                'tariffId': self['identifier'].value(),
                'show': self['show'].value()
            }
        else:
            return {
                'tariffNameUzb': self['tariffNameUzb'].value(),
                'tariffNameRus': self['tariffNameRus'].value(),
                'tariffNameEng': self['tariffNameEng'].value(),
                'tariffNameFra': self['tariffNameFra'].value(),
                'tariffNameEsp': self['tariffNameEsp'].value(),
                'show': self['show'].value()
            }
Пример #10
0
class StaffMemberForm(forms.Form):
    first_name = forms.CharField(
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': u'Введите имя',
        }),
        max_length=60,
        label=u'Имя')
    middle_name = forms.CharField(
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': u'Введите отчество',
        }),
        max_length=60,
        label=u'Отчество')
    last_name = forms.CharField(
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': u'Введите фамилию',
        }),
        max_length=60,
        label=u'Фамилия')
    is_chairman = forms.BooleanField(
        widget=forms.CheckboxInput(attrs={
            'class': 'form-control',
        }),
        label=u'Является администрацией',
        initial=False,
        required=False,
    )
    chair_position = forms.CharField(
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': u'нет'
        }),
        label=u'Должность в администрации',
        empty_value=u'нет')
    is_combiner = forms.BooleanField(
        widget=forms.CheckboxInput(attrs={
            'class': 'form-control',
        }),
        label=u'Является совместителем',
        initial=False,
        required=False,
    )
    subject = forms.CharField(
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': u'Введите предмет'
        }),
        label=u'Преподаваемый предмет')
    category = forms.CharField(
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': u'Введите категорию'
        }),
        label=u'Категория')
    email = forms.EmailField(
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': u'email',
        }),
        label=u'Электронная почта (необязательно)',
        empty_value=u'',
        required=False)
    experience = forms.IntegerField(
        widget=forms.NumberInput(attrs={
            'class': 'form-control',
        }),
        label=u'Преподавательский стаж',
        min_value=0,
        max_value=100)

    def save(self):
        data = self.cleaned_data
        StaffMember().add_or_update(data.get('first_name'),
                                    data.get('middle_name'),
                                    data.get('last_name'),
                                    data.get('is_chairman'),
                                    data.get('chair_position'),
                                    data.get('is_combiner'),
                                    data.get('subject'), data.get('category'),
                                    data.get('email'), data.get('experience'))
        return self
Пример #11
0
class DocumentForm(forms.Form):
    title = forms.CharField(
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': u'Название документа',
        }),
        label=u'Название документа',
        max_length=150)
    description = forms.CharField(widget=forms.TextInput(
        attrs={
            'class': 'form-control',
            'placeholder': u'Краткое описание документа (необязательно)',
        }),
                                  label=u'Описание документа',
                                  required=False)
    doc = forms.FileField(
        widget=forms.ClearableFileInput(attrs={
            'class': 'form-control-file',
        }),
        label=u'Файл')
    categories = forms.CharField(widget=forms.TextInput(
        attrs={
            'class':
            'form-control',
            'placeholder':
            u'Категории документа (каждая категория начинается с #)',
        }),
                                 label=u'Категории')
    createNewsEntry = forms.BooleanField(
        widget=(forms.CheckboxInput(attrs={
            'class': 'form-control',
        })),
        label=u'Создать новость',
        required=False)
    newsPic = forms.FileField(
        widget=forms.ClearableFileInput(attrs={
            'class': 'form-control-file',
        }),
        label=u'Картинка новости',
        required=False)

    def save(self):
        data = self.cleaned_data
        document = Document()
        document.title = data.get('title')
        document.title_id = document.make_title_id()
        document.description = data.get('description')
        document.save()
        if data.get('doc') is not None:
            doc_file = data.get('doc')
            doc_namext = re.split('[.]+', doc_file.name)
            document.doc.save('%s_%s.%s' %
                              (doc_namext[0], str(document.id), doc_namext[1]),
                              doc_file,
                              save=True)
        document.save()
        categories_raw = data.get('categories')
        categories_raw.lower()
        categories = re.split('[#]+', categories_raw)
        for cat_name in categories:
            if cat_name is not None and cat_name != '':
                category = DocumentCategory.objects.get_or_create(
                    name=cat_name)
                document.categories.add(category)
        document.save()
        createNews = data.get('createNewsEntry')
        if createNews:
            entry = News()
            entry.title = document.title
            entry.content = document.description
            entry.doc_url = reverse('document_show',
                                    kwargs={
                                        'title': document.make_title_id(),
                                    })
            entry.save()
            if data.get('newsPic') is not None:
                pic_file = data.get('newsPic')
                pic_namext = re.split('[.]+', pic_file.name)
                entry.pic.save('%s_%s.%s' %
                               (pic_namext[0], str(entry.id), pic_namext[1]),
                               pic_file,
                               save=True)
            entry.save()
        return document
Пример #12
0
class LeaseForm(forms.ModelForm):
    default_attrs = {'class': 'form-control'}

    ticket = forms.IntegerField(required=False,
                                widget=forms.NumberInput(attrs=default_attrs))

    type = forms.ChoiceField(required=False,
                             choices=lease_types,
                             widget=forms.Select(attrs=default_attrs))

    organization = forms.ModelChoiceField(
        required=True,
        queryset=Client.objects.all().order_by('netname'),
        widget=forms.Select(attrs=default_attrs))
    group = forms.ModelChoiceField(
        required=False,
        queryset=LeaseGroup.objects.all().order_by('description'),
        widget=forms.Select(attrs=default_attrs))

    cities = forms.ModelMultipleChoiceField(
        required=True,
        queryset=City.objects.all().order_by('name'),
        widget=forms.SelectMultiple(attrs=default_attrs))

    identity = forms.CharField(required=True,
                               widget=forms.TextInput(attrs=default_attrs))
    addresses = forms.CharField(required=False,
                                widget=forms.Textarea(attrs=default_attrs))
    agreement = forms.CharField(required=False,
                                widget=forms.TextInput(attrs=default_attrs))
    support_email = forms.CharField(
        required=False, widget=forms.TextInput(attrs=default_attrs))
    description = forms.CharField(required=False,
                                  widget=forms.TextInput(attrs=default_attrs))

    contacts = forms.CharField(required=False,
                               widget=forms.Textarea(attrs=default_attrs))
    comment = forms.CharField(required=False,
                              widget=forms.Textarea(attrs=default_attrs))
    google_map_url = forms.CharField(
        required=False, widget=forms.TextInput(attrs=default_attrs))

    is_ours = forms.BooleanField(required=False, widget=forms.CheckboxInput())
    is_bought = forms.BooleanField(required=False,
                                   widget=forms.CheckboxInput())

    class Meta:
        model = Lease
        fields = [
            'ticket',
            'organization',
            'cities',
            'identity',
            'agreement',
            'support_email',
            'description',
            'type',
            'contacts',
            'comment',
            'is_ours',
            'is_bought',
            'group',
            'google_map_url',
            'addresses',
        ]

    def clean_addresses(self):
        lease_type = self.cleaned_data.get('type')
        addresses = self.cleaned_data.get('addresses')
        if lease_type in ['l2', 'qinq']:
            if not addresses:
                raise forms.ValidationError(
                    'Адреса включения обязательны для l2-каналов')
        return addresses
Пример #13
0
    def __init__(self, *args, **kwargs):
        """
        Takes two additional keyword arguments:

        :param cartpos: The cart position the form should be for
        :param event: The event this belongs to
        """
        cartpos = self.cartpos = kwargs.pop('cartpos', None)
        orderpos = self.orderpos = kwargs.pop('orderpos', None)
        pos = cartpos or orderpos
        item = pos.item
        questions = pos.item.questions_to_ask
        event = kwargs.pop('event')
        self.all_optional = kwargs.pop('all_optional', False)

        super().__init__(*args, **kwargs)

        if item.admission and event.settings.attendee_names_asked:
            self.fields['attendee_name_parts'] = NamePartsFormField(
                max_length=255,
                required=event.settings.attendee_names_required,
                scheme=event.settings.name_scheme,
                titles=event.settings.name_scheme_titles,
                label=_('Attendee name'),
                initial=(cartpos.attendee_name_parts
                         if cartpos else orderpos.attendee_name_parts),
            )
        if item.admission and event.settings.attendee_emails_asked:
            self.fields['attendee_email'] = forms.EmailField(
                required=event.settings.attendee_emails_required,
                label=_('Attendee email'),
                initial=(cartpos.attendee_email
                         if cartpos else orderpos.attendee_email))

        for q in questions:
            # Do we already have an answer? Provide it as the initial value
            answers = [a for a in pos.answerlist if a.question_id == q.id]
            if answers:
                initial = answers[0]
            else:
                initial = None
            tz = pytz.timezone(event.settings.timezone)
            help_text = rich_text(q.help_text)
            label = escape(q.question)  # django-bootstrap3 calls mark_safe
            required = q.required and not self.all_optional
            if q.type == Question.TYPE_BOOLEAN:
                if q.required:
                    # For some reason, django-bootstrap3 does not set the required attribute
                    # itself.
                    widget = forms.CheckboxInput(
                        attrs={'required': 'required'})
                else:
                    widget = forms.CheckboxInput()

                if initial:
                    initialbool = (initial.answer == "True")
                else:
                    initialbool = False

                field = forms.BooleanField(
                    label=label,
                    required=required,
                    help_text=help_text,
                    initial=initialbool,
                    widget=widget,
                )
            elif q.type == Question.TYPE_NUMBER:
                field = forms.DecimalField(
                    label=label,
                    required=required,
                    help_text=q.help_text,
                    initial=initial.answer if initial else None,
                    min_value=Decimal('0.00'),
                )
            elif q.type == Question.TYPE_STRING:
                field = forms.CharField(
                    label=label,
                    required=required,
                    help_text=help_text,
                    initial=initial.answer if initial else None,
                )
            elif q.type == Question.TYPE_TEXT:
                field = forms.CharField(
                    label=label,
                    required=required,
                    help_text=help_text,
                    widget=forms.Textarea,
                    initial=initial.answer if initial else None,
                )
            elif q.type == Question.TYPE_COUNTRYCODE:
                field = CountryField().formfield(
                    label=label,
                    required=required,
                    help_text=help_text,
                    widget=forms.Select,
                    empty_label='',
                    initial=initial.answer if initial else None,
                )
            elif q.type == Question.TYPE_CHOICE:
                field = forms.ModelChoiceField(
                    queryset=q.options,
                    label=label,
                    required=required,
                    help_text=help_text,
                    widget=forms.Select,
                    to_field_name='identifier',
                    empty_label='',
                    initial=initial.options.first() if initial else None,
                )
            elif q.type == Question.TYPE_CHOICE_MULTIPLE:
                field = forms.ModelMultipleChoiceField(
                    queryset=q.options,
                    label=label,
                    required=required,
                    help_text=help_text,
                    to_field_name='identifier',
                    widget=forms.CheckboxSelectMultiple,
                    initial=initial.options.all() if initial else None,
                )
            elif q.type == Question.TYPE_FILE:
                field = forms.FileField(
                    label=label,
                    required=required,
                    help_text=help_text,
                    initial=initial.file if initial else None,
                    widget=UploadedFileWidget(position=pos,
                                              event=event,
                                              answer=initial),
                )
            elif q.type == Question.TYPE_DATE:
                field = forms.DateField(
                    label=label,
                    required=required,
                    help_text=help_text,
                    initial=dateutil.parser.parse(initial.answer).date()
                    if initial and initial.answer else None,
                    widget=DatePickerWidget(),
                )
            elif q.type == Question.TYPE_TIME:
                field = forms.TimeField(
                    label=label,
                    required=required,
                    help_text=help_text,
                    initial=dateutil.parser.parse(initial.answer).time()
                    if initial and initial.answer else None,
                    widget=TimePickerWidget(
                        time_format=get_format_without_seconds(
                            'TIME_INPUT_FORMATS')),
                )
            elif q.type == Question.TYPE_DATETIME:
                field = SplitDateTimeField(
                    label=label,
                    required=required,
                    help_text=help_text,
                    initial=dateutil.parser.parse(
                        initial.answer).astimezone(tz)
                    if initial and initial.answer else None,
                    widget=SplitDateTimePickerWidget(
                        time_format=get_format_without_seconds(
                            'TIME_INPUT_FORMATS')),
                )
            field.question = q
            if answers:
                # Cache the answer object for later use
                field.answer = answers[0]

            if q.dependency_question_id:
                field.widget.attrs[
                    'data-question-dependency'] = q.dependency_question_id
                field.widget.attrs[
                    'data-question-dependency-values'] = escapejson_attr(
                        json.dumps(q.dependency_values))
                if q.type != 'M':
                    field.widget.attrs[
                        'required'] = q.required and not self.all_optional
                    field._required = q.required and not self.all_optional
                field.required = False

            self.fields['question_%s' % q.id] = field

        responses = question_form_fields.send(sender=event, position=pos)
        data = pos.meta_info_data
        for r, response in sorted(responses, key=lambda r: str(r[0])):
            for key, value in response.items():
                # We need to be this explicit, since OrderedDict.update does not retain ordering
                self.fields[key] = value
                value.initial = data.get('question_form_data', {}).get(key)
Пример #14
0
class EventCancelForm(forms.Form):
    subevent = forms.ModelChoiceField(SubEvent.objects.none(),
                                      label=pgettext_lazy('subevent', 'Date'),
                                      required=False,
                                      empty_label=pgettext_lazy(
                                          'subevent', 'All dates'))
    all_subevents = forms.BooleanField(
        label=_('Cancel all dates'),
        initial=False,
        required=False,
    )
    subevents_from = forms.SplitDateTimeField(
        widget=SplitDateTimePickerWidget(
            attrs={
                'data-inverse-dependency': '#id_all_subevents',
            }),
        label=pgettext_lazy('subevent', 'All dates starting at or after'),
        required=False,
    )
    subevents_to = forms.SplitDateTimeField(
        widget=SplitDateTimePickerWidget(
            attrs={
                'data-inverse-dependency': '#id_all_subevents',
            }),
        label=pgettext_lazy('subevent', 'All dates starting before'),
        required=False,
    )
    auto_refund = forms.BooleanField(
        label=_('Automatically refund money if possible'),
        initial=True,
        required=False)
    manual_refund = forms.BooleanField(
        label=
        _('Create manual refund if the payment method does not support automatic refunds'
          ),
        widget=forms.CheckboxInput(
            attrs={'data-display-dependency': '#id_auto_refund'}),
        initial=True,
        required=False,
        help_text=
        _('If checked, all payments with a payment method not supporting automatic refunds will be on your '
          'manual refund to-do list. Do not check if you want to refund some of the orders by offsetting '
          'with different orders or issuing gift cards.'))
    refund_as_giftcard = forms.BooleanField(
        label=
        _('Refund order value to a gift card instead instead of the original payment method'
          ),
        widget=forms.CheckboxInput(
            attrs={'data-display-dependency': '#id_auto_refund'}),
        initial=False,
        required=False,
    )
    gift_card_expires = SplitDateTimeField(
        label=_('Gift card validity'),
        required=False,
        widget=SplitDateTimePickerWidget(
            attrs={'data-display-dependency': '#id_refund_as_giftcard'}, ))
    gift_card_conditions = forms.CharField(
        label=_('Special terms and conditions'),
        required=False,
        widget=forms.Textarea(attrs={
            'rows':
            2,
            'data-display-dependency':
            '#id_refund_as_giftcard'
        }, ))
    keep_fee_fixed = forms.DecimalField(
        label=_("Keep a fixed cancellation fee"),
        max_digits=10,
        decimal_places=2,
        required=False)
    keep_fee_per_ticket = forms.DecimalField(
        label=_("Keep a fixed cancellation fee per ticket"),
        help_text=_("Free tickets and add-on products are not counted"),
        max_digits=10,
        decimal_places=2,
        required=False)
    keep_fee_percentage = forms.DecimalField(
        label=_("Keep a percentual cancellation fee"),
        max_digits=10,
        decimal_places=2,
        required=False)
    keep_fees = forms.MultipleChoiceField(
        label=_("Keep fees"),
        widget=forms.CheckboxSelectMultiple,
        choices=[(k, v) for k, v in OrderFee.FEE_TYPES
                 if k != OrderFee.FEE_TYPE_GIFTCARD],
        help_text=
        _('The selected types of fees will not be refunded but instead added to the cancellation fee. Fees '
          'are never refunded in when an order in an event series is only partially canceled since it '
          'consists of tickets for multiple dates.'),
        required=False,
    )
    send = forms.BooleanField(label=_("Send information via email"),
                              required=False)
    send_subject = forms.CharField()
    send_message = forms.CharField()
    send_waitinglist = forms.BooleanField(
        label=_("Send information to waiting list"), required=False)
    send_waitinglist_subject = forms.CharField()
    send_waitinglist_message = forms.CharField()

    def _set_field_placeholders(self, fn, base_parameters):
        phs = [
            '{%s}' % p for p in sorted(
                get_available_placeholders(self.event, base_parameters).keys())
        ]
        ht = _('Available placeholders: {list}').format(list=', '.join(phs))
        if self.fields[fn].help_text:
            self.fields[fn].help_text += ' ' + str(ht)
        else:
            self.fields[fn].help_text = ht
        self.fields[fn].validators.append(PlaceholderValidator(phs))

    def __init__(self, *args, **kwargs):
        self.event = kwargs.pop('event')
        kwargs.setdefault('initial', {})
        kwargs['initial'][
            'gift_card_expires'] = self.event.organizer.default_gift_card_expiry
        super().__init__(*args, **kwargs)
        self.fields['send_subject'] = I18nFormField(
            label=_("Subject"),
            required=True,
            widget_kwargs={'attrs': {
                'data-display-dependency': '#id_send'
            }},
            initial=_('Canceled: {event}'),
            widget=I18nTextInput,
            locales=self.event.settings.get('locales'),
        )
        self.fields['send_message'] = I18nFormField(
            label=_('Message'),
            widget=I18nTextarea,
            required=True,
            widget_kwargs={'attrs': {
                'data-display-dependency': '#id_send'
            }},
            locales=self.event.settings.get('locales'),
            initial=LazyI18nString.from_gettext(
                gettext_noop(
                    'Hello,\n\n'
                    'with this email, we regret to inform you that {event} has been canceled.\n\n'
                    'We will refund you {refund_amount} to your original payment method.\n\n'
                    'You can view the current state of your order here:\n\n{url}\n\nBest regards,\n\n'
                    'Your {event} team')))

        self._set_field_placeholders('send_subject', [
            'event_or_subevent', 'refund_amount', 'position_or_address',
            'order', 'event'
        ])
        self._set_field_placeholders('send_message', [
            'event_or_subevent', 'refund_amount', 'position_or_address',
            'order', 'event'
        ])
        self.fields['send_waitinglist_subject'] = I18nFormField(
            label=_("Subject"),
            required=True,
            initial=_('Canceled: {event}'),
            widget=I18nTextInput,
            widget_kwargs={
                'attrs': {
                    'data-display-dependency': '#id_send_waitinglist'
                }
            },
            locales=self.event.settings.get('locales'),
        )
        self.fields['send_waitinglist_message'] = I18nFormField(
            label=_('Message'),
            widget=I18nTextarea,
            required=True,
            locales=self.event.settings.get('locales'),
            widget_kwargs={
                'attrs': {
                    'data-display-dependency': '#id_send_waitinglist'
                }
            },
            initial=LazyI18nString.from_gettext(
                gettext_noop(
                    'Hello,\n\n'
                    'with this email, we regret to inform you that {event} has been canceled.\n\n'
                    'You will therefore not receive a ticket from the waiting list.\n\n'
                    'Best regards,\n\n'
                    'Your {event} team')))
        self._set_field_placeholders('send_waitinglist_subject',
                                     ['event_or_subevent', 'event'])
        self._set_field_placeholders('send_waitinglist_message',
                                     ['event_or_subevent', 'event'])

        if self.event.has_subevents:
            self.fields['subevent'].queryset = self.event.subevents.all()
            self.fields['subevent'].widget = Select2(
                attrs={
                    'data-inverse-dependency':
                    '#id_all_subevents',
                    'data-model-select2':
                    'event',
                    'data-select2-url':
                    reverse('control:event.subevents.select2',
                            kwargs={
                                'event': self.event.slug,
                                'organizer': self.event.organizer.slug,
                            }),
                    'data-placeholder':
                    pgettext_lazy('subevent', 'All dates')
                })
            self.fields['subevent'].widget.choices = self.fields[
                'subevent'].choices
        else:
            del self.fields['subevent']
            del self.fields['all_subevents']
        change_decimal_field(self.fields['keep_fee_fixed'],
                             self.event.currency)

    def clean(self):
        d = super().clean()
        if d.get('subevent') and d.get('subevents_from'):
            raise ValidationError(
                pgettext_lazy(
                    'subevent',
                    'Please either select a specific date or a date range, not both.'
                ))
        if d.get('all_subevents') and d.get('subevent_from'):
            raise ValidationError(
                pgettext_lazy(
                    'subevent',
                    'Please either select all dates or a date range, not both.'
                ))
        if bool(d.get('subevents_from')) != bool(d.get('subevents_to')):
            raise ValidationError(
                pgettext_lazy(
                    'subevent',
                    'If you set a date range, please set both a start and an end.'
                ))
        if self.event.has_subevents and not d['subevent'] and not d[
                'all_subevents'] and not d.get('subevents_from'):
            raise ValidationError(
                _('Please confirm that you want to cancel ALL dates in this event series.'
                  ))
        return d
Пример #15
0
class ExperimentFilterset(filters.FilterSet):

    search = filters.CharFilter(
        method="filter_search",
        widget=SearchWidget(
            attrs={"class": "form-control", "placeholder": "Search Deliveries"}
        ),
    )
    type = filters.MultipleChoiceFilter(
        choices=Experiment.TYPE_CHOICES,
        conjoined=False,
        widget=forms.SelectMultiple(attrs={"class": "form-control"}),
    )
    status = filters.ChoiceFilter(
        empty_label="All Statuses",
        choices=Experiment.STATUS_CHOICES,
        widget=forms.Select(attrs={"class": "form-control"}),
    )
    firefox_channel = filters.ChoiceFilter(
        empty_label="All Channels",
        choices=Experiment.CHANNEL_CHOICES[1:],
        widget=forms.Select(attrs={"class": "form-control"}),
    )
    firefox_version = filters.ChoiceFilter(
        empty_label="All Versions",
        choices=Experiment.VERSION_CHOICES[1:],
        widget=forms.Select(attrs={"class": "form-control"}),
        method="version_filter",
    )
    owner = filters.ModelChoiceFilter(
        empty_label="All Owners",
        queryset=get_user_model().objects.all().order_by("email"),
        widget=forms.Select(attrs={"class": "form-control"}),
    )
    analysis_owner = filters.ModelChoiceFilter(
        empty_label="All Data Scientists",
        queryset=get_user_model().objects.all().order_by("email"),
        widget=forms.Select(attrs={"class": "form-control"}),
    )

    archived = filters.BooleanFilter(
        label="Show archived deliveries",
        widget=forms.CheckboxInput(),
        method="archived_filter",
    )
    experiment_date_field = filters.ChoiceFilter(
        empty_label="No Date Restriction",
        choices=[
            (Experiment.EXPERIMENT_STARTS, "Delivery Starts"),
            (Experiment.EXPERIMENT_PAUSES, "Delivery Pauses"),
            (Experiment.EXPERIMENT_ENDS, "Delivery Ends"),
        ],
        widget=forms.Select(attrs={"class": "form-control"}),
        method="experiment_date_field_filter",
    )
    date_range = filters.DateFromToRangeFilter(
        method="date_range_filter",
        widget=DateRangeWidget(attrs={"type": "date", "class": "form-control"}),
    )

    in_qa = filters.BooleanFilter(
        label="Show only deliveries in QA",
        widget=forms.CheckboxInput(),
        method="in_qa_filter",
    )

    surveys = filters.BooleanFilter(
        label="Show deliveries with surveys",
        widget=forms.CheckboxInput(),
        method="surveys_filter",
    )

    subscribed = filters.BooleanFilter(
        label="Show subscribed deliveries",
        widget=forms.CheckboxInput(),
        method="subscribed_filter",
    )

    longrunning = filters.BooleanFilter(
        label="Show long-running deliveries",
        widget=forms.CheckboxInput(),
        method="longrunning_filter",
    )

    is_paused = filters.BooleanFilter(
        label="Show enrollment complete deliveries",
        widget=forms.CheckboxInput(),
        method="is_paused_filter",
    )

    completed_results = filters.BooleanFilter(
        label="Show deliveries with results completed",
        widget=forms.CheckboxInput(),
        method="completed_results_filter",
    )

    class Meta:
        model = Experiment
        fields = (
            "search",
            "type",
            "status",
            "firefox_channel",
            "firefox_version",
            "owner",
            "analysis_owner",
            "in_qa",
            "surveys",
            "archived",
            "subscribed",
            "longrunning",
            "is_paused",
            "completed_results",
        )

    def filter_search(self, queryset, name, value):
        vector = SearchVector(
            "name",
            "short_description",
            "owner__email",
            "analysis_owner__email",
            "slug",
            "related_work",
            "addon_experiment_id",
            "pref_key",
            "public_name",
            "public_description",
            "objectives",
            "analysis",
            "engineering_owner",
            "bugzilla_id",
            "normandy_slug",
            "data_science_bugzilla_url",
            "feature_bugzilla_url",
        )

        query = SearchQuery(value)

        return (
            queryset.annotate(rank=SearchRank(vector, query), search=vector)
            .filter(search=value)
            .order_by("-rank")
        )

    def archived_filter(self, queryset, name, value):
        if not value:
            return queryset.exclude(archived=True)
        return queryset

    def experiment_date_field_filter(self, queryset, name, value):
        # this custom method isn't doing anything. There has to
        # be a custom method to be able to display the select
        # filter that controls which date range we show
        return queryset

    def version_filter(self, queryset, name, value):
        return queryset.filter(
            Q(firefox_min_version__lte=value, firefox_max_version__gte=value)
            | Q(firefox_min_version=value)
        )

    def date_range_filter(self, queryset, name, value):
        date_type = self.form.cleaned_data["experiment_date_field"]

        experiment_date_field = {
            Experiment.EXPERIMENT_STARTS: "start_date",
            Experiment.EXPERIMENT_PAUSES: "enrollment_end_date",
            Experiment.EXPERIMENT_ENDS: "end_date",
        }[date_type]

        results = []

        for experiment in queryset.all():
            date = getattr(experiment, experiment_date_field)

            # enrollment end dates are optional, so there won't always
            # be a pause date for an experiment
            if date:
                if value.start and date < value.start.date():
                    continue
                if value.stop and date > value.stop.date():
                    continue
                results.append(experiment.id)

        return queryset.filter(pk__in=results)

    def in_qa_filter(self, queryset, name, value):
        if value:
            return queryset.filter(review_qa_requested=True, review_qa=False)

        return queryset

    def surveys_filter(self, queryset, name, value):
        if value:
            return queryset.filter(survey_required=True)

        return queryset

    def subscribed_filter(self, queryset, name, value):
        if value:
            return queryset.filter(subscribers__in=[self.request.user.id])

        return queryset

    def longrunning_filter(self, queryset, name, value):
        if value:
            return (
                queryset.exclude(firefox_max_version__exact="")
                .annotate(
                    firefox_min_int=Cast(
                        Func(
                            F("firefox_min_version"),
                            Value(ExperimentConstants.VERSION_REGEX.pattern),
                            function="substring",
                        ),
                        IntegerField(),
                    ),
                    firefox_max_int=Cast(
                        Func(
                            F("firefox_max_version"),
                            Value(ExperimentConstants.VERSION_REGEX.pattern),
                            function="substring",
                        ),
                        IntegerField(),
                    ),
                    version_count=F("firefox_max_int") - F("firefox_min_int"),
                )
                .filter(version_count__gte=3)
            )

        return queryset

    def is_paused_filter(self, queryset, name, value):
        if value:
            return queryset.filter(is_paused=True, status=Experiment.STATUS_LIVE)

        return queryset

    def completed_results_filter(self, queryset, name, value):
        if value:
            return queryset.exclude(
                Q(results_url="") | Q(results_url=None),
                Q(results_initial="") | Q(results_initial=None),
                Q(results_lessons_learned="") | Q(results_lessons_learned=None),
            )
        return queryset

    def get_type_display_value(self):
        return ", ".join(
            [
                dict(Experiment.TYPE_CHOICES)[type].replace(" Experiment", "")
                for type in self.data.getlist("type")
            ]
        )

    def get_owner_display_value(self):
        user_id = self.data.get("owner")

        if user_id is not None:
            return str(get_user_model().objects.get(id=user_id))

    def get_display_start_date_info(self):
        experiment_date_field = self.data.get("experiment_date_field")
        date_after = self.data.get("date_range_after")
        date_before = self.data.get("date_range_before")

        if date_after and date_before:
            return f"{experiment_date_field} between {date_after} and {date_before}"
        elif date_after and date_before == "":
            return f"{experiment_date_field} after {date_after}"
        elif date_after == "" and date_before:
            return f"{experiment_date_field} before {date_before}"
        else:
            return ""
Пример #16
0
class SubscriptionForm(PluginSettingsFormMixin, forms.Form):

    settings_form_headline = _('Notifications')
    settings_order = 1
    settings_write_access = False

    settings = SettingsModelChoiceField(
        Settings,
        empty_label=None,
        label=_('Settings')
    )
    edit = forms.BooleanField(
        required=False,
        label=_('When this article is edited')
    )
    edit_email = forms.BooleanField(
        required=False,
        label=_('Also receive emails about article edits'),
        widget=forms.CheckboxInput(
            attrs={'onclick': mark_safe("$('#id_edit').attr('checked', $(this).is(':checked'));")}
        )
    )

    def __init__(self, article, request, *args, **kwargs):

        self.article = article
        self.user = request.user
        initial = kwargs.pop('initial', None)
        self.notification_type = NotificationType.objects.get_or_create(
            key=ARTICLE_EDIT,
            content_type=ContentType.objects.get_for_model(article)
        )[0]
        self.edit_notifications = models.ArticleSubscription.objects.filter(
            article=article,
            subscription__notification_type=self.notification_type,
            subscription__settings__user=self.user,
        )
        self.default_settings = Settings.objects.get_or_create(
            user=request.user,
            interval=notify_settings.INTERVALS_DEFAULT
        )[0]
        if self.edit_notifications:
            self.default_settings = self.edit_notifications[0].subscription.settings
        if not initial:
            initial = {
                'edit': bool(self.edit_notifications),
                'edit_email': bool(self.edit_notifications.filter(subscription__send_emails=True)),
                'settings': self.default_settings,
            }
        kwargs['initial'] = initial
        super(SubscriptionForm, self).__init__(*args, **kwargs)
        self.fields['settings'].queryset = Settings.objects.filter(
            user=request.user,
        )

    def get_usermessage(self):
        if self.changed_data:
            return _('Your notification settings were updated.')
        else:
            return _('Your notification settings were unchanged, so nothing saved.')

    def save(self, *args, **kwargs):

        cd = self.cleaned_data
        if not self.changed_data:
            return
        if cd['edit']:
            try:
                edit_notification = models.ArticleSubscription.objects.get(
                    subscription__notification_type=self.notification_type,
                    article=self.article,
                    subscription__settings=cd['settings'],
                )
                edit_notification.subscription.send_emails = cd['edit_email']
                edit_notification.subscription.save()
            except models.ArticleSubscription.DoesNotExist:
                subscription, __ = Subscription.objects.get_or_create(
                    settings=cd['settings'],
                    notification_type=self.notification_type,
                    object_id=self.article.id,
                )
                edit_notification = models.ArticleSubscription.objects.create(
                    subscription=subscription,
                    article=self.article,
                )
                subscription.send_emails = cd['edit_email']
                subscription.save()

        else:
            self.edit_notifications.delete()
Пример #17
0
class UserRegisterForm(forms.Form):
    username = forms.CharField(
        required=True,
        label=u"用户名",
        error_messages={
            "required": u"请输入用户名",
            "max_length": u"用户名最长为20位",
            "min_length": u"用户名最短位6位",
        },
        widget=forms.TextInput(attrs={
            "placeholder": u"请输入用户名",
            "class": "form-control",
        }),
        max_length=20,
        min_length=6,
    )

    password = forms.CharField(
        required=True,
        label=u"密码",
        error_messages={
            "required": u"请输入密码",
            "max_length": u"密码最长为20位",
            "min_length": u"密码最短位6位",
        },
        widget=forms.PasswordInput(attrs={
            "placeholder": u"请输入密码",
            "class": "form-control",
        }),
        max_length=20,
        min_length=6,
    )

    password_confirm = forms.CharField(
        required=True,
        label=u'确认密码',
        error_messages={
            "required": u"请输入密码",
            "max_length": u"密码最长为20位",
            "min_length": u"密码最短位6位",
        },
        widget=forms.PasswordInput(attrs={
            "placeholder": u"请再次输入密码",
            "class": "form-control",
        }),
        max_length=20,
        min_length=6,
    )

    email = forms.EmailField(
        required=True,
        label=u'邮箱',
        error_messages={
            "required": u"请输入邮箱",
        },
        widget=forms.EmailInput(attrs={
            "placeholder": u"请输入邮箱",
            "class": "form-control",
        }),
    )

    confirm_message = forms.BooleanField(
        required=True,
        widget=forms.CheckboxInput(),
    )
Пример #18
0
class addhouse_form(forms.Form):
    name = forms.CharField(
        max_length=256,
        widget=forms.TextInput(attrs={'class': 'form-control'}),
        required=True)
    address = forms.CharField(
        max_length=256,
        widget=forms.TextInput(attrs={'class': 'form-control'}),
        required=True)
    postcode = forms.CharField(
        max_length=4,
        widget=forms.TextInput(attrs={'class': 'form-control'}),
        required=True)
    price = forms.IntegerField(
        min_value=1,
        widget=forms.NumberInput(attrs={
            'class': 'form-control',
            'placeholder': "200 (per night)"
        }),
        required=True)
    profile = forms.CharField(max_length=5000,
                              widget=forms.Textarea(attrs={
                                  'class': 'form-control',
                                  'rows': 5
                              }),
                              required=False)
    maxguest = forms.IntegerField(
        min_value=1,
        widget=forms.NumberInput(attrs={
            'class': 'form-control',
            'placeholder': 'eg. 1'
        }),
        required=True)
    bed = forms.IntegerField(min_value=0,
                             widget=forms.NumberInput(attrs={
                                 'class': 'form-control',
                                 'placeholder': 'eg. 1'
                             }),
                             required=True)
    bedroom = forms.IntegerField(
        min_value=0,
        widget=forms.NumberInput(attrs={
            'class': 'form-control',
            'placeholder': 'eg. 1'
        }),
        required=True)
    bathroom = forms.IntegerField(
        min_value=0,
        widget=forms.NumberInput(attrs={
            'class': 'form-control',
            'placeholder': 'eg. 1'
        }),
        required=True)
    park = forms.IntegerField(min_value=0,
                              widget=forms.NumberInput(attrs={
                                  'class': 'form-control',
                                  'placeholder': 'eg. 1'
                              }),
                              required=True)
    tv = forms.BooleanField(
        widget=forms.CheckboxInput(attrs={'class': 'form-check-input'}),
        required=False)
    kitchen = forms.BooleanField(
        widget=forms.CheckboxInput(attrs={'class': 'form-check-input'}),
        required=False)
    washer = forms.BooleanField(
        widget=forms.CheckboxInput(attrs={'class': 'form-check-input'}),
        required=False)
    fridge = forms.BooleanField(
        widget=forms.CheckboxInput(attrs={'class': 'form-check-input'}),
        required=False)
    conditioner = forms.BooleanField(
        widget=forms.CheckboxInput(attrs={'class': 'form-check-input'}),
        required=False)
    wifi = forms.BooleanField(
        widget=forms.CheckboxInput(attrs={'class': 'form-check-input'}),
        required=False)
    studyroom = forms.BooleanField(
        widget=forms.CheckboxInput(attrs={'class': 'form-check-input'}),
        required=False)
    pool = forms.BooleanField(
        widget=forms.CheckboxInput(attrs={'class': 'form-check-input'}),
        required=False)
    rule = forms.CharField(max_length=5000,
                           widget=forms.Textarea(attrs={
                               'class': 'form-control',
                               'rows': 5
                           }),
                           required=False)
    cancellation = forms.CharField(max_length=5000,
                                   widget=forms.Textarea(attrs={
                                       'class': 'form-control',
                                       'rows': 5
                                   }),
                                   required=False)
    extra = forms.CharField(max_length=5000,
                            widget=forms.Textarea(attrs={
                                'class': 'form-control',
                                'rows': 5
                            }),
                            required=False)
Пример #19
0
    def __init__(self, **kwargs):
        self.shop = kwargs.pop("shop")
        if not self.shop:
            raise ValueError("Error! No shop provided.")
        super(ContentWizardForm, self).__init__(**kwargs)

        if djangoenv.has_installed("shuup.simple_cms"):
            pages = self._get_installed_pages()

            self.fields["about_us"] = forms.BooleanField(
                label=_("Create About Us page"),
                required=False,
                initial=True,
                widget=forms.CheckboxInput(
                    attrs={"disabled": (content_data.ABOUT_US_KEY in pages)}))

            # Set the help text for different ocasions - whether the content is installed or not.
            if content_data.ABOUT_US_KEY in pages:
                self.fields["about_us"].help_text = _(
                    "We have already created an 'About Us' template for you based "
                    "on your shop information. You must review the page and "
                    "change it accordingly.")
            else:
                self.fields["about_us"].help_text = _(
                    "We will create an 'About Us' template for you. "
                    "We will base content of the page on your shop information. "
                    "After we are done, you must review the page and "
                    "change it accordingly.")

            self.fields["privacy_policy"] = forms.BooleanField(
                label=_("Create Privacy Policy page"),
                required=False,
                initial=True,
                widget=forms.CheckboxInput(attrs={
                    "disabled": (content_data.PRIVACY_POLICY_KEY in pages)
                }))
            # Set the help text for different ocasions - whether the content is installed or not.
            if content_data.PRIVACY_POLICY_KEY in pages:
                self.fields["privacy_policy"].help_text = _(
                    "We have already created a 'Privacy Policy' template "
                    "for you based on your shop information. "
                    "You must review the page and change it accordingly.")
            else:
                self.fields["privacy_policy"].help_text = _(
                    "We will create a 'Privacy Policy' template for you. "
                    "We will base content of the page on "
                    "your shop information. After we are done, "
                    "you must review the page and change it accordingly.")

            self.fields["terms_conditions"] = forms.BooleanField(
                label=_("Create Terms and Conditions page"),
                required=False,
                initial=True,
                widget=forms.CheckboxInput(attrs={
                    "disabled": (
                        content_data.TERMS_AND_CONDITIONS_KEY in pages)
                }),
            )
            # Set the help text for different ocasions - whether the content is installed or not.
            if content_data.TERMS_AND_CONDITIONS_KEY in pages:
                self.fields["terms_conditions"].help_text = _(
                    "We have already created a 'Terms & Conditions' template "
                    "for you based on your shop information. "
                    "You must review the page and change it accordingly.")
            else:
                self.fields["terms_conditions"].help_text = _(
                    "We will create a 'Terms & Conditions' template "
                    "for you. We will base content of the page on "
                    "your shop information. After we are done, "
                    "you must review the page and change it accordingly.")

            self.fields["refund_policy"] = forms.BooleanField(
                label=_("Create Refund Policy page"),
                required=False,
                initial=True,
                widget=forms.CheckboxInput(attrs={
                    "disabled": (content_data.REFUND_POLICY_KEY in pages)
                }),
            )
            # Set the help text for different ocasions - whether the content is installed or not.
            if content_data.REFUND_POLICY_KEY in pages:
                self.fields["refund_policy"].help_text = _(
                    "We have already created a 'Refund Policy' template "
                    "for you based on your shop information. "
                    "You must review the page and change it accordingly.")
            else:
                self.fields["refund_policy"].help_text = _(
                    "We will create an 'Refund Policy' template for you. "
                    "We will base content of the page on your shop information. "
                    "After we are done, you must review the page and "
                    "change it accordingly.")

        if djangoenv.has_installed("shuup.xtheme"):
            from shuup.xtheme.models import SavedViewConfig
            svc_pk = config.get(self.shop, CONTENT_FOOTER_KEY)
            svc = SavedViewConfig.objects.filter(pk=svc_pk).first()

            self.fields["configure_footer"] = forms.BooleanField(
                label=_("Configure the footer"),
                required=False,
                initial=True,
                widget=forms.CheckboxInput(attrs={"disabled": bool(svc)}),
                help_text=_(
                    "We will now configure your shop footer and fill it with some of your shop's information. "
                    "Don't worry, you can change this at any time."))
Пример #20
0
    class UnitForm(forms.ModelForm):
        class Meta(object):
            model = Unit
            fields = (
                'target_f',
                'state',
            )

        target_f = MultiStringFormField(
            nplurals=tnplurals,
            required=False,
            attrs=target_attrs,
        )
        state = UnitStateField(
            required=False,
            label=_('Needs work'),
            widget=forms.CheckboxInput(
                attrs=fuzzy_attrs,
                check_test=lambda x: x == FUZZY,
            ),
        )
        similarity = forms.FloatField(required=False)
        mt_similarity = forms.FloatField(required=False)
        suggestion = forms.ModelChoiceField(queryset=Suggestion.objects.all(),
                                            required=False)
        comment = forms.CharField(required=False)

        def __init__(self, *args, **kwargs):
            self.request = kwargs.pop('request', None)
            super(UnitForm, self).__init__(*args, **kwargs)
            self._updated_fields = []

            self.fields['target_f'].widget.attrs['data-translation-aid'] = \
                self['target_f'].value()

        @property
        def updated_fields(self):
            order_dict = {
                SubmissionFields.STATE: 0,
                SubmissionFields.TARGET: 1,
            }
            return sorted(self._updated_fields, key=lambda x: order_dict[x[0]])

        def clean_target_f(self):
            value = self.cleaned_data['target_f']

            if self.instance.target != multistring(value or [u'']):
                self.instance._target_updated = True
                self._updated_fields.append(
                    (SubmissionFields.TARGET, to_db(self.instance.target),
                     to_db(value)))

            return value

        def clean_similarity(self):
            value = self.cleaned_data['similarity']

            if 0 <= value <= 1 or value is None:
                return value

            raise forms.ValidationError(
                _('Value of `similarity` should be in in the [0..1] range'))

        def clean_mt_similarity(self):
            value = self.cleaned_data['mt_similarity']

            if 0 <= value <= 1 or value is None:
                return value

            raise forms.ValidationError(
                _('Value of `mt_similarity` should be in in the [0..1] range'))

        def clean(self):
            old_state = self.instance.state  # Integer
            is_fuzzy = self.cleaned_data['state']  # Boolean
            new_target = self.cleaned_data['target_f']

            # If suggestion is provided set `old_state` should be `TRANSLATED`.
            if self.cleaned_data['suggestion']:
                old_state = TRANSLATED

                # Skip `TARGET` field submission if suggestion value is equal
                # to submitted translation
                if new_target == self.cleaned_data['suggestion'].target_f:
                    self._updated_fields = []

            if (self.request is not None
                    and not check_permission('administrate', self.request)
                    and is_fuzzy):
                self.add_error(
                    'state',
                    forms.ValidationError(
                        _('Needs work flag must be '
                          'cleared')))

            if new_target:
                if old_state == UNTRANSLATED:
                    self.instance._save_action = TRANSLATION_ADDED
                    self.instance.store.mark_dirty(
                        CachedMethods.WORDCOUNT_STATS)
                else:
                    self.instance._save_action = TRANSLATION_CHANGED

                if is_fuzzy:
                    new_state = FUZZY
                else:
                    new_state = TRANSLATED
            else:
                new_state = UNTRANSLATED
                if old_state > FUZZY:
                    self.instance._save_action = TRANSLATION_DELETED
                    self.instance.store.mark_dirty(
                        CachedMethods.WORDCOUNT_STATS)

            if is_fuzzy != (old_state == FUZZY):
                # when Unit toggles its FUZZY state the number of translated
                # words also changes
                self.instance.store.mark_dirty(CachedMethods.WORDCOUNT_STATS,
                                               CachedMethods.LAST_ACTION)

            if old_state not in [new_state, OBSOLETE]:
                self.instance._state_updated = True
                self._updated_fields.append(
                    (SubmissionFields.STATE, old_state, new_state))

                self.cleaned_data['state'] = new_state
            else:
                self.instance._state_updated = False
                self.cleaned_data['state'] = old_state

            return super(UnitForm, self).clean()
Пример #21
0
 class Meta:
     model = ICMS
     fields = (
         'cst',
         'mod_bc',
         'p_icms',
         'p_red_bc',
         'mod_bcst',
         'p_mvast',
         'p_red_bcst',
         'p_icmsst',
         'mot_des_icms',
         'p_dif',
         'p_bc_op',
         'ufst',
         'icms_incluido_preco',
         'icmsst_incluido_preco',
     )
     widgets = {
         'cst':
         forms.Select(attrs={'class': 'form-control'}),
         'mod_bc':
         forms.Select(attrs={'class': 'form-control'}),
         'p_icms':
         forms.TextInput(attrs={'class': 'form-control percentual-mask'}),
         'p_red_bc':
         forms.TextInput(attrs={'class': 'form-control percentual-mask'}),
         'mod_bcst':
         forms.Select(attrs={'class': 'form-control'}),
         'p_mvast':
         forms.TextInput(attrs={'class': 'form-control percentual-mask'}),
         'p_red_bcst':
         forms.TextInput(attrs={'class': 'form-control percentual-mask'}),
         'p_icmsst':
         forms.TextInput(attrs={'class': 'form-control percentual-mask'}),
         'mot_des_icms':
         forms.Select(attrs={'class': 'form-control'}),
         'p_dif':
         forms.TextInput(attrs={'class': 'form-control percentual-mask'}),
         'p_bc_op':
         forms.TextInput(attrs={'class': 'form-control percentual-mask'}),
         'ufst':
         forms.Select(attrs={'class': 'form-control'}),
         'icms_incluido_preco':
         forms.CheckboxInput(attrs={'class': 'form-control'}),
         'icmsst_incluido_preco':
         forms.CheckboxInput(attrs={'class': 'form-control'}),
     }
     labels = {
         'cst': _('CST ICMS'),
         'mod_bc': _('Modalidade de determinação da BC do ICMS'),
         'p_icms': _('Alíquota ICMS'),
         'p_red_bc': _('% da Redução de BC'),
         'mod_bcst': _('Modalidade de determinação da BC do ICMS ST'),
         'p_mvast': _('% Margem de valor Adicionado do ICMS ST'),
         'p_red_bcst': _('% da Redução de BC do ICMS ST'),
         'p_icmsst': _('Alíquota ICMS ST'),
         'mot_des_icms': _('Motivo da desoneração do ICMS'),
         'p_dif': _('% do diferimento'),
         'p_bc_op': _('% da BC operação própria'),
         'ufst': _('UF para qual é devido o ICMS ST'),
         'icms_incluido_preco': _('ICMS incluso no preço'),
         'icmsst_incluido_preco': _('ICMS-ST incluso no preço'),
     }
Пример #22
0
class RegistrationForm(forms.Form):
    """
	Form for registering a new user account.

	Validates that the password is entered twice and matches,
	and that the username is not already taken.

	"""
    username = forms.CharField(max_length=30,
                               widget=forms.TextInput(attrs=attrs_dict),
                               label=u'Username')
    email = forms.EmailField(
        widget=forms.TextInput(attrs=dict(attrs_dict, max_length=200)),
        label=u'Email address')
    fname = forms.CharField(max_length=30, label=u'First Name')
    lname = forms.CharField(max_length=30, label=u'Last Name')
    password1 = forms.CharField(widget=forms.PasswordInput(attrs=attrs_dict),
                                label=u'Password')
    password2 = forms.CharField(widget=forms.PasswordInput(attrs=attrs_dict),
                                label=u'Password (again, to catch typos)')
    tos = forms.BooleanField(
        widget=forms.CheckboxInput(attrs=attrs_dict),
        label=u'I have read and agree to the Terms of Service')

    def clean_username(self):
        """
		Validates that the username is not already in use.

		"""
        if self.cleaned_data.get('username', None):
            try:
                user = User.objects.get(
                    username__exact=self.cleaned_data['username'])
            except User.DoesNotExist:
                return self.cleaned_data['username']
            raise forms.ValidationError(
                u'The username "%s" is already taken. Please choose another.' %
                self.cleaned_data['username'])

    def clean_email(self):
        """
		Validates that the email is not already in use.

		"""
        if self.cleaned_data.get('email', None):
            try:
                user = User.objects.get(
                    username__exact=self.cleaned_data['email'])
            except User.DoesNotExist:
                return self.cleaned_data['email']
            raise forms.ValidationError(
                u'The email "%s" is already taken. Please choose another.' %
                self.cleaned_data['email'])

    def clean_password2(self):
        """
		Validates that the two password inputs match.

		"""
        if self.cleaned_data.get('password1', None) and self.cleaned_data.get('password2', None) and \
        self.cleaned_data['password1'] == self.cleaned_data['password2']:
            return self.cleaned_data['password2']
        raise forms.ValidationError(
            u'You must type the same password each time')

    def clean_tos(self):
        """
		Validates that the user accepted the Terms of Service.

		"""
        if self.cleaned_data.get('tos', False):
            return self.cleaned_data['tos']
        raise forms.ValidationError(u'You must agree to the terms to register')
Пример #23
0
    def __init__(self, *args, **kwargs):
        """
        Takes two additional keyword arguments:

        :param cartpos: The cart position the form should be for
        :param event: The event this belongs to
        """
        cartpos = kwargs.pop('cartpos', None)
        orderpos = kwargs.pop('orderpos', None)
        item = cartpos.item if cartpos else orderpos.item
        questions = list(item.questions.all())
        event = kwargs.pop('event')

        super().__init__(*args, **kwargs)

        if item.admission and event.settings.attendee_names_asked:
            self.fields['attendee_name'] = forms.CharField(
                max_length=255,
                required=event.settings.attendee_names_required,
                label=_('Attendee name'),
                initial=(cartpos.attendee_name
                         if cartpos else orderpos.attendee_name))

        for q in questions:
            # Do we already have an answer? Provide it as the initial value
            answers = [
                a for a in
                (cartpos.answers.all() if cartpos else orderpos.answers.all())
                if a.question_id == q.id
            ]
            if answers:
                initial = answers[0]
            else:
                initial = None
            if q.type == Question.TYPE_BOOLEAN:
                if q.required:
                    # For some reason, django-bootstrap3 does not set the required attribute
                    # itself.
                    widget = forms.CheckboxInput(
                        attrs={'required': 'required'})
                else:
                    widget = forms.CheckboxInput()

                if initial:
                    initialbool = (initial.answer == "True")
                else:
                    initialbool = False

                field = forms.BooleanField(label=q.question,
                                           required=q.required,
                                           initial=initialbool,
                                           widget=widget)
            elif q.type == Question.TYPE_NUMBER:
                field = forms.DecimalField(
                    label=q.question,
                    required=q.required,
                    initial=initial.answer if initial else None,
                    min_value=Decimal('0.00'))
            elif q.type == Question.TYPE_STRING:
                field = forms.CharField(
                    label=q.question,
                    required=q.required,
                    initial=initial.answer if initial else None,
                )
            elif q.type == Question.TYPE_TEXT:
                field = forms.CharField(
                    label=q.question,
                    required=q.required,
                    widget=forms.Textarea,
                    initial=initial.answer if initial else None,
                )
            elif q.type == Question.TYPE_CHOICE:
                field = forms.ModelChoiceField(
                    queryset=q.options.all(),
                    label=q.question,
                    required=q.required,
                    widget=forms.RadioSelect,
                    initial=initial.options.first() if initial else None,
                )
            elif q.type == Question.TYPE_CHOICE_MULTIPLE:
                field = forms.ModelMultipleChoiceField(
                    queryset=q.options.all(),
                    label=q.question,
                    required=q.required,
                    widget=forms.CheckboxSelectMultiple,
                    initial=initial.options.all() if initial else None,
                )
            field.question = q
            if answers:
                # Cache the answer object for later use
                field.answer = answers[0]
            self.fields['question_%s' % q.id] = field
Пример #24
0
def columnView(request, boardId=None, columnId=None):
    errorsExceptStyle = False  # dato utilizzato nel template per rendere attivo il bottone al suseguirsi di un errore nell'inserimento
    if request.method == 'GET' and boardId is not None and columnId is not None:  # se il metodo e GET e la colonna non esiste ritorna not found
        column = Column.objects.filter(pk=columnId, board=boardId)
        board = Board.objects.filter(pk=boardId, users=request.user)
        if not board.exists() or not column.exists():
            return HttpResponseNotFound(NOT_FOUND_PAGE)
        formModifyColumn = FormModifyColumnName(
            initial={
                'boardId': boardId,
                'columnId':
                columnId,  # inizializza form per la modifica del nome
                'newName': Column.objects.get(pk=columnId).name
            })
    elif request.method == 'POST':  # se il metodo e post modifica nome colonna o elimina card
        userLoged = User.objects.get(username=request.user.username)
        formDeleteCard = FormDeleteCard(request.POST)
        formDeleteCard.setUser(userLoged)
        formModifyColumn = FormModifyColumnName(request.POST)
        formModifyColumn.setUser(userLoged)
        if formModifyColumn.is_valid(
        ):  # se il form di modifica e valido modifica nome
            columnId = formModifyColumn.cleaned_data.get('columnId')
            newName = formModifyColumn.cleaned_data.get('newName')
            column = Column.objects.get(pk=columnId)
            column.name = newName
            column.save()
            return redirect(Column.objects.get(pk=columnId).get_absolute_url())
        elif formDeleteCard.is_valid(
        ):  # se il form di eliminazione e valido allora elimina card
            columnId = formDeleteCard.cleaned_data.get('columnId')
            cardId = formDeleteCard.cleaned_data.get('cardId')
            Card.objects.get(pk=cardId).delete()
            return redirect(Column.objects.get(pk=columnId).get_absolute_url())
        elif '*not_found' in str(
                formModifyColumn.errors) and '*not_found' not in str(
                    formDeleteCard.errors):
            boardId = formDeleteCard.cleaned_data.get('boardId')
            columnId = formDeleteCard.cleaned_data.get('columnId')
        elif '*not_found' not in str(
                formModifyColumn.errors) and '*not_found' in str(
                    formDeleteCard.errors):
            # se il form di modifica non e valido ma non ha errori not fount lascia il testo modificabile e il bottone attivo
            errorsExceptStyle = True
            boardId = formModifyColumn.cleaned_data.get('boardId')
            columnId = formModifyColumn.cleaned_data.get('columnId')
            formModifyColumn.fields['newName'].widget = forms.TextInput(
                attrs={'class': 'field'})
            formModifyColumn.fields['checkbox'].widget = forms.CheckboxInput(
                attrs={
                    'name': 'onoffswitch',
                    'class': 'onoffswitch-checkbox',
                    'id': 'myonoffswitch',
                    'checked': 'true',
                    'onclick': MODIFY_ACTIVATE_COLUMN
                })
        else:
            return HttpResponseNotFound(NOT_FOUND_PAGE)
    else:
        return HttpResponseNotFound(NOT_FOUND_PAGE)
    queryCards = Card.objects.filter(column=columnId)
    cards = []
    for card in queryCards:  # costruzione elementi card con dati e form di eliminazione
        formDelete = FormDeleteCard(initial={
            'boardId': boardId,
            'columnId': columnId,
            'cardId': card.pk
        })
        dict = {'card': card, 'formDelete': formDelete}
        cards.append(dict)
    return render(
        request, 'columndetail.html', {
            'board': Board.objects.get(pk=boardId),
            'column': Column.objects.get(pk=columnId),
            'cards': cards,
            'formModify': formModifyColumn,
            'errorsexcept': errorsExceptStyle,
        })
Пример #25
0
class PropertyCreate(forms.Form):
    title = forms.CharField(max_length=30,
                            widget=forms.TextInput(attrs={
                                'class': 'form-control',
                            }))
    price = forms.IntegerField(widget=forms.NumberInput(
        attrs={
            'class': 'form-control',
        }))
    baths = forms.IntegerField()
    beds = forms.IntegerField()
    area = forms.IntegerField()
    garages = forms.IntegerField(required=False)
    latitude = forms.IntegerField(
        required=False,
        widget=forms.NumberInput(attrs={
            'class': 'form-control',
            'readonly': 'true',
        }))
    longitude = forms.IntegerField(
        required=False,
        widget=forms.NumberInput(attrs={
            'class': 'form-control',
            'readonly': 'true',
            'visibility': 'hidden',
        }))
    package = forms.CharField(
        required=False,
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'readonly': 'true',
            'visibility': 'hidden',
        }))

    description = forms.CharField(
        max_length=2000,
        widget=forms.Textarea(attrs={
            'class': 'form-control',
        }),
    )
    image = forms.ImageField(required=False,
                             widget=forms.FileInput(
                                 attrs={
                                     'class': 'file',
                                     'multiple': 'true',
                                     'data-show-upload': 'false',
                                     'data-show-caption': 'false',
                                     'data-show-remove': 'false',
                                     'data-browse-class': 'btn btn-default',
                                     'data-browse-label': 'Browse Images',
                                     'accept': 'image/jpeg,image/png',
                                 }))

    choice = ["sale", "rent"]
    # js.index()
    status = forms.ChoiceField(choices=[(o, str(o)) for o in choice])

    choiceprop = [
        "Apartment", "Cottage", "Condonium", "Cottage", "Flat", "House"
    ]
    Property_type = forms.ChoiceField(choices=[(o, str(o))
                                               for o in choiceprop])
    Allow_User_rating = forms.ChoiceField(
        required=False,
        widget=forms.CheckboxInput(attrs={
            #'style': 'position: absolute; opacity: 0;'
        }))

    Air_conditioning = forms.ChoiceField(
        required=False,
        widget=forms.CheckboxInput(attrs={
            #'style' :'position: absolute; opacity: 0;'
        }))
    bedding = forms.ChoiceField(
        required=False,
        widget=forms.CheckboxInput(attrs={
            #'style' :'position: absolute; opacity: 0;'
        }))
    heating = forms.ChoiceField(
        required=False,
        widget=forms.CheckboxInput(attrs={
            #'style' :'position: absolute; opacity: 0;'
        }))
    garrage = forms.ChoiceField(
        required=False,
        widget=forms.CheckboxInput(attrs={
            #'style' :'position: absolute; opacity: 0;'
        }))
    Toaster = forms.ChoiceField(
        required=False,
        widget=forms.CheckboxInput(attrs={
            #'style' :'position: absolute; opacity: 0;'
        }))
    Parquet = forms.ChoiceField(
        required=False,
        widget=forms.CheckboxInput(attrs={
            #'style' :'position: absolute; opacity: 0;'
        }))
    Beach = forms.ChoiceField(
        required=False,
        widget=forms.CheckboxInput(attrs={
            #'style' :'position: absolute; opacity: 0;'
        }))
    Garrage = forms.ChoiceField(
        required=False,
        widget=forms.CheckboxInput(attrs={
            #'style' :'position: absolute; opacity: 0;'
        }))
    Cable_TV = forms.ChoiceField(
        required=False,
        widget=forms.CheckboxInput(attrs={
            #'style' :'position: absolute; opacity: 0;'
        }))
    pool = forms.ChoiceField(
        required=False,
        widget=forms.CheckboxInput(attrs={
            #'style' :'position: absolute; opacity: 0;'
        }))
    Balcony = forms.ChoiceField(
        required=False,
        widget=forms.CheckboxInput(attrs={
            #'style' :'position: absolute; opacity: 0;'
        }))
    Hi_Fi = forms.ChoiceField(
        required=False,
        widget=forms.CheckboxInput(attrs={
            #'style' :'position: absolute; opacity: 0;'
        }))
    Bedding = forms.ChoiceField(
        required=False,
        widget=forms.CheckboxInput(attrs={
            #'style' :'position: absolute; opacity: 0;'
        }))
    Microwave = forms.ChoiceField(
        required=False,
        widget=forms.CheckboxInput(attrs={
            #'style' :'position: absolute; opacity: 0;'
        }))
    Toaster = forms.ChoiceField(
        required=False,
        widget=forms.CheckboxInput(attrs={
            #'style' :'position: absolute; opacity: 0;'
        }))
    Balcony = forms.ChoiceField(
        required=False,
        widget=forms.CheckboxInput(attrs={
            #'style' :'position: absolute; opacity: 0;'
        }))
    Smoking_allowed = forms.ChoiceField(
        required=False,
        widget=forms.CheckboxInput(attrs={
            #'style' :'position: absolute; opacity: 0;'
        }))
    Coffee_pot = forms.ChoiceField(
        required=False,
        widget=forms.CheckboxInput(attrs={
            #'style' :'position: absolute; opacity: 0;'
        }))
    Roof_terrace = forms.ChoiceField(
        required=False,
        widget=forms.CheckboxInput(attrs={
            #'style' :'position: absolute; opacity: 0;'
        }))
    iron = forms.ChoiceField(
        required=False,
        widget=forms.CheckboxInput(attrs={
            #'style' :'position: absolute; opacity: 0;'
        }))

    def clean(self):
        cleaned_data = super(PropertyCreate, self).clean()
        name = cleaned_data.get('name')
        email = cleaned_data.get('email')
        message = cleaned_data.get('description')
        if not name and not email and not message:
            raise forms.ValidationError('You have to write something!')
Пример #26
0
def cardsView(request, boardId=None, columnId=None, cardId=None):
    errorsExceptStyle = False  # flag lascia attivo bottone a seguito di un errore
    if request.method == 'GET' and boardId is not None and columnId is not None and cardId is not None:
        board = Board.objects.filter(
            pk=boardId, users=request.user
        )  # se la richiesta e get e non esiste la colonna ritorna notfound
        column = Column.objects.filter(pk=columnId, board=boardId)
        card = Card.objects.filter(pk=cardId, column=columnId)
        if not board.exists() or not column.exists() or not card.exists():
            return HttpResponseNotFound(NOT_FOUND_PAGE)
        # inizializza form con i dati della card
        formModifyCard = FormModifyCard(
            initial={
                'boardId': boardId,
                'columnId': columnId,
                'cardId': cardId,
                'newColumn': column.get(pk=columnId).name,
                'newTitle': card.get(pk=cardId).title,
                'newdescription': card.get(pk=cardId).description,
                'newDateExpired': card.get(pk=cardId).dateExpire,
                'newStoryPoints': card.get(pk=cardId).storyPoints
            })
    elif request.method == 'POST':  # se la richiesta e post modifica dati card o elimina/aggiungi utente board alla card
        userLoged = User.objects.get(username=request.user.username)
        formModifyCard = FormModifyCard(request.POST)
        formModifyCard.setUser(userLoged)
        formAddOrRemoveUser = FormAddOrRemUserCard(request.POST)
        formAddOrRemoveUser.setUser(userLoged)
        if formModifyCard.is_valid(
        ):  # se il form di modifica e valido  allora modifica dati card
            cardId = formModifyCard.cleaned_data.get('cardId')
            newColumn = formModifyCard.cleaned_data.get('newColumn')
            newTitle = formModifyCard.cleaned_data.get('newTitle')
            newdescription = formModifyCard.cleaned_data.get('newdescription')
            newDateExpired = formModifyCard.cleaned_data.get('newDateExpired')
            newStoryPoints = formModifyCard.cleaned_data.get('newStoryPoints')
            card = Card.objects.get(pk=cardId)
            card.title = newTitle
            card.description = newdescription
            card.dateExpire = newDateExpired
            card.storyPoints = newStoryPoints
            card.column = Column.objects.get(name=newColumn)
            card.save()
            return redirect(Card.objects.get(pk=cardId).get_absolute_url())
        elif formAddOrRemoveUser.is_valid(
        ):  # se il form aggiungi utente e valido allora elimina o agginugi utente
            cardId = formAddOrRemoveUser.cleaned_data.get('cardId')
            userId = formAddOrRemoveUser.cleaned_data.get('userId')
            userAdded = User.objects.get(pk=userId)
            if not Card.objects.filter(users=userAdded, pk=cardId).exists(
            ):  # se l utente non fa parte  della card aggiungilo
                Card.objects.get(pk=cardId).users.add(userAdded)
            else:  # se l utente fa parte della card eliminalo
                Card.objects.get(pk=cardId).users.remove(userAdded)
            return redirect(Card.objects.get(pk=cardId).get_absolute_url())
        elif '*not_found' in str(
                formModifyCard.errors) and '*not_found' not in str(
                    formAddOrRemoveUser.errors):
            boardId = formAddOrRemoveUser.cleaned_data.get('boardId')
            columnId = formAddOrRemoveUser.cleaned_data.get('columnId')
            cardId = formAddOrRemoveUser.cleaned_data.get('cardId')

        elif '*not_found' not in str(
                formModifyCard.errors) and '*not_found' in str(
                    formAddOrRemoveUser.errors):
            errorsExceptStyle = True  # se l errore proviene da modifiy card ma non e un notfund lascia il testo modificabile all'utente
            boardId = formModifyCard.cleaned_data.get('boardId')
            columnId = formModifyCard.cleaned_data.get('columnId')
            cardId = formModifyCard.cleaned_data.get('cardId')
            formModifyCard.fields['newTitle'].widget = forms.TextInput(
                attrs={'class': 'field'})
            formModifyCard.fields['newColumn'].widget = forms.TextInput(
                attrs={'class': 'field'})
            formModifyCard.fields['newdescription'].widget = forms.Textarea(
                attrs={'class': 'field'})
            formModifyCard.fields['newDateExpired'].widget = forms.DateInput(
                attrs={
                    'id': 'datepicker',
                    'class': 'field'
                })
            formModifyCard.fields['newStoryPoints'].widget = forms.NumberInput(
                attrs={'class': 'field'})
            formModifyCard.fields['checkbox'].widget = forms.CheckboxInput(
                attrs={
                    'name': 'onoffswitch',
                    'class': 'onoffswitch-checkbox',
                    'id': 'myonoffswitch',
                    'checked': 'true',
                    'onclick': MODIFY_ACTIVATE_CARD
                })
        else:
            return HttpResponseNotFound(NOT_FOUND_PAGE)
    else:
        return HttpResponseNotFound(NOT_FOUND_PAGE)
    formListAdd = []
    formListDel = []
    for user in User.objects.all(
    ):  # creazione struttura utenti contenente dati e form agiung/elimina utente
        form = FormAddOrRemUserCard(
            initial={
                'boardId': boardId,
                'columnId': columnId,
                'cardId': cardId,
                'userId': user.pk
            })
        dict = {'user': user, 'form': form}
        if Board.objects.filter(pk=boardId,
                                users=user).exists() and Card.objects.filter(
                                    users=user, pk=cardId).exists():
            formListDel.append(dict)
        elif Board.objects.filter(
                pk=boardId, users=user).exists() and not Card.objects.filter(
                    users=user, pk=cardId).exists():
            formListAdd.append(dict)
    return render(
        request, 'cardetail.html', {
            'board': Board.objects.get(pk=boardId),
            'column': Column.objects.get(pk=columnId),
            'card': Card.objects.get(pk=cardId),
            'formModify': formModifyCard,
            'formListDel': formListDel,
            'formListAdd': formListAdd,
            'errorsexcept': errorsExceptStyle
        })
Пример #27
0
class PrepaidStartForm(PrepaidForm):
    helper = FormHelper()
    submit = Submit('activate', _(u'Activate'))
    helper.add_input(submit)

    username = forms.RegexField(
        regex=r'^\w+$',
        max_length=30,
        widget=forms.TextInput(attrs=attrs_dict),
        label=_(u"Username"),
        error_messages={
            'invalid':
            _(u"This value must contain only letters, numbers and underscores."
              )
        })
    email = forms.EmailField(label=_(u"Email address"), required=False)
    password1 = forms.CharField(widget=forms.PasswordInput(attrs=attrs_dict,
                                                           render_value=False),
                                label=_(u"Password"))
    password2 = forms.CharField(widget=forms.PasswordInput(attrs=attrs_dict,
                                                           render_value=False),
                                label=_(u"Password (again)"))
    tos = forms.BooleanField(
        widget=forms.CheckboxInput(attrs=attrs_dict),
        label=_(u'I have read and agree to the Terms of Service'),
        error_messages={
            'required': _(u"You must agree to the terms to register")
        })
    first_name = forms.CharField(label=_(u"first name"),
                                 max_length=30,
                                 required=False,
                                 widget=forms.TextInput())
    last_name = forms.CharField(label=_(u"last name"),
                                max_length=30,
                                required=False,
                                widget=forms.TextInput())

    detail_help = _(u'Note. An optional field to fill.')
    email_help = _(
        u'Note. Your email address will not show anyone else. If you do not fill in this field, and forget your password you can not recover it.'
    )
    password_help = _(
        u'From 6 to 20 characters, only letters and numbers. Note. Your password will not be shown to anyone else.'
    )
    layout = Layout(
        Fieldset(
            u'',
            'prnumber',
            'prcode',
        ),
        Fieldset(
            u'',
            'username',
            Row('password1', 'password2'),
            HTML(password_help),
        ),

        # second fieldset shows the contact info
        Fieldset(
            _(u'Additional Information'),
            HTML(detail_help),
            'email',
            HTML(email_help),
            'first_name',
            'last_name',
        ),
        Fieldset(
            u'',
            'tos',
        ))

    helper.add_layout(layout)

    def __init__(self, request, *args, **kwargs):
        super(PrepaidStartForm, self).__init__(*args, **kwargs)
        self.user = request.user
        self.ip = request.META['REMOTE_ADDR']
        self.user_exits = True

    def clean_username(self):
        """
        Validate that the username is alphanumeric and is not already
        in use.

        """
        try:
            user = User.objects.get(
                username__iexact=self.cleaned_data['username'])
        except User.DoesNotExist:
            return self.cleaned_data['username']
        self.user_exits = False
        raise forms.ValidationError(
            _(u"A user with that username already exists."))

    @transaction.commit_on_success
    def save_prepaid(self, card):
        try:
            #log.debug('email({0})'.format(self.data.get('email')))
            new_user = User.objects.create_user(self.data.get('username'), '',
                                                self.data.get('password1'))
            new_user.is_active = True
            user_group = Group.objects.get(name="user")
            new_user.groups.add(user_group)
            new_user.save()
            new_endpoint = Endpoint.objects.create_endpoint(
                new_user, self.data.get('prnumber'))
            #

            bal = Balance.objects.get(
                accountcode__username__exact=self.data.get('username'))
            pay_date = datetime.datetime.now()
            name = 'add:::lincom3000:::prepaid:::{0}'.format(card.pk)
            comments = 'Added Start Paskage'
            method = 'from site prepaid'

            code = "{0}{1}{2}".format(name, comments, method)
            mcode = hashlib.md5()
            mcode.update(code.upper())

            temp_txt = "".join([str(random.randint(0, 9)) for i in range(20)])
            pay_transaction_id = "{0}X{1}".format(int(time.time()), temp_txt)
            up_ball = Balance.objects.filter(
                accountcode__username__exact=self.data.get('username')).update(
                    cash=F('cash') + card.start_balance)
            #log.debug("Prepaid enabled {0}".format(card.enabled))
            b = BalanceHistory.objects.create(
                name=name,
                accountcode=bal,
                site=bal.site,
                pay_date=pay_date,
                method=method,
                amount=Decimal(card.start_balance),
                transaction_id=pay_transaction_id,
                details=comments,
                reason_code=mcode.hexdigest())
            b.success = True
            b.save()
            card.enabled = True
            card.save()
            return new_endpoint
        except:
            #log.error(e)
            #transaction.rollback()
            history = PrepaidLog.objects.create_history(
                self.ip,
                self.data.get("prnumber"),
                code=self.data.get("prcode"),
                st=4,
                nt=2)
            return False

    def clean(self):
        fl_error = False
        nt = 3
        st = 4
        log.debug("len username: {0} user_exits:{1} tos:{2}".format(
            self.data.get('username'), self.user_exits, self.data.get('tos')))

        if self.user_exits and self.data.get('username') is not None and len(
                self.data.get('username')) > 0 and self.data.get(
                    'tos') is not None:
            if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data:
                if self.cleaned_data['password1'] != self.cleaned_data[
                        'password2']:
                    raise forms.ValidationError(
                        _(u"The two password fields didn't match."))
                else:
                    try:
                        #log.debug("number: {0} (user:{1}) ip: {2}".format(self.data.get("prnumber"), self.user, self.ip))
                        prc = Prepaid.objects.get(
                            num_prepaid__iexact=self.data.get("prnumber"))
                    except Prepaid.DoesNotExist:
                        #log.error("prnumber: {0} (user:{1}) ip: {2}".format(self.data.get("prnumber"), self.user, self.ip))
                        history = PrepaidLog.objects.create_history(
                            self.ip, self.data.get("prnumber"))
                        #log.error(history.st)
                        raise forms.ValidationError(
                            _(u"Incorrect number or the code of the card."))
                    try:
                        #log.debug("number: {0} code:{3} (user:{1}) ip: {2}".format(self.data.get("prnumber"), self.user, self.ip, self.data.get("prcode")))
                        card = Prepaid.objects.is_card(
                            self.data.get("prnumber"), self.data.get("prcode"))
                        #log.debug("card: {0}".format(card))
                        if card:
                            if card.enabled:
                                st = 3
                                nt = card.nt
                                fl_error = True
                            elif card.is_valid:
                                st = 1
                                nt = card.nt
                                fl_error = True
                            elif card.nt == 2:

                                log.debug("RUN save_prepaid")
                                new_endpoint = self.save_prepaid(card)
                                if new_endpoint:
                                    nt = card.nt
                                    st = 5
                                else:
                                    raise forms.ValidationError(
                                        _(u"System error no activate prepaid card!"
                                          ))
                            else:
                                st = 6
                                nt = card.nt
                                fl_error = True
                        else:
                            st = 2
                            fl_error = True
                    except:
                        #log.error("number: {0} (user:{1}) ip: {2}".format(self.data.get("prnumber"), self.user, self.ip))
                        #raise forms.ValidationError(_("System error no activate prepaid card!"))
                        raise forms.ValidationError(
                            _(u"Incorrect number or the code of the card."))
                    history = PrepaidLog.objects.create_history(
                        self.ip,
                        self.data.get("prnumber"),
                        code=self.data.get("prcode"),
                        st=st,
                        nt=nt)
                    if fl_error:
                        raise forms.ValidationError(
                            _(u"Incorrect number or the code of the card."))
            return self.cleaned_data
Пример #28
0
from django.utils.translation import ugettext

ACTION_CHECKBOX_NAME = '_selected_action'


class ActionForm(forms.Form):
    action = forms.ChoiceField(label=_('Action:'))
    select_across = forms.BooleanField(
        label='',
        required=False,
        initial=0,
        widget=forms.HiddenInput({'class': 'select-across'}),
    )


checkbox = forms.CheckboxInput({'class': 'action-select'}, lambda value: False)


class AdminForm(object):
    def __init__(self,
                 form,
                 fieldsets,
                 prepopulated_fields,
                 readonly_fields=None,
                 model_admin=None):
        self.form, self.fieldsets = form, fieldsets
        self.prepopulated_fields = [{
            'field':
            form[field_name],
            'dependencies': [form[f] for f in dependencies]
        } for field_name, dependencies in prepopulated_fields.items()]
Пример #29
0
class SearchHousesForm(forms.Form):
    country = forms.CharField(
        required=False,
        widget=forms.TextInput(attrs={
            'name': 'country',
            'required': False,
            'placeholder': _('Country'),
            'title': _('Choice country for search'),
            'maxlength': 30,
            'list': 'countries',
            'class': 'form-control mb-2'
        })
    )

    city = forms.CharField(
        required=False,
        widget=forms.TextInput(attrs={
            'name': 'city',
            'required': False,
            'placeholder': _('City'),
            'title': _('Enter city name for search'),
            'maxlength': 40,
            'class': 'form-control mb-2'
        })
    )

    type = forms.MultipleChoiceField(
        required=False,
        choices=House.HOUSE_TYPE,
        widget=forms.CheckboxSelectMultiple(attrs={
            'name': 'type',
            'required': False,
            'checked': True,
            'title': _('Choice house-types for search'),
        })
    )

    req_max_price = 100
    # House.objects.aggregate(Max('price'))['price__max']

    min_price = forms.DecimalField(
        label='From',
        required=False,
        initial=0.00,
        widget=forms.NumberInput(attrs={
            'name': 'min_price',
            'required': False,
            'title': _('Enter minimum price'),
            'min': 0,
            'max': req_max_price,
            'class': 'form-control'
        })
    )
    max_price = forms.DecimalField(
        label='To',
        required=False,
        initial=req_max_price,
        widget=forms.NumberInput(attrs={
            'name': 'max_price',
            'required': False,
            'title': _('Enter maximum price'),
            'min': 0,
            'max': req_max_price,
            'class': 'form-control'
        })
    )
    rooms = forms.IntegerField(
        required=False,
        widget=forms.NumberInput(attrs={
            'name': 'rooms',
            'required': False,
            'placeholder': '1',
            'title': _('Enter rooms count'),
            'min': 1,
            'max': 100,
            'class': 'form-control'
        })
    )
    # House.objects.aggregate(Max('rooms'))['rooms__max'],
    sleeper = forms.IntegerField(
        required=False,
        widget=forms.NumberInput(attrs={
            'name': 'sleeper',
            'required': False,
            'placeholder': '1',
            'title': _('Enter sleeper count'),
            'min': 1,
            'max': 100,
            'class': 'form-control'
        })

    )
    # House.objects.aggregate(Max('sleeper'))['sleeper__max'],
    active = forms.BooleanField(
        label='Only active',
        required=False,
        initial=True,
        widget=forms.CheckboxInput(attrs={
            'name': 'active',
            'required': False,
            'title': _('Search only active advertisement')
        })
    )
    #
    public = forms.DateField(
        required=False,
        initial=date(2018, 1, 1),
        widget=forms.SelectDateWidget(
            years=range(2017, datetime.now().year + 1),
            attrs={

            'name': 'public',
            'required': False,
                'title': _('Search advertisement populated after this date'),
            'class': 'custom-select col-3'
        })

    )

    text = forms.CharField(
        required=False,
        widget=forms.HiddenInput(attrs={
            'name': 'text',
            'required': False,
            'id': 'hide-text',
        })

    )

    sort = forms.ChoiceField(
        choices=SORTED_TYPE,
        required=False,
        widget=forms.Select(attrs={
            'name': 'sort',
            'required': False,
            'class': 'select_sort pull-right text-right',
            'title': _('Select sorting option'),
        })
    )

    def get_only_full(self):
        """Очистка списка значений полей от пустых полей"""
        dict = self.cleaned_data.copy()

        for key in self.cleaned_data:
            if not (dict[key]) and key != 'type':
                del dict[key]
        return dict
Пример #30
0
class DeviceForm(forms.ModelForm):
    attrs = {'class': 'form-control'}
    netname = forms.CharField(widget=forms.TextInput(attrs=attrs))
    comment = forms.CharField(required=False,
                              widget=forms.Textarea(attrs=attrs))
    status = forms.ChoiceField(widget=forms.Select(attrs=attrs),
                               choices=Device.STATUSES)
    store_entry = forms.ModelChoiceField(required=False,
                                         queryset=Entry.objects.none(),
                                         widget=forms.Select(attrs=attrs))
    community = forms.CharField(required=False,
                                widget=forms.TextInput(attrs=attrs))
    version = forms.CharField(required=False,
                              widget=forms.TextInput(attrs=attrs))
    type = forms.ChoiceField(widget=forms.Select(attrs=attrs),
                             choices=DEVICE_TYPES,
                             required=True)
    is_managed = forms.BooleanField(widget=forms.CheckboxInput(),
                                    required=False)
    datacenter = forms.ModelChoiceField(
        required=False,
        widget=forms.Select(attrs=attrs),
        queryset=common_models.Datacenter.objects.all().prefetch_related(
            'city'))  # .order_by('city__name', 'address'
    management_net = forms.ModelChoiceField(required=False,
                                            widget=forms.Select(attrs=attrs),
                                            queryset=Net.objects.none())

    rack = forms.ModelChoiceField(
        required=False,
        queryset=common_models.Rack.objects.all().order_by('location'),
        widget=forms.Select(attrs=attrs))
    rack_placement = forms.ChoiceField(required=True,
                                       choices=Device.RACK_PLACEMENT_CHOICES,
                                       widget=forms.Select(attrs=attrs))
    whole_rack_depth = forms.BooleanField(required=False,
                                          widget=forms.CheckboxInput())
    start_unit = forms.IntegerField(required=False,
                                    widget=forms.NumberInput(attrs=attrs))

    class Meta:
        model = Device
        fields = [
            'netname',
            'comment',
            'type',
            'store_entry',
            'status',
            'management_net',
            'community',
            'datacenter',
            'version',
            'is_managed',
            'whole_rack_depth',
            'rack',
            'rack_placement',
            'start_unit',
        ]

    def clean(self):
        if self.cleaned_data.get('netname') and 'netname' in self._errors:
            del self._errors['netname']
        return self.cleaned_data

    def clean_start_unit(self):
        start_unit = self.cleaned_data['start_unit']

        if not start_unit:
            return start_unit

        rack = self.cleaned_data['rack']
        side = self.cleaned_data['rack_placement']

        store_entry = self.cleaned_data['store_entry']
        if not store_entry:
            raise forms.ValidationError('Требуется указание складского юнита')

        if not rack:
            raise forms.ValidationError(
                'Если указан юнит, необходимо указать и стойку')

        if not store_entry.unit_height:
            raise forms.ValidationError('Не задана высота %s' % store_entry)

        end_unit = start_unit + store_entry.unit_height - 1

        need_whole_rack_depth = self.cleaned_data['whole_rack_depth']

        if not rack.can_accommodate(
                start_unit=start_unit,
                end_unit=end_unit,
                side=side,
                device=self.instance,
                need_whole_depth=need_whole_rack_depth,
        ):
            raise forms.ValidationError(
                'Невозможно разместить девайс в этом юните')

        return start_unit