Esempio n. 1
0
class PersonPostingsForm(BaseUpdateForm):
    edit_fields = [
        ('rank', MembershipPersonRank, False),
        ('role', MembershipPersonRole, False),
        ('title', MembershipPersonTitle, False),
        ('firstciteddate', MembershipPersonFirstCitedDate, False),
        ('lastciteddate', MembershipPersonLastCitedDate, False),
        ('realstart', MembershipPersonRealStart, False),
        ('realend', MembershipPersonRealEnd, False),
        ('startcontext', MembershipPersonStartContext, False),
        ('endcontext', MembershipPersonEndContext, False),
        ('organization', MembershipPersonOrganization, False),
        ('member', MembershipPersonMember, False),
    ]

    clone_sources = {
        'member': 'organization',
    }

    organization = forms.ModelChoiceField(label=_("Organization"),
                                          queryset=Organization.objects.all())
    rank = forms.ModelChoiceField(label=_("Rank"),
                                  queryset=Rank.objects.distinct('value'),
                                  required=False)
    role = forms.ModelChoiceField(label=_("Role"),
                                  queryset=Role.objects.distinct('value'),
                                  required=False)
    title = forms.CharField(label=_("Title"), required=False)
    firstciteddate = ApproximateDateFormField(label=_("Date first cited"),
                                              required=False)
    lastciteddate = ApproximateDateFormField(label=_("Date last cited"),
                                             required=False)
    realstart = forms.BooleanField(label=_("Start date?"))
    realend = forms.BooleanField(label=_("End date?"))
    startcontext = forms.CharField(label=_("Context for start date"),
                                   required=False)
    endcontext = forms.CharField(label=_("Context for end date"),
                                 required=False)

    def __init__(self, *args, **kwargs):
        person_id = kwargs.pop('person_id')

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

        self.fields['member'] = forms.ModelChoiceField(
            queryset=Person.objects.filter(uuid=person_id))

    class Meta:
        model = MembershipPerson
        fields = '__all__'
Esempio n. 2
0
class ViolationBasicsForm(BaseUpdateForm):
    class Meta:
        model = Violation
        fields = '__all__'

    edit_fields = [
        ('startdate', ViolationStartDate, False),
        ('enddate', ViolationEndDate, False),
        ('types', ViolationType, True),
        ('description', ViolationDescription, False),
        ('perpetrator', ViolationPerpetrator, True),
        ('perpetratororganization', ViolationPerpetratorOrganization, True),
        ('perpetratorclassification', ViolationPerpetratorClassification,
         True),
        ('division_id', ViolationDivisionId, False),
    ]

    startdate = ApproximateDateFormField(label=_("Start date"), required=False)
    enddate = ApproximateDateFormField(label=_("End date"), required=False)
    description = forms.CharField(label=_("Description"))
    perpetrator = forms.ModelMultipleChoiceField(label=_("Perpetrator"),
                                                 queryset=Person.objects.all(),
                                                 required=False)
    perpetratororganization = forms.ModelMultipleChoiceField(
        label=_("Perpetrator unit"),
        queryset=Organization.objects.all(),
        required=False)
    division_id = forms.CharField(label=_("Country"), required=False)

    def __init__(self, *args, **kwargs):
        violation_id = kwargs.pop('violation_id', None)

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

        self.fields['perpetratorclassification'] = GetOrCreateChoiceField(
            label=_("Perpetrator classification"),
            queryset=ViolationPerpetratorClassification.objects.all(),
            object_ref_model=self._meta.model,
            form=self,
            field_name='perpetratorclassification',
            object_ref_pk=violation_id,
            required=False)
        self.fields['types'] = GetOrCreateChoiceField(
            label=_("Violation type"),
            queryset=ViolationType.objects.all(),
            object_ref_model=self._meta.model,
            form=self,
            field_name='types',
            object_ref_pk=violation_id)
Esempio n. 3
0
class RemoteWorkshopForm(forms.Form):
    date = ApproximateDateFormField(
        widget=forms.TextInput(attrs={'class': 'compact-input'}))
    city = forms.CharField(
        required=True,
        max_length=200,
        widget=forms.TextInput(attrs={'class': 'compact-input'}))
    country = LazyTypedChoiceField(
        choices=[(None, _('Choose country'))] + list(countries))
    sponsorship = forms.CharField(
        widget=forms.Textarea(attrs={'class': 'compact-input'}))
    coaches = forms.CharField(
        widget=forms.Textarea(attrs={'class': 'compact-input'}))
    tools = forms.CharField(
        widget=forms.Textarea(attrs={'class': 'compact-input'})
    )
    diversity = forms.CharField(
        widget=forms.Textarea(attrs={'class': 'compact-input'})
    )
    additional = forms.CharField(
        widget=forms.Textarea(attrs={'class': 'compact-input'})
    )

    def clean_date(self):
        date = self.cleaned_data.get('date')
        validate_approximatedate(date)
        # Check if the event is in the future
        validate_future_date(date)
        # Check if date is 3 months away
        validate_event_date(date)
        return date

    def get_data_for_saving(self):
        return self.cleaned_data
Esempio n. 4
0
class DatesForm(forms.Form):
    near_future = PrettyDateField(future=True)
    near_past = PrettyDateField(future=False)
    just_a_date = PrettyDateField()
    approximate = ApproximateDateFormField()

    def clean(self):
        self.safe_cleaned_data = self.cleaned_data
        return self.cleaned_data
Esempio n. 5
0
class WorkshopForm(forms.Form):
    date = ApproximateDateFormField(widget=forms.TextInput(
        attrs={'class': 'compact-input'}))
    city = forms.CharField(
        required=True,
        max_length=200,
        widget=forms.TextInput(attrs={'class': 'compact-input'}))
    country = LazyTypedChoiceField(choices=[(None, 'Choose country')] +
                                   list(countries))
    venue = forms.CharField(widget=forms.Textarea(
        attrs={'class': 'compact-input'}))
    sponsorship = forms.CharField(widget=forms.Textarea(
        attrs={'class': 'compact-input'}))
    coaches = forms.CharField(widget=forms.Textarea(
        attrs={'class': 'compact-input'}))
    local_restrictions = forms.CharField(
        required=True, widget=forms.Textarea(attrs={'class': 'compact-input'}))
    safety = forms.CharField(
        required=True, widget=forms.Textarea(attrs={'class': 'compact-input'}))
    diversity = forms.CharField(widget=forms.Textarea(
        attrs={'class': 'compact-input'}))
    additional = forms.CharField(widget=forms.Textarea(
        attrs={'class': 'compact-input'}))
    confirm_covid_19_protocols = forms.BooleanField()

    def clean_date(self):
        date = self.cleaned_data.get('date')
        validate_approximatedate(date)
        # Check if the event is in the future
        validate_future_date(date)
        # Check if date is 3 months away
        validate_event_date(date)
        return date

    def get_data_for_saving(self):
        return self.cleaned_data

    def clean_local_restrictions(self):
        local_restrictions = self.cleaned_data.get('local_restrictions')
        # Check if organizer provides link to government website
        validate_local_restrictions(local_restrictions)
        return local_restrictions
Esempio n. 6
0
class WorkshopForm(forms.Form):
    date = ApproximateDateFormField(widget=forms.TextInput(
        attrs={'class': 'compact-input'}))
    city = forms.CharField(
        required=True,
        max_length=200,
        widget=forms.TextInput(attrs={'class': 'compact-input'}))
    country = LazyTypedChoiceField(choices=[(None, 'Choose country')] +
                                   list(countries))
    venue = forms.CharField(widget=forms.Textarea(
        attrs={'class': 'compact-input'}))
    sponsorship = forms.CharField(widget=forms.Textarea(
        attrs={'class': 'compact-input'}))
    coaches = forms.CharField(widget=forms.Textarea(
        attrs={'class': 'compact-input'}))

    def clean_date(self):
        date = self.cleaned_data.get('date')
        validate_approximatedate(date)
        # TODO: add checking if the event is in the future
        return date

    def get_data_for_saving(self):
        return self.cleaned_data
Esempio n. 7
0
class BasePersonForm(forms.Form):

    STANDING_CHOICES = (
        ('not-sure', _(u"Don’t Know")),
        ('standing', _(u"Yes")),
        ('not-standing', _(u"No")),
    )

    honorific_prefix = forms.CharField(
        label=_("Title / pre-nominal honorific (e.g. Dr, Sir, etc.)"),
        max_length=256,
        required=False,
    )
    name = forms.CharField(
        label=_("Full name"),
        max_length=1024,
    )
    honorific_suffix = forms.CharField(
        label=_("Post-nominal letters (e.g. CBE, DSO, etc.)"),
        max_length=256,
        required=False,
    )
    email = forms.EmailField(
        label=_("Email"),
        max_length=256,
        required=False,
    )
    gender = forms.CharField(
        label=_(u"Gender (e.g. “male”, “female”)"),
        max_length=256,
        required=False,
    )
    birth_date = ApproximateDateFormField(
        label=_("Date of birth (as YYYY-MM-DD or YYYY)"),
        required=False,
    )
    wikipedia_url = forms.URLField(
        label=_("Wikipedia URL"),
        max_length=256,
        required=False,
    )
    homepage_url = forms.URLField(
        label=_("Homepage URL"),
        max_length=256,
        required=False,
    )
    twitter_username = forms.CharField(
        label=_(u"Twitter username (e.g. “democlub”)"),
        max_length=256,
        required=False,
    )
    facebook_personal_url = forms.URLField(
        label=_("Facebook profile URL"),
        max_length=256,
        required=False,
    )
    facebook_page_url = forms.URLField(
        label=_("Facebook page (e.g. for their campaign)"),
        max_length=256,
        required=False,
    )
    linkedin_url = forms.URLField(
        label=_("LinkedIn URL"),
        max_length=256,
        required=False,
    )
    party_ppc_page_url = forms.URLField(
        label=_(u"The party’s candidate page for this person"),
        max_length=256,
        required=False,
    )

    if 'cv' in settings.EXTRA_SIMPLE_FIELDS:
        cv = forms.CharField(required=False,
                             label=_(u"CV or Résumé"),
                             widget=forms.Textarea)

    if 'program' in settings.EXTRA_SIMPLE_FIELDS:
        program = forms.CharField(required=False,
                                  label=_(u"Program"),
                                  widget=forms.Textarea)

    def clean_twitter_username(self):
        # Remove any URL bits around it:
        username = self.cleaned_data['twitter_username'].strip()
        m = re.search('^.*twitter.com/(\w+)', username)
        if m:
            username = m.group(1)
        # If there's a leading '@', strip that off:
        username = re.sub(r'^@', '', username)
        if not re.search(r'^\w*$', username):
            message = _(
                "The Twitter username must only consist of alphanumeric characters or underscore"
            )
            raise ValidationError(message)
        return username

    def check_party_and_constituency_are_selected(self, cleaned_data):
        '''This is called by the clean method of subclasses'''

        for election_data in self.elections_with_fields:
            election = election_data.slug
            election_name = election_data.name

            standing_status = cleaned_data.get('standing_' + election,
                                               'standing')
            if standing_status != 'standing':
                continue

            # Make sure that there is a party selected; we need to do this
            # from the clean method rather than single field validation
            # since the party field that should be checked depends on the
            # selected constituency.
            post_id = cleaned_data['constituency_' + election]
            if not post_id:
                message = _("If you mark the candidate as standing in the "
                            "{election}, you must select a post")
                raise forms.ValidationError(
                    message.format(election=election_name))
            # Check that that post actually exists:
            if not Post.objects.filter(extra__slug=post_id).exists():
                message = _("An unknown post ID '{post_id}' was specified")
                raise forms.ValidationError(message.format(post_id=post_id))
            try:
                party_set = PartySet.objects.get(postextra__slug=post_id)
            except PartySet.DoesNotExist:
                message = _("Could not find parties for the post with ID "
                            "'{post_id}' in the {election}")
                raise forms.ValidationError(
                    message.format(post_id=post_id, election=election_name))
            party_field = 'party_' + party_set.slug + '_' + election
            try:
                party_id = int(cleaned_data[party_field], 10)
            except ValueError:
                party_id = None
            if not Organization.objects.filter(classification='Party',
                                               id=party_id).exists():
                message = _("You must specify a party for the {election}")
                raise forms.ValidationError(
                    message.format(election=election_name))
        return cleaned_data
Esempio n. 8
0
class BasePersonForm(PopItApiMixin, forms.Form):

    STANDING_CHOICES = (
        ('not-sure', _(u"Don’t Know")),
        ('standing', _(u"Yes")),
        ('not-standing', _(u"No")),
    )

    honorific_prefix = forms.CharField(
        label=_("Title / pre-nominal honorific (e.g. Dr, Sir, etc.)"),
        max_length=256,
        required=False,
    )
    name = forms.CharField(
        label=_("Full name"),
        max_length=1024,
    )
    honorific_suffix = forms.CharField(
        label=_("Post-nominal letters (e.g. CBE, DSO, etc.)"),
        max_length=256,
        required=False,
    )
    email = forms.EmailField(
        label=_("Email"),
        max_length=256,
        required=False,
    )
    gender = forms.CharField(
        label=_(u"Gender (e.g. “male”, “female”)"),
        max_length=256,
        required=False,
    )
    birth_date = ApproximateDateFormField(
        label=_("Date of birth (as YYYY-MM-DD or YYYY)"),
        required=False,
    )
    wikipedia_url = forms.URLField(
        label=_("Wikipedia URL"),
        max_length=256,
        required=False,
    )
    homepage_url = forms.URLField(
        label=_("Homepage URL"),
        max_length=256,
        required=False,
    )
    twitter_username = forms.CharField(
        label=_(u"Twitter username (e.g. “democlub”)"),
        max_length=256,
        required=False,
    )
    facebook_personal_url = forms.URLField(
        label=_("Facebook profile URL"),
        max_length=256,
        required=False,
    )
    facebook_page_url = forms.URLField(
        label=_("Facebook page (e.g. for their campaign)"),
        max_length=256,
        required=False,
    )
    linkedin_url = forms.URLField(
        label=_("LinkedIn URL"),
        max_length=256,
        required=False,
    )
    party_ppc_page_url = forms.URLField(
        label=_(u"The party’s candidate page for this person"),
        max_length=256,
        required=False,
    )

    def clean_twitter_username(self):
        # Remove any URL bits around it:
        username = self.cleaned_data['twitter_username'].strip()
        m = re.search('^.*twitter.com/(\w+)', username)
        if m:
            username = m.group(1)
        # If there's a leading '@', strip that off:
        username = re.sub(r'^@', '', username)
        if not re.search(r'^\w*$', username):
            message = _("The Twitter username must only consist of alphanumeric characters or underscore")
            raise ValidationError(message)
        return username

    def check_party_and_constituency_are_selected(self, cleaned_data):
        '''This is called by the clean method of subclasses'''

        for election, election_data in self.elections_with_fields:
            election_name = election_data['name']

            standing_status = cleaned_data.get(
                'standing_' + election, 'standing'
            )
            if standing_status != 'standing':
               continue

            # Make sure that there is a party selected; we need to do this
            # from the clean method rather than single field validation
            # since the party field that should be checked depends on the
            # selected constituency.
            post_id = cleaned_data['constituency_' + election]
            if not post_id:
                message = _("If you mark the candidate as standing in the "
                            "{election}, you must select a post")
                raise forms.ValidationError(message.format(
                    election=election_name
                ))
            # Check that that post actually exists:
            try:
                get_post_cached(self.api, post_id)
            except UnknownPostException:
                message = _("An unknown post ID '{post_id}' was specified")
                raise forms.ValidationError(
                    message.format(post_id=post_id)
                )
            party_set = AREA_POST_DATA.post_id_to_party_set(post_id)
            if not party_set:
                message = _("Could not find parties for the post with ID "
                            "'{post_id}' in the {election}")
                raise forms.ValidationError(
                    message.format(post_id=post_id, election=election_name)
                )
            party_field = 'party_' + party_set + '_' + election
            party_id = cleaned_data[party_field]
            if party_id not in PARTY_DATA.party_id_to_name:
                message = _("You must specify a party for the {election}")
                raise forms.ValidationError(message.format(election=election_name))
        return cleaned_data
Esempio n. 9
0
class ReleaseForm(ModelForm):
    class Meta:
        model = Release
        fields = (
            'name',
            'label',
            'releasetype',
            'totaltracks',
            'release_country',
            'catalognumber',
            'description',
            'main_image',
            'releasedate_approx',
            'd_tags',
            'barcode',
        )

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

        self.user = kwargs['initial']['user']
        self.instance = kwargs['instance']
        self.label = kwargs.pop('label', None)

        super(ReleaseForm, self).__init__(*args, **kwargs)
        """
        Prototype function, set some fields to readonly depending on permissions
        """
        if not self.user.has_perm("alibrary.admin_release", self.instance):
            self.fields['catalognumber'].widget.attrs['readonly'] = 'readonly'

        self.helper = FormHelper()
        self.helper.form_id = "id_feedback_form_%s" % 'asd'
        self.helper.form_class = 'form-horizontal'
        self.helper.form_method = 'post'
        self.helper.form_action = ''
        self.helper.form_tag = False

        # TODO: this is very ugly!
        unknown_label, c = Label.objects.get_or_create(slug='unknown')
        if c:
            Label.objects.filter(pk=unknown_label.pk).update(
                name='Unknown label', slug='unknown')

        noton_label, c = Label.objects.get_or_create(
            slug='not-on-label-self-released')
        if c:
            Label.objects.filter(pk=unknown_label.pk).update(
                name='Not on Label / Self Released',
                slug='not-on-label-self-released')

        base_layout = Fieldset(
            _('General'),
            LookupField('name', css_class='input-xlarge'),
            LookupField('releasetype', css_class='input-xlarge'),
            LookupField('totaltracks', css_class='input-xlarge'),
        )

        catalog_layout = Fieldset(
            _('Label/Catalog'),
            LookupField('label', css_class='input-xlarge'),
            HTML(
                """<ul class="horizontal unstyled clearfix action label-select">
                <li><a data-label="%s" data-label_id="%s" href="#"><i class="icon-double-angle-right"></i> %s</a></li>
                <li><a data-label="%s" data-label_id="%s" href="#"><i class="icon-double-angle-right"></i> %s</a></li>
            </ul>""" %
                (unknown_label.name, unknown_label.pk, unknown_label.name,
                 noton_label.name, noton_label.pk, noton_label.name)),
            LookupField('catalognumber', css_class='input-xlarge'),
            LookupField('release_country', css_class='input-xlarge'),
            LookupField('releasedate_approx', css_class='input-xlarge'),
        )

        meta_layout = Fieldset(
            'Meta',
            LookupField('description', css_class='input-xxlarge'),
            LookupImageField('main_image', ),
            LookupField('remote_image', ),
        )

        tagging_layout = Fieldset(
            'Tags',
            LookupField('d_tags'),
        )

        identifiers_layout = Fieldset(
            _('Identifiers'),
            LookupField('barcode', css_class='input-xlarge'),
        )

        layout = Layout(
            base_layout,
            HTML('<div id="artist_relation_container"></div>'),
            meta_layout,
            catalog_layout,
            identifiers_layout,
            tagging_layout,
        )

        self.helper.add_layout(layout)

    main_image = forms.Field(widget=AdvancedFileInput(), required=False)
    remote_image = forms.URLField(required=False)
    releasedate_approx = ApproximateDateFormField(label="Releasedate",
                                                  required=False)
    d_tags = TagField(widget=TagAutocompleteTagIt(max_tags=9),
                      required=False,
                      label=_('Tags'))

    label = search_fields.AutocompleteField('alibrary.label',
                                            allow_new=True,
                                            required=False)

    description = forms.CharField(widget=forms.Textarea(), required=False)

    # TODO: rework clean function
    def clean(self, *args, **kwargs):

        cd = super(ReleaseForm, self).clean()

        try:
            label = cd['label']
            if not label.pk:
                label.creator = self.user
                label.save()
        except:
            pass

        if cd.get('remote_image', None):
            remote_file = get_file_from_url(cd['remote_image'])
            if remote_file:
                cd['main_image'] = remote_file

        return cd

    def save(self, *args, **kwargs):
        return super(ReleaseForm, self).save(*args, **kwargs)
Esempio n. 10
0
class ReleaseForm(ModelForm):
    class Meta:
        model = Release
        fields = ('name', 'label', 'releasetype', 'release_country',
                  'catalognumber', 'description', 'main_image',
                  'releasedate_approx', 'd_tags')

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

        self.user = kwargs['initial']['user']
        self.instance = kwargs['instance']

        print self.instance

        print self.user.has_perm("alibrary.edit_release")
        print self.user.has_perm("alibrary.admin_release", self.instance)

        self.label = kwargs.pop('label', None)

        super(ReleaseForm, self).__init__(*args, **kwargs)
        """
        Prototype function, set some fields to readonly depending on permissions
        """
        if not self.user.has_perm("alibrary.admin_release", self.instance):
            self.fields['catalognumber'].widget.attrs['readonly'] = 'readonly'

        self.helper = FormHelper()
        self.helper.form_id = "id_feedback_form_%s" % 'asd'
        self.helper.form_class = 'form-horizontal'
        self.helper.form_method = 'post'
        self.helper.form_action = ''
        self.helper.form_tag = False

        base_layout = Fieldset(
            _('General'),
            #Div(HTML('<h4>%s</h4><p>%s</p>' % (_('Bulk Edit'), _('Choose Artist name and/or license to apply on every track.'))), css_class='form-help'),
            LookupField('name', css_class='input-xlarge'),
            LookupField('releasetype', css_class='input-xlarge'),
        )

        artist_layout = Fieldset(
            _('Artist(s)'),
            Field('extra_artists', css_class='input-xlarge'),
        )

        catalog_layout = Fieldset(
            _('Label/Catalog'),
            LookupField('label', css_class='input-xlarge'),
            HTML("""<ul class="action label-select">
                    <li><a data-label="Unknown 22" href="#">Unknown label</a></li>
                    <li><a data-label="Not on label" href="#">Not on label</a></li>
                </ul>"""),
            LookupField('catalognumber', css_class='input-xlarge'),
            LookupField('release_country', css_class='input-xlarge'),
            # LookupField('releasedate', css_class='input-xlarge'),
            LookupField('releasedate_approx', css_class='input-xlarge'),
        )

        image_layout = Fieldset(
            'Meta',
            LookupField('description', css_class='input-xxlarge'),
            'main_image',
        )

        tagging_layout = Fieldset(
            'Tags',
            'd_tags',
        )

        layout = Layout(
            #ACTION_LAYOUT,
            base_layout,
            # artist_layout,
            image_layout,
            catalog_layout,
            tagging_layout,
            #ACTION_LAYOUT,
        )

        self.helper.add_layout(layout)

    main_image = forms.Field(widget=FileInput(), required=False)
    #releasedate = forms.DateField(required=False,widget=forms.DateInput(format = '%Y-%m-%d'), input_formats=('%Y-%m-%d',))
    releasedate_approx = ApproximateDateFormField(label="Releasedate",
                                                  required=False)
    d_tags = TagField(widget=TagAutocompleteTagIt(max_tags=9),
                      required=False,
                      label=_('Tags'))
    name = forms.CharField(
        widget=selectable.AutoCompleteWidget(ReleaseNameLookup), required=True)
    label = selectable.AutoCompleteSelectField(ReleaseLabelLookup,
                                               allow_new=True,
                                               required=False)
    description = forms.CharField(widget=PagedownWidget(),
                                  required=False,
                                  help_text="Markdown enabled text")

    #extra_artists = selectable.AutoComboboxSelectMultipleField(ArtistLookup, required=False)

    # TODO: rework clean function
    def clean(self, *args, **kwargs):

        cd = super(ReleaseForm, self).clean()

        print cd

        label = cd['label']
        try:
            if not label.pk:
                print "SEEMS TO BE NEW ONE..."
                label.save()
        except:
            pass

        if 'main_image' in cd and cd['main_image'] != None:
            print "IMAGE SAFIX!!"
            try:
                ui = cd['main_image']
                dj_file = DjangoFile(open(ui.temporary_file_path()),
                                     name='cover.jpg')
                cd['main_image'], created = Image.objects.get_or_create(
                    original_filename='cover_%s.jpg' % self.instance.pk,
                    file=dj_file,
                    folder=self.instance.folder,
                    is_public=True)
            except Exception, e:
                print e
                pass

        else: