Beispiel #1
0
    def clean(self, value):
        """
        Only the default language should be required.
        """
        clean_data = []
        errors = ErrorList()
        if not value or isinstance(value, (list, tuple)):
            if not value or not [v for v in value if v not in validators.EMPTY_VALUES]:
                if self.required:
                    raise ValidationError(self.error_messages['required'])
                else:
                    return self.compress([])
        else:
            raise ValidationError(self.error_messages['invalid'])
        for i, field in enumerate(self.fields):
            try:
                field_value = value[i]
            except IndexError:
                field_value = None
            if i == 0 and self.required and field_value in validators.EMPTY_VALUES:
                raise ValidationError(self.error_messages['required'])
            try:
                clean_data.append(field.clean(field_value))
            except ValidationError as e:
                # Collect all validation errors in a single list, which we'll
                # raise at the end of clean(), rather than raising a single
                # exception for the first error we encounter.
                errors.extend(e.messages)
        if errors:
            raise ValidationError(errors)

        out = self.compress(clean_data)
        self.validate(out)
        self.run_validators(out)
        return out
Beispiel #2
0
def _login_view(request):
    """Standard Django login plus lowercases the login email(username)"""
    if request.method == "POST":
        redirect_to = request.REQUEST.get('next', False)

        form = LoginForm(request.POST)
        if form.is_valid():
            new_user = authenticate(
                username=form.cleaned_data['email'].lower(),
                password=form.cleaned_data['password']
            )
            if new_user and new_user.is_active:
                login(request, new_user)
                if redirect_to:
                    return HttpResponseRedirect(redirect_to)
                else:
                    return HttpResponseRedirect(reverse("seed:home"))
            else:
                errors = ErrorList()
                errors = form._errors.setdefault(NON_FIELD_ERRORS, errors)
                errors.append('Username and/or password were invalid.')
    else:
        form = LoginForm()

    return locals()
Beispiel #3
0
    def clean(self, value):
        # Get the value
        # Totally replaced validation.
        clean_data = []
        errors = ErrorList()

        # Only the visible field is required.
        radio_value = value[0]
        field_visible = [False] * len(self.fields)
        field_visible[0] = True
        field_visible[self.url_type_registry.index(radio_value) + 1] = True

        # The validators only fire for visible fields.
        for i, field in enumerate(self.fields):
            try:
                field_value = value[i]
            except IndexError:
                field_value = None

            if not field_visible[i]:
                clean_data.append(None)
                continue

            if self.required and field_value in validators.EMPTY_VALUES:
                raise ValidationError(self.error_messages['required'])

            try:
                clean_data.append(field.clean(field_value))
            except ValidationError, e:
                errors.extend(e.messages)  # Collect all widget errors
    def clean(self, value):
        clean_data = []
        errors = ErrorList()

        if value in validators.EMPTY_VALUES and self.required:
            raise ValidationError(self.error_messages['required'])

        for i, field in enumerate(self.fields):
            try:
                field_value = value[i]
            except IndexError:
                field_value = None

            if field_value in validators.EMPTY_VALUES:
                if (self.required and not self.optional):
                    raise ValidationError(self.error_messages['required'])
            else:
                field_value = field_value
                try:
                    clean_data.append(field.clean(field_value))
                except ValidationError, e:
                    errors.extend(e.messages)

            if i == len(self.fields) and len(clean_data) == 0:
                raise ValidationError(self.error_messages['optional_required'])
    def clean(self, value):
        """ Take a tuple of fields_valie(dict) and json_value(str) from JSONWidget """
        fields_value, json_value = value

        errors = ErrorList()
        # Clear json value
        if isinstance(json_value, basestring):
            try:
                json_value = loads(json_value)
            except ValueError:
                json_value = None
                errors.append(_(u"JSON Field: Enter valid JSON"))

        if json_value != None and not isinstance(json_value, dict):
            errors.append(_(u"JSON Field: Must be a dict"))

        # Clear fields
        assert isinstance(fields_value, dict)

        if json_value:
            merge_dict(fields_value, json_value)

        def _clean(f, _values):
            for k, v in iterhelper(f):
                if isinstance(v, (dict, tuple, list)):
                    _clean(v, _values.get(k, {}))
                else:
                    try:
                        tmp = _values.get(k, None)
                        v.clean(tmp)
                        _values[k] = v.to_python(tmp)
                    except FormValidationError, e:
                        errors.extend(
                            map(lambda x, y: x + y, [u"%s %s: " % (_("Field"), k)] * len(e.messages), e.messages)
                        )
Beispiel #6
0
def lib_artist(request, artist_name):
    artist_name_comma = Artist.commafy(artist_name)

    artist = get_object_or_none(Artist, name=artist_name_comma)
    if (artist is None):
        artist = get_object_or_none(Artist, name=artist_name)

    errors = ErrorList()
    albums = []
    similar_artists = []
    artist_art = ''
    api = PyLastFm()
    art_api = EchoNest()

    if artist is not None:
        albums = Album.objects.filter(artist=artist).order_by("-date_released")

        if albums.count() > 0:
            lfm_artist = get_last_fm_artist_name(artist)
            if lfm_artist:
                similar_artists = [similar for similar in api.get_similar_artists(lfm_artist)
                                   if Artist.objects.filter(name__iexact=similar).count() > 0 or
                                   Artist.objects.filter(name__iexact=Artist.commafy(similar)).count() > 0
                                   ]
                artist_art = art_api.get_artist_art(lfm_artist)
            else:
                errors.append('The artist could not be found by Last.Fm')

    return render_to_response('artist.html', {
        'errors': errors,
        'albums': albums,
        'artist': artist,
        'artist_art': artist_art,
        'similar_artists': similar_artists,
    }, context_instance=RequestContext(request))
 def clean(self, value):
     '''\
     value is assumed to be a dictionary of values with keys corresponding
     to the ones in self.subfields. Each value is validated against it's 
     corresponding field.
     '''
     clean_data = {}
     errors = ErrorList()
     
     if value is None:
         return value
     
     if not isinstance(value, dict):
         raise ValidationError(self.error_messages['invalid'])
     
     for fieldname, field in self.subfields.items():
         if not fieldname in value.keys():
             if field.required:
                 raise ValidationError(field.error_messages['required'])
             else:
                 continue
         
         try:
             clean_data[fieldname] = field.clean(value[fieldname])
         except ValidationError, e:
             errors.extend(e.messages)
Beispiel #8
0
    def form_valid(self, form):
        with transaction.commit_manually():
            try:
                super(ItemCreate, self).form_valid(form)
            except ValidationError as e:
                transaction.rollback()
                errors = ErrorList()
                for error in e.messages:
                    errors.append(error)
                errors = form._errors.setdefault(NON_FIELD_ERRORS, errors)

                return super(ItemCreate, self).form_invalid(form)

            context = self.get_context_data()

            itemimage_form = context['itemimage_formset']

            if itemimage_form.is_valid():
                itemimage_form.save()
                transaction.commit()
                return redirect(self.get_success_url())
            else:
                transaction.rollback()
                return self.render_to_response(
                    self.get_context_data(form=form)
                )
Beispiel #9
0
 def clean_sub_fields(self, value):
     """'value' being the list of the values of the subfields, validate
     each subfield."""
     clean_data = []
     errors = ErrorList()
     # Remove the field corresponding to the SKIP_CHECK_NAME boolean field
     # if required.
     fields = self.fields if not self.skip_check else self.fields[:-1]
     for index, field in enumerate(fields):
         try:
             field_value = value[index]
         except IndexError:
             field_value = None
         # Check the field's 'required' field instead of the global
         # 'required' field to allow subfields to be required or not.
         if field.required and field_value in validators.EMPTY_VALUES:
             errors.append(
                 '%s: %s' % (field.label, self.error_messages['required']))
             continue
         try:
             clean_data.append(field.clean(field_value))
         except ValidationError, e:
             # Collect all validation errors in a single list, which we'll
             # raise at the end of clean(), rather than raising a single
             # exception for the first error we encounter.
             errors.extend(
                 ['%s: %s' % (field.label, message)
                 for message in e.messages])
Beispiel #10
0
    def clean(self, value):
        """
        Validates every value in the given list. A value is validated against
        the corresponding Field in self.fields.

        For example, if this MultiValueField was instantiated with
        fields=(DateField(), TimeField()), clean() would call
        DateField.clean(value[0]) and TimeField.clean(value[1]).
        """
        clean_data = []
        errors = ErrorList()
        if not value or isinstance(value, (list, tuple)):
            if not value or not [v for v in value if v not in validators.EMPTY_VALUES]:
                if self.required:
                    raise ValidationError(self.error_messages["required"])
                else:
                    return self.compress([])
        else:
            raise ValidationError(self.error_messages["invalid"])
        for i, field in enumerate(self.fields):
            try:
                field_value = value[i]
            except IndexError:
                field_value = None
            if self.required and field_value in validators.EMPTY_VALUES:
                raise ValidationError(self.error_messages["required"])
            try:
                clean_data.append(field.clean(field_value))
            except ValidationError, e:
                # Collect all validation errors in a single list, which we'll
                # raise at the end of clean(), rather than raising a single
                # exception for the first error we encounter.
                errors.extend(e.messages)
Beispiel #11
0
    def clean(self, value):
        clean_data = []
        errors = ErrorList()
        if not value or isinstance(value, (list, tuple)):
            if not value or not [v for v in value if v not in self.empty_values]:
                if self.required:
                    raise ValidationError(self.error_messages['required'])
                else:
                    return []
        else:
            raise ValidationError(self.error_messages['invalid'])
        
        field = self.field_type(required=self.required)
        for field_value in value:
            try:
                clean_data.append(field.clean(field_value))
            except ValidationError as e:
                # Collect all validation errors in a single list, which we'll
                # raise at the end of clean(), rather than raising a single
                # exception for the first error we encounter.
                errors.extend(e.messages)
            if field.required:
                field.required = False
        if errors:
            raise ValidationError(errors)

        self.validate(clean_data)
        self.run_validators(clean_data)
        return clean_data
Beispiel #12
0
    def form_valid(self, form):
        try:
            return super(ExhibitionCreate, self).form_valid(form)
        except ValidationError as e:
            errors = ErrorList()
            for error in e.messages:
                errors.append(error)
            errors = form._errors.setdefault(NON_FIELD_ERRORS, errors)

            return super(ExhibitionCreate, self).form_invalid(form)
Beispiel #13
0
    def clean(self, value):
        """
        Validates every value in the given list. A value is validated against
        the corresponding Field in self.fields.

        For example, if this MultiValueField was instantiated with
        fields=(DateField(), TimeField()), clean() would call
        DateField.clean(value[0]) and TimeField.clean(value[1]).
        """
        clean_data = {}
        errors = ErrorList()
        if not value or isinstance(value, dict):
            if not value or not [v for v in value.values() if v not in self.empty_values]:
                if self.required:
                    raise ValidationError(self.error_messages['required'])
                else:
                    return {}
        else:
            raise ValidationError(self.error_messages['invalid'])
        
        # sort out required => at least one element must be in there
        
        data_field = self.field_type(**self.field_kwargs)
        for key, val in value.items():
            # ignore empties. Can they even come up here?
            if key in self.empty_values and val in self.empty_values:
                continue
            
            try:
                val = data_field.clean(val)
            except ValidationError as e:
                # Collect all validation errors in a single list, which we'll
                # raise at the end of clean(), rather than raising a single
                # exception for the first error we encounter.
                errors.extend(e.messages)
                
            try:
                self._validate_key(key)
            except ValidationError as e:
                # Collect all validation errors in a single list, which we'll
                # raise at the end of clean(), rather than raising a single
                # exception for the first error we encounter.
                errors.extend(e.messages)
            
            clean_data[key] = val
                
            if data_field.required:
                data_field.required = False
                
        if errors:
            raise ValidationError(errors)

        self.validate(clean_data)
        self.run_validators(clean_data)
        return clean_data
Beispiel #14
0
 def post(self, request, *args, **kwargs):
     if self.async_response is not None:
         return self.async_response
     if self.subscription_form.is_valid():
         try:
             subscription = self.subscription_form.create_subscription()
             return HttpResponseRedirect(reverse(ManageBillingAccountView.urlname, args=(subscription.account.id,)))
         except NewSubscriptionError as e:
             errors = ErrorList()
             errors.extend([e.message])
             self.subscription_form._errors.setdefault(NON_FIELD_ERRORS, errors)
     return self.get(request, *args, **kwargs)
Beispiel #15
0
def lib_main(request):
    albums = []
    errors = ErrorList()

    pager = Paginator([], 1)
    selected_page = 1

    form = None  # it's our search form
    # If a form was just submitted
    if request.method == 'POST':
        form = SearchForm(request.POST)  # A form bound to the POST data
        if form.is_valid():
            # Use the form fields to search and filter albums from the db
            albums = lib_main_filter_albums(form)

            pager = Paginator(albums, form.cleaned_data['items_per_page'])
            selected_page = int(form.cleaned_data['selected_page'])

            page_list = [(str(x), str(x)) for x in pager.page_range][:100]
            if len(page_list) is 0:
                form.fields['selected_page'][('1', '1')]
            else:
                form.fields['selected_page'].choices = page_list
            form.fields['selected_page'].initial = selected_page
        else:
            # Add all of the errors in the form.errors dict to our error list
            errors.extend(chain.from_iterable(form.errors.values()))
        form.save()
    else:
        form = SearchForm(initial={'artist': request.GET.get('artist'),
                                   'album': request.GET.get('album'),
                                   'label': request.GET.get('label'),
                                   'year': request.GET.get('year'),
                                   'genre': request.GET.get('genre'),
                                   'stack': request.GET.get('stack'),
                                   'selected_page': "1",
                                   'items_per_page': "25",
                                   })
        form.fields['selected_page'].choices = [(str(x), str(x)) for x in pager.page_range][:100]

    albums_page = []
    try:
        albums_page = pager.page(selected_page).object_list
    except EmptyPage:
        albums_page = pager.page(1).object_list
        errors.append("That page is empty.")

    return render_to_response('library.html', {
        'form': form,
        'albums': albums_page,
        'errors': errors,
    }, context_instance=RequestContext(request))
Beispiel #16
0
def login_view(request):
    """
    Standard Django login, with additions:
        Lowercase the login email (username)
        Check user has accepted ToS, if any.
    """
    if request.method == "POST":
        redirect_to = request.REQUEST.get('next', False)
        if not redirect_to:
            redirect_to = reverse('seed:home')

        form = LoginForm(request.POST)
        if form.is_valid():
            new_user = authenticate(
                username=form.cleaned_data['email'].lower(),
                password=form.cleaned_data['password']
            )
            if new_user and new_user.is_active:
                # determine if user has accepted ToS, if one exists
                try:
                    user_accepted_tos = has_user_agreed_latest_tos(new_user)
                except NoActiveTermsOfService:
                    # there's no active ToS, skip interstitial
                    user_accepted_tos = True

                if user_accepted_tos:
                    login(request, new_user)
                    return HttpResponseRedirect(redirect_to)
                else:
                    # store login info for django-tos to handle
                    request.session['tos_user'] = new_user.pk
                    request.session['tos_backend'] = new_user.backend
                    context = RequestContext(request)
                    context.update({
                        'next': redirect_to,
                        'tos': TermsOfService.objects.get_current_tos()
                    })
                    return render_to_response(
                        'tos/tos_check.html',
                        context_instance=context
                    )
            else:
                errors = ErrorList()
                errors = form._errors.setdefault(NON_FIELD_ERRORS, errors)
                errors.append('Username and/or password were invalid.')
    else:
        form = LoginForm()
    return render_to_response(
        'landing/login.html',
        locals(),
        context_instance=RequestContext(request),
    )
Beispiel #17
0
    def clean(self, value):
        """
        Validates every value in the given list. A value is validated against
        the corresponding Field in self.fields.

        For example, if this MultiValueField was instantiated with
        fields=(DateField(), TimeField()), clean() would call
        DateField.clean(value[0]) and TimeField.clean(value[1]).
        """
        clean_data = []
        errors = ErrorList()
        if not value or isinstance(value, (list, tuple)):
            if not value or not [v for v in value if v not in self.empty_values]:
                if self.required:
                    raise ValidationError(self.error_messages['required'], code='required')
                else:
                    return self.compress([])
        else:
            raise ValidationError(self.error_messages['invalid'], code='invalid')
        for i, field in enumerate(self.fields):
            try:
                field_value = value[i]
            except IndexError:
                field_value = None
            if field_value in self.empty_values:
                if self.require_all_fields:
                    # Raise a 'required' error if the MultiValueField is
                    # required and any field is empty.
                    if self.required:
                        raise ValidationError(self.error_messages['required'], code='required')
                elif field.required:
                    # Otherwise, add an 'incomplete' error to the list of
                    # collected errors and skip field cleaning, if a required
                    # field is empty.
                    if field.error_messages['incomplete'] not in errors:
                        errors.append(field.error_messages['incomplete'])
                    continue
            try:
                clean_data.append(field.clean(field_value))
            except ValidationError as e:
                # Collect all validation errors in a single list, which we'll
                # raise at the end of clean(), rather than raising a single
                # exception for the first error we encounter. Skip duplicates.
                errors.extend(m for m in e.error_list if m not in errors)
        if errors:
            raise ValidationError(errors)

        out = self.compress(clean_data)
        self.validate(out)
        self.run_validators(out)
        return out
    def clean(self, value):
        """
        Validates every value in the given list. A value is validated against
        the corresponding Field in self.fields.

        Only allows for exactly 1 valid value to be submitted, this is what
        gets returned by compress.

        example to use directy (instead of using FileOrURLField):
            MutuallyExclusiveValueField(
                fields=(forms.IntegerField(), forms.IntegerField()),
                widget=MutuallyExclusiveRadioWidget(widgets=[
                        forms.Select(choices=[(1,1), (2,2)]),
                        forms.TextInput(attrs={'placeholder':
                                               'Enter a number'}),
                    ]))
        """
        clean_data = []
        errors = ErrorList()
        if not value or isinstance(value, (list, tuple)):
            if not value or not [
                    v for v in value if v not in self.empty_values]:
                if self.required:
                    raise ValidationError(
                        self.error_messages['required'], code='required')
                else:
                    return self.compress([])
        else:
            raise ValidationError(
                self.error_messages['invalid'], code='invalid')
        for i, field in enumerate(self.fields):
            try:
                field_value = value[i]
            except IndexError:
                field_value = None
            try:
                clean_data.append(field.clean(field_value))
            except ValidationError as e:
                # Collect all validation errors in a single list, which we'll
                # raise at the end of clean(), rather than raising a single
                # exception for the first error we encounter.
                errors.extend(e.messages)
        if errors:
            raise ValidationError(errors)

        out = self.compress(clean_data)
        self.validate(out)
        self.run_validators(out)
        return out
Beispiel #19
0
    def clean(self, value):
        clean_data = {}
        errors = ErrorList()
        if not value or isinstance(value, dict):
            if not value or not [v for v in value.values() if v not in self.empty_values]:
                if self.required:
                    raise ValidationError(self.error_messages['required'])
                else:
                    return {}
        else:
            raise ValidationError(self.error_messages['invalid'])
        
        # sort out required => at least one element must be in there
        
        data_field = self.field_type(**self.field_kwargs)
        for key, val in value.items():
            # ignore empties. Can they even come up here?
            if key in self.empty_values and val in self.empty_values:
                continue
            
            try:
                val = data_field.clean(val)
            except ValidationError as e:
                # Collect all validation errors in a single list, which we'll
                # raise at the end of clean(), rather than raising a single
                # exception for the first error we encounter.
                errors.extend(e.messages)
                
            try:
                self._validate_key(key)
            except ValidationError as e:
                # Collect all validation errors in a single list, which we'll
                # raise at the end of clean(), rather than raising a single
                # exception for the first error we encounter.
                errors.extend(e.messages)
            
            clean_data[key] = val
                
            if data_field.required:
                data_field.required = False
                
        if errors:
            raise ValidationError(errors)

        self.validate(clean_data)
        self.run_validators(clean_data)
        return clean_data
Beispiel #20
0
def errors_append(form, field_name, message):
    u"""
    Add an ValidationError to a field (instead of __all__) during Form.clean():

    class MyForm(forms.Form):
        def clean(self):
            value_a=self.cleaned_data['value_a']
            value_b=self.cleaned_data['value_b']
            if value_a==... and value_b==...:
                formutils.errors_append(self, 'value_a', u'Value A must be ... if value B is ...')
            return self.cleaned_data
    """
    error_list = form.errors.get(field_name)
    if error_list is None:
        error_list = ErrorList()
        form.errors[field_name] = error_list
    error_list.append(message)
 def __init__(self, label, help_text, html, required, default_value=None, attrs={}):
     self.label_text = label
     self.help_text = help_text
     self.html = html
     self.required = required
     self.default_value = default_value
     self.attrs = attrs
     self.errors = ErrorList()
Beispiel #22
0
def lib_album(request, artist_name, album_title):
    errors = ErrorList()
    songs = []
    album_art = ''
    api = PyLastFm()

    album = get_object_or_none(Album, artist__name__iexact=artist_name, name__iexact=album_title)
    artist = get_object_or_none(Artist, name__iexact=artist_name)

    if album is not None and artist is not None:
        # Check if we have the track listing in our database
        songs = Song.objects.filter(album=album).order_by('track_num')

        try:
            lfm_artist = get_last_fm_artist_name(artist)
            album_art = api.get_album_art(lfm_artist, album.name)
            # If not, get the track listing from Last.fm and save it.
            if songs.count() == 0:
                songs = save_track_list(album)
        except WSError:
            errors.append('The album or artist could not be found by Last.Fm')
            
    else:
        if artist is None:
            errors.append('The artist was not found in the WUVT Library.')
        if album is None:
            errors.append('The album was not found in the WUVT library.')

    return render_to_response('album.html', {
        'errors': errors,
        'album': album,
        'album_art': album_art,
        'songs': songs,
    }, context_instance=RequestContext(request))
Beispiel #23
0
 def is_promotable(self):
     """
     Returns True if the object's state is the last state of its lifecycle.
     """
     self._promotion_errors = ErrorList()
     if self.lifecycle.last_state == self.state:
         self._promotion_errors.append(_(u"The object is at its last state."))
         return False
     return True
Beispiel #24
0
    def clean(self, value):
        """
        This is a copy of MultiValueField.clean() with a BUGFIX:
        -   if self.required and field_value in validators.EMPTY_VALUES:
        +   if field.required and field_value in validators.EMPTY_VALUES:
        """
        from django.forms.util import ErrorList
        from django.core import validators
        from django.core.exceptions import ValidationError


        clean_data = []
        errors = ErrorList()
        if not value or isinstance(value, (list, tuple)):
            if not value or not [v for v in value if v not in validators.EMPTY_VALUES]:
                if self.required:
                    raise ValidationError(self.error_messages['required'])
                else:
                    return self.compress(value)
        else:
            raise ValidationError(self.error_messages['invalid'])
        for i, field in enumerate(self.fields):
            try:
                field_value = value[i]
            except IndexError:
                field_value = None
            if field.required and field_value in validators.EMPTY_VALUES:
                raise ValidationError(self.error_messages['required'])
            try:
                clean_data.append(field.clean(field_value))
            except ValidationError as e:
                # Collect all validation errors in a single list, which we'll
                # raise at the end of clean(), rather than raising a single
                # exception for the first error we encounter.
                errors.extend(e.messages)
        if errors:
            raise ValidationError(errors)

        out = self.compress(clean_data)
        self.validate(out)
        self.run_validators(out)

        return out
    def clean(self, value):
        self.errors = ErrorList()
        self.value = value
        try:
            self.validate(value)
        except ValidationError as e:
            self.errors.extend(e.messages)

        if self.errors:
            raise ValidationError(self.errors)
        return value
Beispiel #26
0
 def clean_product_rates(self):
     original_data = self.cleaned_data['product_rates']
     rates = json.loads(original_data)
     rate_instances = []
     errors = ErrorList()
     for rate_data in rates:
         rate_form = ProductRateForm(rate_data)
         if not rate_form.is_valid():
             errors.extend(list(self._get_errors_from_subform(rate_data['name'], rate_form)))
         else:
             rate_instances.append(self._retrieve_product_rate(rate_form))
     if errors:
         self._errors.setdefault('product_rates', errors)
     self.new_product_rates = rate_instances
     rate_ids = lambda x: set([r.id for r in x])
     if (not self.is_update
         and (self.plan_version is None
              or rate_ids(rate_instances).symmetric_difference(rate_ids(self.plan_version.product_rates.all())))):
         self.is_update = True
     return original_data
Beispiel #27
0
    def clean(self, value):
        """
        Validates every value in the given list. A value is validated against
        the corresponding Field in self.fields.

        For example, if this MultiValueField was instantiated with
        fields=(DateField(), TimeField()), clean() would call
        DateField.clean(value[0]) and TimeField.clean(value[1]).
        """
        clean_data = []
        errors = ErrorList()

            # Currently no file is uploaded so we continue validation.
            # If a file is already updated is and you haven't

#            if not value or isinstance(value, (list, tuple)):
#                if not value or not [v for v in value if v not in validators.EMPTY_VALUES]:
#                    if self.required:
#                        raise ValidationError(self.error_messages['required'])
#                    else:
#                        return self.compress([])
#            else:
#                raise ValidationError(self.error_messages['invalid'])

        if value[0]:
            try:
                field_value = value[0]
            except IndexError:
                field_value = None
            if self.required and field_value in validators.EMPTY_VALUES:
                raise ValidationError(self.error_messages['required'])
            try:
                clean_data.append(self.fields[0].clean(field_value))
            except ValidationError, e:
                # Collect all validation errors in a single list, which we'll
                # raise at the end of clean(), rather than raising a single
                # exception for the first error we encounter.
                errors.extend(e.messages)

            clean_data.extend([None for i in range(6)])
    def clean(self, value):
        """
        Validates every value in the given list. A value is validated against
        the corresponding Field in self.fields.

        For example, if this MultiValueField was instantiated with
        fields=(DateField(), TimeField()), clean() would call
        DateField.clean(value[0]) and TimeField.clean(value[1]).
        """
        clean_data = []
        errors = ErrorList()
        if not value or isinstance(value, (list, tuple)):
            if not value or not [v for v in value if v not in self.empty_values]:
                if self.required:
                    raise ValidationError(self.error_messages['required'])
                else:
                    return []
        else:
            raise ValidationError(self.error_messages['invalid'])
        
        field = self.field_type(required=self.required)
        for field_value in value:
            if self.required and field_value in self.empty_values:
                raise ValidationError(self.error_messages['required'])
            try:
                clean_data.append(field.clean(field_value))
            except ValidationError as e:
                # Collect all validation errors in a single list, which we'll
                # raise at the end of clean(), rather than raising a single
                # exception for the first error we encounter.
                errors.extend(e.messages)
            if field.required:
                field.required = False
        if errors:
            raise ValidationError(errors)

        self.validate(clean_data)
        self.run_validators(clean_data)
        return clean_data
    def _validate_data(self, cleaned_data, row_num, applicable_contract):
        """
        Like django's clean method, use this to validate across fields
        """

        errors = ErrorList()

        validation_methods = [
            self._validate_open_closed_date,
            self._validate_service_adaptation,
            self._validate_media_code,
            self._validate_stage_reached,
            self._validate_dob_present,
        ]

        validation_methods.extend(self.get_extra_validators_for_applicable_contract(applicable_contract))

        validation_methods_depend_on_category = [
            self._validate_time_spent,
            self._validate_exemption,
            self._validate_telephone_or_online_advice,
            self._validate_determination_dvca_is_family,
        ]

        for m in validation_methods:
            try:
                m(cleaned_data)
            except serializers.ValidationError as ve:
                errors.append(self.format_message(ve.message, row_num))
        try:
            category = self._validate_category_consistency(cleaned_data)
        except serializers.ValidationError as ve:
            errors.append(self.format_message(ve.message, row_num))
            raise serializers.ValidationError(errors)

        for m in validation_methods_depend_on_category:
            try:
                m(cleaned_data, category)
            except serializers.ValidationError as ve:
                errors.append(self.format_message(ve.message, row_num))

        if len(errors):
            raise serializers.ValidationError(errors)

        return cleaned_data
    def _validate_fields(self):
        """
        Validate individual field values, like django's clean_<fieldname> with
        less magic ( no setattr('clean_'+field_name) junk) just loop over
        the fields and apply the validators specified in the
        field spec (self._get_expected_fields_for_row(row))
        """
        cleaned_data = {}
        errors = ErrorList()

        for row_num, row in enumerate(self.rows):
            expected_fields = self._get_validators_for_row(row)
            if len(row) != len(expected_fields):
                raise serializers.ValidationError(
                    "Row: %s - Incorrect number of columns should be %s "
                    "actually %s" % (row_num + 1, len(expected_fields), len(row))
                )

            for idx, field_name in enumerate(expected_fields):
                field_value = row[idx]
                validators = expected_fields[field_name]
                try:
                    cleaned_data[field_name] = self._validate_field(
                        field_name, field_value.strip(), idx, row_num, validators
                    )
                except serializers.ValidationError as ve:
                    errors.append(ve)
                except (AssertionError, TypeError) as e:
                    errors.append(e)
            try:
                # Global Validation
                applicable_contract = self._get_applicable_contract_for_row(row)
                self.cleaned_data.append(self._validate_data(cleaned_data, row_num, applicable_contract))
            except serializers.ValidationError as ve:
                errors.extend(ve.error_list)

        if len(errors):
            raise serializers.ValidationError(errors)
Beispiel #31
0
    def post(self, request):
        form = self.form_class(request.POST, request.FILES)
        backend_forms = []
        if form.is_valid():
            text = form.cleaned_data['text']
            access_level, user_identifier, confirm = request.service.check_access(
                request, text)

            def prepare_message():
                message = Message()
                message.set_service(request.service)
                message.user_identifier = user_identifier
                message.text = text
                return message

            if access_level == 'moderate':
                message = prepare_message()
                message.closed = False
                message.save()
                return render_to_response(
                    'multitreehole/publish-moderate.html', {
                        'user_identifier': user_identifier,
                        'message': message,
                    },
                    context_instance=RequestContext(request))
            elif access_level == 'accept':
                message = prepare_message()
                message.closed = True
                message.save()
                if confirm(message):
                    client = request.backend.make_client(
                        request.service.backend.pk,
                        request.service.backend.params)
                    backend_message = client.make_message(
                        form.cleaned_data['text'])
                    status = backend_message.publish(request.POST,
                                                     request.FILES)
                else:
                    status = {
                        'error':
                        ErrorList([
                            _('Access confirmation failed. Are you requesting concurrently?'
                              )
                        ])
                    }
                if 'forms' in status:
                    backend_forms = status['forms']
                if 'error' in status:
                    form._errors['text'] = status['error']
                if 'data' in status:
                    message.backend = request.service.backend
                    message.backend_data = status['data']
                    message.save()
                    return render_to_response(
                        'multitreehole/publish-accept.html', {
                            'user_identifier': user_identifier,
                            'message': message,
                        },
                        context_instance=RequestContext(request))
                message.delete()
        else:
            access_level, user_identifier, confirm = request.service.check_access(
                request)
        return self.render_to_response({
            'form': form,
            'backend_forms': backend_forms,
            'access_level': access_level,
            'user_identifier': user_identifier,
        })
 def clean(self):
     cleaned_data = self.cleaned_data
     if not cleaned_data.get('excel_file') and not cleaned_data.get(
             'converted_items'):
         self.errors['excel_file'] = ErrorList([u'Required Field'])
     return cleaned_data
Beispiel #33
0
                raise PopupException(
                    _('There was a problem with some of the LDAP information'),
                    detail=str(e))

            if users and form.cleaned_data['ensure_home_directory']:
                for user in users:
                    try:
                        ensure_home_directory(request.fs, user.username)
                    except (IOError, WebHdfsException), e:
                        request.error(
                            _("Cannot make home directory for user %s." %
                              user.username))

            if not users:
                errors = form._errors.setdefault('username_pattern',
                                                 ErrorList())
                errors.append(
                    _('Could not get LDAP details for users in pattern %s.') %
                    username_pattern)
            else:
                return redirect(reverse(list_users))
    else:
        form = AddLdapUsersForm()

    return render('add_ldap_users.mako', request, dict(form=form))


def add_ldap_groups(request):
    """
  add_ldap_groups(request) -> reply
Beispiel #34
0
def edit_document(request, document_slug, revision_id=None):
    """Create a new revision of a wiki document, or edit document metadata."""
    doc = get_object_or_404(
        Document, locale=request.LANGUAGE_CODE, slug=document_slug)
    user = request.user

    can_edit_needs_change = doc.allows(user, 'edit_needs_change')
    can_archive = doc.allows(user, 'archive')

    # If this document has a parent, then the edit is handled by the
    # translate view. Pass it on.
    if doc.parent:
        return translate(request, doc.parent.slug, revision_id)
    if revision_id:
        rev = get_object_or_404(Revision, pk=revision_id, document=doc)
    else:
        rev = doc.current_revision or doc.revisions.order_by('-created',
                                                             '-id')[0]

    disclose_description = bool(request.GET.get('opendescription'))
    doc_form = rev_form = None
    if doc.allows(user, 'create_revision'):
        rev_form = RevisionForm(
            instance=rev,
            initial={'based_on': rev.id, 'comment': ''})
    if doc.allows(user, 'edit'):
        doc_form = DocumentForm(
            initial=_document_form_initial(doc),
            can_archive=can_archive,
            can_edit_needs_change=can_edit_needs_change)

    if request.method == 'GET':
        if not (rev_form or doc_form):
            # You can't do anything on this page, so get lost.
            raise PermissionDenied

    else:  # POST
        # Comparing against localized names for the Save button bothers me, so
        # I embedded a hidden input:
        which_form = request.POST.get('form')

        _document_lock_clear(doc.id, user.username)

        if which_form == 'doc':
            if doc.allows(user, 'edit'):
                post_data = request.POST.copy()
                post_data.update({'locale': request.LANGUAGE_CODE})

                topics = []
                for t in post_data.getlist('topics'):
                    topics.append(long(t))
                post_data.setlist('topics', topics)

                doc_form = DocumentForm(
                    post_data,
                    instance=doc,
                    can_archive=can_archive,
                    can_edit_needs_change=can_edit_needs_change)
                if doc_form.is_valid():
                    # Get the possibly new slug for the imminent redirection:
                    try:
                        doc = doc_form.save(None)
                    except (TitleCollision, SlugCollision) as e:
                        # TODO: .add_error() when we upgrade to Django 1.7
                        errors = doc_form._errors.setdefault('title',
                                                             ErrorList())
                        message = 'The {type} you selected is already in use.'
                        message = message.format(
                            type='title' if isinstance(e, TitleCollision) else
                            'slug')
                        errors.append(_(message))
                    else:
                        # Do we need to rebuild the KB?
                        _maybe_schedule_rebuild(doc_form)

                        return HttpResponseRedirect(
                            urlparams(reverse('wiki.edit_document',
                                              args=[doc.slug]),
                                      opendescription=1))
                disclose_description = True
            else:
                raise PermissionDenied
        elif which_form == 'rev':
            if doc.allows(user, 'create_revision'):
                rev_form = RevisionForm(request.POST)
                rev_form.instance.document = doc  # for rev_form.clean()
                if rev_form.is_valid():
                    _save_rev_and_notify(rev_form, user, doc, base_rev=rev)
                    if 'notify-future-changes' in request.POST:
                        EditDocumentEvent.notify(request.user, doc)

                    return HttpResponseRedirect(
                        reverse('wiki.document_revisions',
                                args=[document_slug]))
            else:
                raise PermissionDenied

    show_revision_warning = _show_revision_warning(doc, rev)
    locked, locked_by = _document_lock(doc.id, user.username)

    return render(request, 'wiki/edit.html', {
        'revision_form': rev_form,
        'document_form': doc_form,
        'disclose_description': disclose_description,
        'document': doc,
        'show_revision_warning': show_revision_warning,
        'locked': locked,
        'locked_by': locked_by})
Beispiel #35
0
def add_event(request,
              template='schedule/schedule_form.html',
              event_form_class=ReferralForm,
              recurrence_form_class=ScheduleOccurrenceForm,
              redirect_to=None):

    # have to contains dtstart variable in URL. URL from schedule have to
    # contains date and time informations.
    if 'dtstart' not in request.GET:
        return http.HttpResponseRedirect('/schedule/')

    if request.method == 'POST':
        if int(request.POST.get('count')) > 40:  # limit occurrence repeat
            return render_to_response(
                '403.html', {
                    'object':
                    _('Sorry. You can not book more than 40 occurrence at the same \
time')
                })
        recurrence_form = recurrence_form_class(request.POST)

        if recurrence_form.is_valid():
            if invalid_delta_time(request.POST.get('start_time_delta'),
                                  request.POST.get('end_time_delta')):
                messages.error(
                    request,
                    _('The start time should be less than the end time'))
                return http.HttpResponseRedirect(
                    request.META.get('HTTP_REFERER') or '/schedule/')

            # filter devices based on selection
            devices = DeviceDetails.objects.filter(
                id__in=request.POST.getlist('device'))
            start_occurrence_date = end_occurrence_date = datetime(
                year=int(request.POST.get('until_year')),
                month=int(request.POST.get('until_month')),
                day=int(request.POST.get('until_day')))
            # create a start delta time
            start_delta = timedelta(
                seconds=int(request.POST.get('start_time_delta')))
            # checking till one minute before next session
            end_delta = timedelta(
                seconds=(int(request.POST.get('end_time_delta')) - 1))
            # get correct start time of device schedule
            start_device_schedule = (start_occurrence_date + start_delta)

            end_device_schedule = (end_occurrence_date + end_delta)
            # try to check if there's any occurrence with the device in
            # specified time
            occurrence_start = Occurrence.objects.filter(
                start_time__range=(start_device_schedule, end_device_schedule),
                scheduleoccurrence__device__in=devices,
            )
            # check exact end time
            end_delta = timedelta(
                seconds=int(request.POST.get('end_time_delta')))
            end_device_schedule = (end_occurrence_date + end_delta)
            occurrence_end = Occurrence.objects.filter(
                end_time__range=(start_device_schedule, end_device_schedule),
                scheduleoccurrence__device__in=devices,
            )
            if len(occurrence_start) is not 0 or len(occurrence_end) is not 0:
                error = recurrence_form._errors.setdefault(
                    'device', ErrorList())
                error.append('Selected device is busy')
            if request.POST.get('tabtitle'):  # booking single client
                if verify_client(request.POST.get('referral')) is False:
                    messages.error(request, _('Check the mandatory fields'))
                    return http.HttpResponseRedirect(
                        request.META.get('HTTP_REFERER') or '/schedule/')
                referral = get_object_or_404(Referral,
                                             pk=request.POST.get('referral'),
                                             service__organization=request.
                                             user.get_profile().org_active)
                event = recurrence_form.save(referral)
            elif request.POST.get('group'):  # booking a group
                group = get_object_or_404(ServiceGroup,
                                          pk=request.POST.get('group'),
                                          service__organization=request.user.
                                          get_profile().org_active,
                                          active=True)
                # this check is already done in template. just to prevent
                # empty groups
                if group.charged_members():
                    first = True
                    for group_member in group.charged_members():
                        if first:
                            event = recurrence_form.save(group_member.referral)
                            first = False
                        else:
                            if not event.errors:
                                # ignore busy check
                                event = recurrence_form.save(
                                    group_member.referral, True)
            else:
                referral = get_object_or_404(
                    Referral,
                    pk=request.POST.get('select_referral'),
                    service__organization=request.user.get_profile(
                    ).org_active)
                event = recurrence_form.save(referral, True, True)
            if not event.errors:
                messages.success(request, _('Schedule saved successfully'))
                return http.HttpResponseRedirect(redirect_to or '/schedule/')
            else:
                return render_to_response(
                    'schedule/event_detail.html',
                    dict(event=event),
                    context_instance=RequestContext(request))
    else:

        dtstart = parser.parse(request.GET['dtstart'])
        room = get_object_or_None(
            Room,
            pk=request.GET.get('room'),
            place__organization=request.user.get_profile().org_active)
        client = get_object_or_None(
            Client,
            pk=request.GET.get('client'),
            person__organization=request.user.get_profile().org_active)
        referral = get_object_or_None(
            Referral,
            pk=request.GET.get('referral'),
            service__organization=request.user.get_profile().org_active)
        event_form = event_form_class()

        recurrence_form = recurrence_form_class(initial=dict(
            dtstart=dtstart,
            day=datetime.strptime(dtstart.strftime("%Y-%m-%d"), "%Y-%m-%d"),
            until=datetime.strptime(dtstart.strftime("%Y-%m-%d"), "%Y-%m-%d"),
            room=room.id,
        ))

        recurrence_form.fields['device'].widget.choices = ([
            (i.id, i) for i in DeviceDetails.objects.active(
                request.user.get_profile().org_active).filter(
                    Q(room=room) | Q(mobility="2", lendable=True)
                    | Q(place=room.place, mobility="2", lendable=False))
        ])

    return render_to_response(
        template,
        dict(
            dtstart=dtstart,
            event_form=event_form,
            recurrence_form=recurrence_form,
            group=ServiceGroup.objects.filter(
                service__organization=request.user.get_profile().org_active,
                active=True),
            room=room,
            object=client,
            referral=referral,
            referrals=Referral.objects.all(),
            room_id=room.id,
        ),
        context_instance=RequestContext(request))
Beispiel #36
0
 def add_field_error(form, field_name, message):
     err_list = ErrorList((message, ))
     form._errors[field_name] = err_list
Beispiel #37
0
def search(request):
    """
    Handler for search form.
    """
    if request.method == 'POST': # If the form has been submitted
        form = SearchForm(request.POST) # A form bound to the POST data
        if form.is_valid(): # All validation rules pass
            #process search form into search object, remove any properties
            #that do not have values.
            data = form.cleaned_data
            for key in filter(lambda x: data[x]==None or data[x] == '', data):
                del data[key]
            search_object = Search()
            search_object.data = data
            
            #at least for now limit the size of the result set
            count = search_object.querySet().count()
            if count > settings.QUERY_LIMIT:
                form._errors['Result Size'] = ErrorList(['Your query returned more than 20,000 records, refine your search'])
            
            elif count == 0 and False:
                form._errors['Result Size'] = ErrorList(['Your query returned no results'])
            
            else:
                #store search in session
                
                search.dataset_version = pdb_select_settings.DATA_VERSION
                request.session['search'] = pickle.dumps(search_object)
                return redirect('%s/search/results/' % settings.SITE_ROOT) # Redirect after POST
        
        # package aa_choices and ss_choices
        aa_choices = []
        ss_choices = []
        for i in RESIDUE_INDEXES:
            aa_chosen = request.POST.getlist('aa_%i' % i)
            aa_choices.append([(c[0],c[1],'checked' if c[0] in aa_chosen else '') for c in AA_CHOICES])
            ss_chosen = request.POST.getlist('ss_%i' % i)
            ss_choices.append([(c[0],c[1],'checked' if c[0] in ss_chosen else '') for c in SS_CHOICES])
    else:
        aa_choices = [AA_CHOICES for i in range(settings.SEGMENT_SIZE)]
        ss_choices = [SS_CHOICES for i in range(settings.SEGMENT_SIZE)]
        form = SearchForm() # An unbound form

    #delete session variable
    try:
        del request.session['search']
    except:
        pass
    #construct a list of values for i
    iValues = [
                    # Generates a series of tuples (<value>,<signed string of value>); zero is 'i'
                    (i,'%+i'%i if i else 'i') for i in RESIDUE_INDEXES
              ]

    #order the residue properties in way that django template can handle it better
    residueFields = []
    fields = ["ss", "aa", "phi", "psi", "ome", "omep", "chi1", "chi2", "chi3", "chi4", "chi5", "bm", "bs", "bg", "h_bond_energy", "zeta", 'a1','a2','a3','a4','a5','a6','a7','L1','L2','L3','L4','L5']
    fields += sidechain_length_relationship_list
    fields += sidechain_angle_relationship_list
    for i in RESIDUE_INDEXES:
        dict = {}
        for prefix in fields:
            dict[prefix] =  form['%s_%i' % (prefix, i)]
            dict['%s_i' % prefix] =  form['%s_i_%i' % (prefix, i)]
            dict['index'] = i
        residueFields.append(dict)

    return render_to_response('search.html', {
        'form': form,
        'maxLength' : settings.SEGMENT_SIZE,
        'iValues':iValues,
        'residueFields':residueFields,
        'aa_choices':aa_choices,
        'ss_choices':ss_choices,
        'sidechain_angle_list':sidechain_angle_relationship_list,
        'sidechain_length_list':sidechain_length_relationship_list,
        'sidechain_length_lookup':json_sidechain_lengths_lookup,
        'sidechain_angle_lookup':json_sidechain_angles_lookup
    }, context_instance=RequestContext(request, processors=[settings_processor]))
Beispiel #38
0
def document_metadata(
        request,
        docid,
        template='documents/document_metadata.html'):

    document = None
    try:
        document = _resolve_document(
            request,
            docid,
            'base.change_resourcebase_metadata',
            _PERMISSION_MSG_METADATA)

    except Http404:
        return HttpResponse(
            loader.render_to_string(
                '404.html', RequestContext(
                    request, {
                        })), status=404)

    except PermissionDenied:
        return HttpResponse(
            loader.render_to_string(
                '401.html', RequestContext(
                    request, {
                        'error_message': _("You are not allowed to edit this document.")})), status=403)

    if document is None:
        return HttpResponse(
            'An unknown error has occured.',
            content_type="text/plain",
            status=401
        )

    else:
        poc = document.poc
        metadata_author = document.metadata_author
        topic_category = document.category

        if request.method == "POST":
            document_form = DocumentForm(
                request.POST,
                instance=document,
                prefix="resource")
            category_form = CategoryForm(
                request.POST,
                prefix="category_choice_field",
                initial=int(
                    request.POST["category_choice_field"]) if "category_choice_field" in request.POST else None)
        else:
            document_form = DocumentForm(instance=document, prefix="resource")
            category_form = CategoryForm(
                prefix="category_choice_field",
                initial=topic_category.id if topic_category else None)

        if request.method == "POST" and document_form.is_valid(
        ) and category_form.is_valid():
            new_poc = document_form.cleaned_data['poc']
            new_author = document_form.cleaned_data['metadata_author']
            new_keywords = document_form.cleaned_data['keywords']
            new_category = TopicCategory.objects.get(
                id=category_form.cleaned_data['category_choice_field'])

            if new_poc is None:
                if poc is None:
                    poc_form = ProfileForm(
                        request.POST,
                        prefix="poc",
                        instance=poc)
                else:
                    poc_form = ProfileForm(request.POST, prefix="poc")
                if poc_form.is_valid():
                    if len(poc_form.cleaned_data['profile']) == 0:
                        # FIXME use form.add_error in django > 1.7
                        errors = poc_form._errors.setdefault('profile', ErrorList())
                        errors.append(_('You must set a point of contact for this resource'))
                        poc = None
                if poc_form.has_changed and poc_form.is_valid():
                    new_poc = poc_form.save()

            if new_author is None:
                if metadata_author is None:
                    author_form = ProfileForm(request.POST, prefix="author",
                                              instance=metadata_author)
                else:
                    author_form = ProfileForm(request.POST, prefix="author")
                if author_form.is_valid():
                    if len(author_form.cleaned_data['profile']) == 0:
                        # FIXME use form.add_error in django > 1.7
                        errors = author_form._errors.setdefault('profile', ErrorList())
                        errors.append(_('You must set an author for this resource'))
                        metadata_author = None
                if author_form.has_changed and author_form.is_valid():
                    new_author = author_form.save()

            if new_poc is not None and new_author is not None:
                the_document = document_form.save()
                the_document.poc = new_poc
                the_document.metadata_author = new_author
                the_document.keywords.add(*new_keywords)
                Document.objects.filter(id=the_document.id).update(category=new_category)

                if getattr(settings, 'SLACK_ENABLED', False):
                    try:
                        from geonode.contrib.slack.utils import build_slack_message_document, send_slack_messages
                        send_slack_messages(build_slack_message_document("document_edit", the_document))
                    except:
                        print "Could not send slack message for modified document."

                return HttpResponseRedirect(
                    reverse(
                        'document_detail',
                        args=(
                            document.id,
                        )))

        if poc is not None:
            document_form.fields['poc'].initial = poc.id
            poc_form = ProfileForm(prefix="poc")
            poc_form.hidden = True

        if metadata_author is not None:
            document_form.fields['metadata_author'].initial = metadata_author.id
            author_form = ProfileForm(prefix="author")
            author_form.hidden = True

        return render_to_response(template, RequestContext(request, {
            "document": document,
            "document_form": document_form,
            "poc_form": poc_form,
            "author_form": author_form,
            "category_form": category_form,
        }))
Beispiel #39
0
def register(request):
    if request.method == 'POST':
        if 'cancel' in request.POST:
            return redirect_to_index(request)
        form = RegistrationForm(request.POST)

        if not settings.NAT_ID_VERIFICATION:
            form.disable_national_id_verification()

        if form.is_valid():
            email = form.cleaned_data['email']
            first_name = form.cleaned_data['first_name']
            last_name = form.cleaned_data['last_name']
            national_id = form.cleaned_data['national_id']

            result, error_field, applicant = (validate_email_and_national_id(
                email, national_id))

            if result:
                try:
                    applicant = form.get_applicant()
                    passwd = applicant.random_password()
                    applicant.save()
                except IntegrityError:
                    # somehow, it gets error

                    result, error_field, applicant = (
                        validate_email_and_national_id(email, national_id))
                    return registration_error(error_field, applicant, email,
                                              national_id, first_name,
                                              last_name)

                registration = Registration(applicant=applicant,
                                            first_name=first_name,
                                            last_name=last_name)
                registration.random_and_save()
                send_password_by_email(applicant, passwd)
                return render_to_response(
                    'application/registration/success.html', {
                        'email': form.cleaned_data['email'],
                        'step_name': "การลงทะเบียนเรียบร้อย"
                    })
            else:
                if not applicant.has_logged_in:
                    return registration_error(error_field, applicant, email,
                                              national_id, first_name,
                                              last_name)

                # e-mail or national id has been registered and logged in
                from django.forms.util import ErrorList
                from commons.utils import admin_email

                if error_field == 'email':
                    dup_obj = u'อีเมล์'
                else:
                    dup_obj = u'รหัสประจำตัวประชาชน'

                form._errors['__all__'] = ErrorList([
                    u"""%(dup_obj)sนี้ถูกลงทะเบียนและถูกใช้แล้ว ถ้าอีเมล์นี้เป็นของคุณจริงและยังไม่เคยลงทะเบียน
กรุณาติดต่อผู้ดูแลระบบทางอีเมล์ <a href="mailto:%(email)s">%(email)s</a> หรือทางเว็บบอร์ด
อาจมีผู้ไม่ประสงค์ดีนำอีเมล์คุณไปใช้""" % {
                        'dup_obj': dup_obj,
                        'email': admin_email()
                    }
                ])

    else:
        form = RegistrationForm()
    return render_to_response('application/registration/register.html',
                              {'form': form},
                              context_instance=RequestContext(request))
Beispiel #40
0
def layer_metadata(request, layername, template='layers/layer_metadata.html'):
    layer = _resolve_layer(request, layername,
                           'base.change_resourcebase_metadata',
                           _PERMISSION_MSG_METADATA)
    layer_attribute_set = inlineformset_factory(
        Layer,
        Attribute,
        extra=0,
        form=LayerAttributeForm,
    )
    topic_category = layer.category

    poc = layer.poc
    metadata_author = layer.metadata_author

    if request.method == "POST":
        if layer.metadata_uploaded_preserve:  # layer metadata cannot be edited
            out = {
                'success': False,
                'errors': METADATA_UPLOADED_PRESERVE_ERROR
            }
            return HttpResponse(json.dumps(out),
                                content_type='application/json',
                                status=400)

        layer_form = LayerForm(request.POST, instance=layer, prefix="resource")
        attribute_form = layer_attribute_set(
            request.POST,
            instance=layer,
            prefix="layer_attribute_set",
            queryset=Attribute.objects.order_by('display_order'))
        category_form = CategoryForm(
            request.POST,
            prefix="category_choice_field",
            initial=int(request.POST["category_choice_field"])
            if "category_choice_field" in request.POST else None)

    else:
        layer_form = LayerForm(instance=layer, prefix="resource")
        attribute_form = layer_attribute_set(
            instance=layer,
            prefix="layer_attribute_set",
            queryset=Attribute.objects.order_by('display_order'))
        category_form = CategoryForm(
            prefix="category_choice_field",
            initial=topic_category.id if topic_category else None)

    if request.method == "POST" and layer_form.is_valid(
    ) and attribute_form.is_valid() and category_form.is_valid():
        new_poc = layer_form.cleaned_data['poc']
        new_author = layer_form.cleaned_data['metadata_author']
        new_keywords = layer_form.cleaned_data['keywords']

        if new_poc is None:
            if poc is None:
                poc_form = ProfileForm(request.POST,
                                       prefix="poc",
                                       instance=poc)
            else:
                poc_form = ProfileForm(request.POST, prefix="poc")
            if poc_form.is_valid():
                if len(poc_form.cleaned_data['profile']) == 0:
                    # FIXME use form.add_error in django > 1.7
                    errors = poc_form._errors.setdefault(
                        'profile', ErrorList())
                    errors.append(
                        _('You must set a point of contact for this resource'))
                    poc = None
            if poc_form.has_changed and poc_form.is_valid():
                new_poc = poc_form.save()

        if new_author is None:
            if metadata_author is None:
                author_form = ProfileForm(request.POST,
                                          prefix="author",
                                          instance=metadata_author)
            else:
                author_form = ProfileForm(request.POST, prefix="author")
            if author_form.is_valid():
                if len(author_form.cleaned_data['profile']) == 0:
                    # FIXME use form.add_error in django > 1.7
                    errors = author_form._errors.setdefault(
                        'profile', ErrorList())
                    errors.append(
                        _('You must set an author for this resource'))
                    metadata_author = None
            if author_form.has_changed and author_form.is_valid():
                new_author = author_form.save()

        new_category = TopicCategory.objects.get(
            id=category_form.cleaned_data['category_choice_field'])

        for form in attribute_form.cleaned_data:
            la = Attribute.objects.get(id=int(form['id'].id))
            la.description = form["description"]
            la.attribute_label = form["attribute_label"]
            la.visible = form["visible"]
            la.display_order = form["display_order"]
            la.save()

        if new_poc is not None and new_author is not None:
            new_keywords = layer_form.cleaned_data['keywords']
            layer.keywords.clear()
            layer.keywords.add(*new_keywords)
            the_layer = layer_form.save()
            up_sessions = UploadSession.objects.filter(layer=the_layer.id)
            if up_sessions.count(
            ) > 0 and up_sessions[0].user != the_layer.owner:
                up_sessions.update(user=the_layer.owner)
            the_layer.poc = new_poc
            the_layer.metadata_author = new_author
            Layer.objects.filter(id=the_layer.id).update(category=new_category)

            if getattr(settings, 'SLACK_ENABLED', False):
                try:
                    from geonode.contrib.slack.utils import build_slack_message_layer, send_slack_messages
                    send_slack_messages(
                        build_slack_message_layer("layer_edit", the_layer))
                except:
                    print "Could not send slack message."

            return HttpResponseRedirect(
                reverse('layer_detail', args=(layer.service_typename, )))

    if poc is not None:
        layer_form.fields['poc'].initial = poc.id
        poc_form = ProfileForm(prefix="poc")
        poc_form.hidden = True

    if metadata_author is not None:
        layer_form.fields['metadata_author'].initial = metadata_author.id
        author_form = ProfileForm(prefix="author")
        author_form.hidden = True

    return render_to_response(
        template,
        RequestContext(
            request, {
                "layer": layer,
                "layer_form": layer_form,
                "poc_form": poc_form,
                "author_form": author_form,
                "attribute_form": attribute_form,
                "category_form": category_form,
            }))
Beispiel #41
0
def hidden_field_errors(form):
    hidden_field_errors = ErrorList()
    for field in form.hidden_fields():
        hidden_field_errors.extend(field.errors)
    return hidden_field_errors