Exemplo n.º 1
0
class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    genre = models.CharField(max_length=10,
                             verbose_name="GENRE",
                             choices=GENRE,
                             default="H")
    #status = models.CharField(max_length=50, verbose_name="Expérience", choices=EXPERIENCE)
    experence = models.CharField(max_length=50, choices=EXPERIENCE)
    wht = PhoneNumberField(
        help_text="+225xxxxxxxx", verbose_name="Contact WhatsApp"
    )  # PhoneNumber.from_string(phone_number=raw_phone, region='CI').as_e164
    pays = CountryField(blank_label='(Préciser Le Pays)')
    ville = models.CharField(max_length=255)
    langages = models.ManyToManyField(Langage,
                                      verbose_name="Preciser vos Langages")
    bio = models.TextField(blank=True, null=True)
    avatar = models.ImageField(upload_to="upload_avatar",
                               blank=True,
                               null=True)
    profile = models.ImageField(upload_to="upload_profile",
                                blank=True,
                                null=True)
    facebook = models.CharField(max_length=255, blank=True)
    twitter = models.CharField(max_length=255, blank=True)
    add_le = models.DateTimeField(auto_now_add=True)
    update_le = models.DateTimeField(auto_now=True)

    # active = models.BooleanField(default=False)

    def __str__(self):
        if self.user.last_name or self.user.first_name:
            return '%s %s (%s)' % (self.user.last_name, self.user.first_name,
                                   self.experence)
        else:
            return self.user.username

    def get_absolute_url(self):
        return reverse('abonne:detail', args=[self.pk])

    class Meta:
        ordering = ('-add_le', '-update_le')

    def Avatar(self):
        if self.avatar:
            return mark_safe(
                '<img src="%s" style="width: 45px; height:45px;" />' %
                self.avatar.url)
        else:
            return "Aucune photo"

    Avatar.short_description = 'Avatar'

    def Profile(self):
        if self.profile:
            return mark_safe(
                '<img src="%s" style="width: 45px; height:45px;" />' %
                self.profile.url)
        else:
            return "Aucun Profile"

    Profile.short_description = 'Profile'

    class Meta:
        verbose_name_plural = "ABONNES"
        verbose_name = "abonne"
Exemplo n.º 2
0
class StaffProfileAdminForm(forms.ModelForm):
    """
    Form used when managing StaffProfile objects
    """
    first_name = forms.CharField(label=_('First Name'), required=True)
    last_name = forms.CharField(label=_('Last Name'), required=True)
    id_number = forms.CharField(label=_('ID Number'), required=True)
    nhif = forms.CharField(label=_('NHIF'), required=False)
    nssf = forms.CharField(label=_('NSSF'), required=False)
    pin_number = forms.CharField(label=_('PIN Number'), required=False)
    emergency_contact_name = forms.CharField(label=_('Emergency Contact Name'),
                                             required=False)
    emergency_contact_relationship = forms.CharField(
        label=_('Emergency Contact Relationship'), required=False)
    emergency_contact_number = PhoneNumberField(
        label=_('Emergency Contact Phone Number'), required=False)

    class Meta:  # pylint: disable=too-few-public-methods
        """
        Class meta options
        """
        model = StaffProfile
        fields = [
            'first_name', 'last_name', 'id_number', 'image', 'phone', 'sex',
            'role', 'nhif', 'nssf', 'pin_number', 'address', 'birthday',
            'leave_days', 'sick_days', 'overtime_allowed', 'start_date',
            'end_date', 'emergency_contact_name', 'emergency_contact_number',
            'emergency_contact_relationship'
        ]

    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('request', None)
        super().__init__(*args, **kwargs)
        if self.instance and self.instance.image:
            self.fields['image'].required = False
        self.helper = FormHelper()
        self.helper.form_tag = True
        self.helper.form_method = 'post'
        self.helper.render_required_fields = True
        self.helper.form_show_labels = True
        self.helper.html5_required = True
        self.helper.form_id = 'staffprofile-form'
        self.helper.layout = Layout(
            Field('first_name', ), Field('last_name', ), Field('image', ),
            Field('phone', ), Field('id_number', ), Field('sex', ),
            Field('role', ), Field('nhif', ), Field('nssf', ),
            Field('pin_number', ), Field('address', ), Field('birthday', ),
            Field('leave_days', ), Field('sick_days', ),
            Field('overtime_allowed', ), Field('start_date', ),
            Field('end_date', ), Field('emergency_contact_name', ),
            Field('emergency_contact_number', ),
            Field('emergency_contact_relationship', ),
            FormActions(
                Submit('submitBtn', _('Submit'), css_class='btn-primary'), ))

    def clean_id_number(self):
        """
        Check if id number is unique
        """
        value = self.cleaned_data.get('id_number')
        # pylint: disable=no-member
        if StaffProfile.objects.exclude(id=self.instance.id).filter(
                data__id_number=value).exists():
            raise forms.ValidationError(_('This id number is already in use.'))
        return value

    def clean_nssf(self):
        """
        Check if NSSF number is unique
        """
        value = self.cleaned_data.get('nssf')
        # pylint: disable=no-member
        if value and StaffProfile.objects.exclude(id=self.instance.id).filter(
                data__nssf=value).exists():
            raise forms.ValidationError(
                _('This NSSF number is already in use.'))
        return value

    def clean_nhif(self):
        """
        Check if NHIF number is unique
        """
        value = self.cleaned_data.get('nhif')
        # pylint: disable=no-member
        if value and StaffProfile.objects.exclude(id=self.instance.id).filter(
                data__nhif=value).exists():
            raise forms.ValidationError(
                _('This NHIF number is already in use.'))
        return value

    def clean_pin_number(self):
        """
        Check if PIN number is unique
        """
        value = self.cleaned_data.get('pin_number')
        # pylint: disable=no-member
        if value and StaffProfile.objects.exclude(id=self.instance.id).filter(
                data__pin_number=value).exists():
            raise forms.ValidationError(
                _('This PIN number is already in use.'))
        return value

    def save(self, commit=True):  # pylint: disable=unused-argument
        """
        Custom save method
        """
        staffprofile = super().save()

        emergency_phone = self.cleaned_data.get('emergency_contact_number')
        if isinstance(emergency_phone, PhoneNumber):
            emergency_phone = emergency_phone.as_e164

        json_data = {
            'id_number':
            self.cleaned_data.get('id_number'),
            'nhif':
            self.cleaned_data.get('nhif'),
            'nssf':
            self.cleaned_data.get('nssf'),
            'pin_number':
            self.cleaned_data.get('pin_number'),
            'emergency_contact_name':
            self.cleaned_data.get('emergency_contact_name'),
            'emergency_contact_relationship':
            self.cleaned_data.get('emergency_contact_relationship'),
            'emergency_contact_number':
            emergency_phone,
        }
        staffprofile.data = json_data
        staffprofile.save()

        user = staffprofile.user
        user.first_name = self.cleaned_data['first_name']
        user.last_name = self.cleaned_data['last_name']
        user.save()
        return staffprofile
Exemplo n.º 3
0
class ClaimForm(forms.Form):
    source = forms.ModelChoiceField(
        label='Name of person or organization',
        queryset=ClaimSource.objects.all(),
        help_text='Can\'t find who you\'re looking for? Click "Add New".',
    )
    source_type = forms.ChoiceField(
        required=False,
        label='Type',
        choices=ClaimSource.SOURCE_TYPE_CHOICES,
        help_text='We prefer claims attributed to specific people. Otherwise, '
        'select "Organization".',
    )
    source_name = forms.CharField(
        required=False,
        label='Name',
        max_length=300,
        help_text='If attributed to a person, please provide their first and '
        'last names.',
    )
    source_title = forms.CharField(
        required=False,
        label='Title',
        max_length=300,
        help_text='Please include the person\'s current title, if known.',
    )
    claimed_on = forms.DateField(
        required=False,
        label='Claimed on',
        widget=DatePickerInput(
            options={
                'todayBtn': "linked",
                'clearBtn': False,
                'endDate': "0d",
                'toggleActive': True,
                'autoclose': True,
            }),
        help_text='Date when the claim was publicly stated, if known.',
    )
    context_description = forms.CharField(
        required=False,
        label='Context',
        max_length=300,
        help_text='Name of the event or description of the context of what was '
        'said.',
    )
    context_url = forms.URLField(
        required=False,
        label='Link',
        max_length=300,
        help_text='If you can, please provide a link to the speech, press '
        'release, video or other material that includes the claim.',
    )
    claim = forms.CharField(
        required=True,
        label='Claim',
        max_length=300,
        help_text='We prefer direct quotes. Otherwise, please accurately '
        'paraphrase what was said.',
    )
    note = forms.CharField(
        required=False,
        label='Extra info',
        help_text='If you can, tell us more about how this was said and what it '
        'means.',
        widget=forms.Textarea,
    )
    submitter_name = forms.CharField(
        required=False,
        label='Your name',
        help_text='First and last names, please.',
    )
    submitter_email = forms.EmailField(
        required=False,
        label='Your email',
        help_text='If you prefer we reach you by email.',
    )
    submitter_phone = PhoneNumberField(
        required=False,
        label='Your email',
        help_text='If you prefer we reach you by email.',
    )

    @property
    def submitter_field_names(self):
        """
        Return a tuple containing the list of ClaimSubmitter fields.
        """
        return (k for k in self.fields.keys() if "submitter_" in k)

    @property
    def has_submitter_data(self):
        """
        Return True of ClaimSubmitter data was submitted through the form.
        """

        if (bool(self.data['submitter_name'])
                or bool(self.data['submitter_phone'])
                or bool(self.data['submitter_email'])):
            return True
        else:
            return False

    def clean(self):
        cleaned_data = super(ClaimForm, self).clean()

        if not bool(cleaned_data.get("source")):
            source = ClaimSource(
                source_type=cleaned_data.get("source_type"),
                name=cleaned_data.get("source_name"),
                title=cleaned_data.get("source_title"),
            )
            source.full_clean()

            cleaned_data['source'] = source

        if self.has_submitter_data:
            submitter = ClaimSubmitter(
                name=cleaned_data.get("submitter_name"),
                email=cleaned_data.get("submitter_email"),
                phone=cleaned_data.get("submitter_phone"),
            )
            submitter.full_clean()
            cleaned_data['submitter'] = submitter
        else:
            cleaned_data['submitter'] = None

        return cleaned_data

    def _clean_submitter_data(self, name, email, phone):
        try:
            submitter = ClaimSubmitter.objects.get(
                name=name,
                email=email,
                phone=phone,
            )
        except ClaimSubmitter.DoesNotExist:
            submitter = ClaimSubmitter(
                name=name,
                email=email,
                phone=phone,
            )
            try:
                submitter.full_clean()
            except ValidationError as err:
                # TODO: override the field names
                raise ValidationError

        return submitter