def _add_share_context(context, request, photos): if len(photos) > 0: photo_url = photos[0].thumbnail.url elif context.get('has_tree'): photo_url = settings.STATIC_URL + "img/tree.png" else: photo_url = settings.STATIC_URL + "img/otmLogo126.png" photo_url = request.build_absolute_uri(photo_url) title = trans("%s on %s") % (context['title'], request.instance.name) if context.get('benefits_total_currency', 0) > 0: description = trans("This %s saves %s%s per year.") % ( context['title'], context['currency_symbol'], number_format(context['benefits_total_currency'], decimal_pos=0) ) else: description = trans("This %s is mapped on %s.") % ( context['title'], request.instance.name, ) context['share'] = { 'url': request.build_absolute_uri(), 'title': title, 'description': description, 'image': photo_url, }
class SendCredentialProposalForm(AgentNameForm): connection_id = forms.CharField(widget=forms.HiddenInput()) partner_name = forms.CharField(label=trans('Partner Name'), max_length=60) cred_def = forms.CharField(max_length=80, widget=forms.HiddenInput()) credential_name = forms.CharField(widget=forms.HiddenInput()) schema_attrs = forms.CharField(label=trans('Credential Attributes'), max_length=500, widget=forms.Textarea) def __init__(self, *args, **kwargs): super(SendCredentialProposalForm, self).__init__(*args, **kwargs) self.fields['agent_name'].widget.attrs['readonly'] = True self.fields['agent_name'].widget.attrs['hidden'] = True self.fields['connection_id'].widget.attrs['readonly'] = True self.fields['partner_name'].widget.attrs['readonly'] = True self.fields['cred_def'].widget.attrs['readonly'] = True # build a list of attributes for the given schema initial = kwargs.get('initial') if initial: schema_attrs = initial.get('schema_attrs', '{}') schema_attrs = json.loads(schema_attrs) self.fields['schema_attrs'].widget.attrs['hidden'] = True for attr in schema_attrs: field_name = 'schema_attr_' + attr self.fields[field_name] = forms.CharField(label=attr, max_length=500)
class SendCredentialResponseFormProposal(SendConversationResponseForm): # a bunch of fields that are read-only to present to the user agent_name = forms.CharField(widget=forms.HiddenInput()) libindy_offer_schema_id = forms.CharField(widget=forms.HiddenInput()) conversation_id = forms.CharField(label=trans('conversation_id'), max_length=500) from_partner_name = forms.CharField(widget=forms.HiddenInput()) claim_name = forms.CharField(widget=forms.HiddenInput()) credential_attrs = forms.CharField(label=trans('Credential Attributs'), max_length=500) def __init__(self, *args, **kwargs): super(SendCredentialResponseFormProposal, self).__init__(*args, **kwargs) self.fields['agent_name'].widget.attrs['readonly'] = True self.fields['agent_name'].widget.attrs['hidden'] = True self.fields['libindy_offer_schema_id'].widget.attrs['readonly'] = True self.fields['libindy_offer_schema_id'].widget.attrs['hidden'] = True self.fields['conversation_id'].widget.attrs['readonly'] = True self.fields['claim_name'].widget.attrs['readonly'] = True self.fields['claim_name'].widget.attrs['hidden'] = True self.fields['from_partner_name'].widget.attrs['hidden'] = True self.fields['from_partner_name'].widget.attrs['hidden'] = True # self.fields['credential_attrs'].widget.attrs['readonly'] = False # build a list of attributes for the current schema initial = kwargs.get('initial') if initial: credential_attrs = initial.get('credential_attrs', {}) self.fields['credential_attrs'].widget.attrs['hidden'] = True for attr in credential_attrs: field_name = 'credential_attr_' + attr self.fields[field_name] = forms.CharField( label=attr, initial=credential_attrs[attr]) self.fields[field_name].widget.attrs['readonly'] = True
class BlogPostForm(forms.ModelForm): helper = FormHelper() # helper.form_tag = False helper.layout = Layout( _('Create a blog post'), Field('published'), Field('title'), Field('description'), Field('post_date'), Field('language'), Field('content'), Div(HTML(""" <div class="btn-group" role="group" aria-label="..."> <button type="button" id="italics-btn" title="{0}" class="btn btn-inverse"> <span class="glyphicon glyphicon-italic"></span> </button> <button type="button" id="bold-btn" title="{1}" class="btn btn-inverse"> <span class="glyphicon glyphicon-bold"></span> </button> <button type="button" id="list-btn" title="{2}" class="btn btn-inverse"> <span class="glyphicon glyphicon-list"></span> </button> <button type="button" id="link-btn" title="{3}" class="btn btn-inverse"> <span class="glyphicon glyphicon-link"></span> </button> <button type="button" id="picture-btn" title="{4}" class="btn btn-inverse" data-toggle="modal" data-target="#upload-img-modal"> <span class="glyphicon glyphicon-picture"></span> </button> </div> """.format(trans("Insert italics code"), trans("Insert bold text code"), trans("Insert a list item"), trans("Insert a link"), trans("Upload picture"))), css_class="pull-left"), Div(FormActions(Submit('save', _('Save')), ), css_class="pull-right"), ) class Meta: model = Post fields = '__all__'
def user(request, username): user = get_object_or_404(User, username=username) instance_id = request.GET.get("instance_id", None) instance = get_instance_or_404(pk=instance_id) if instance_id else None query_vars = {"instance_id": instance_id} if instance_id else {} audit_dict = _get_audits(request.user, instance, query_vars, user, ["Plot", "Tree"], 0) reputation = user.get_reputation(instance) if instance else None public_fields = [(trans("First Name"), "user.first_name"), (trans("Last Name"), "user.last_name")] private_fields = [(trans("Email"), "user.email")] return { "user": user, "reputation": reputation, "instance_id": instance_id, "audits": audit_dict["audits"], "next_page": audit_dict["next_page"], "public_fields": public_fields, "private_fields": private_fields, }
def user(request, username): user = get_object_or_404(User, username=username) instance_id = request.GET.get('instance_id', None) instance = (get_instance_or_404(pk=instance_id) if instance_id else None) query_vars = {'instance_id': instance_id} if instance_id else {} audit_dict = _get_audits(request.user, instance, query_vars, user, ['Plot', 'Tree'], 0) reputation = user.get_reputation(instance) if instance else None public_fields = [ (trans('First Name'), 'user.first_name'), (trans('Last Name'), 'user.last_name') ] private_fields = [ (trans('Email'), 'user.email') ] return {'user': user, 'reputation': reputation, 'instance_id': instance_id, 'audits': audit_dict['audits'], 'next_page': audit_dict['next_page'], 'public_fields': public_fields, 'private_fields': private_fields}
def clean_udfs(self): errors = {} scalar_fields = {field.name: field for field in self.get_user_defined_fields() if not field.iscollection} collection_fields = {field.name: field for field in self.get_user_defined_fields() if field.iscollection} # Clean scalar udfs for (key, val) in self.udfs.iteritems(): field = scalar_fields.get(key, None) if field: try: field.clean_value(val) except ValidationError as e: errors["udf:%s" % key] = e.messages else: errors["udf:%s" % key] = trans("Invalid user defined field name") # Clean collection values, but only if they were loaded if self.udfs.collection_data_loaded: collection_data = self.udfs.collection_fields for collection_field_name, data in collection_data.iteritems(): collection_field = collection_fields.get(collection_field_name, None) if collection_field: try: collection_field.clean_collection(data) except ValidationError as e: errors.update(e.message_dict) else: errors["udf:%s" % collection_field_name] = trans("Invalid user defined field name") if errors: raise ValidationError(errors)
def _get_status_panel_specs(ie): verified_panel = { 'name': 'verified', 'status': GenericImportRow.VERIFIED, 'title': trans('Ready to Add') } error_panel = { 'name': 'error', 'status': GenericImportRow.ERROR, 'title': trans('Errors') } success_panel = { 'name': 'success', 'status': GenericImportRow.SUCCESS, 'title': trans('Successfully Added') } if isinstance(ie, TreeImportEvent): warning_panel = { 'name': 'warning', 'status': TreeImportRow.WARNING, 'title': trans('Warnings') } panels = [verified_panel, error_panel, warning_panel, success_panel] else: merge_required_panel = { 'name': 'merge_required', 'status': None, 'title': trans('Merge Required') } panels = [ verified_panel, merge_required_panel, error_panel, success_panel] return panels
def clean(self): errors = {} if len(self.currency_symbol) > 4: errors['currency_symbol'] = trans( 'Symbol is too long') positive_fields = ['electricity_kwh_to_currency', 'natural_gas_kbtu_to_currency', 'h20_gal_to_currency', 'co2_lb_to_currency', 'o3_lb_to_currency', 'nox_lb_to_currency', 'pm10_lb_to_currency', 'sox_lb_to_currency', 'voc_lb_to_currency'] for field in positive_fields: value = getattr(self, field) try: value = float(value or '') if value < 0: errors[field] = [trans('Values must be not be negative')] except ValueError: pass if errors: raise ValidationError(errors)
def action_format_string_for_audit(clz, audit): if audit.field == 'id' or audit.field is None: lang = { Audit.Type.Insert: trans('created a %(model)s'), Audit.Type.Update: trans('updated the %(model)s'), Audit.Type.Delete: trans('deleted the %(model)s'), Audit.Type.PendingApprove: trans('approved an ' 'edit to the %(model)s'), Audit.Type.PendingReject: trans('rejected an ' 'edit to the %(model)s') } else: lang = { Audit.Type.Insert: trans('set %(field)s to %(value)s'), Audit.Type.Update: trans('set %(field)s to %(value)s'), Audit.Type.Delete: trans('deleted %(field)s'), Audit.Type.PendingApprove: trans('approved setting ' '%(field)s to %(value)s'), Audit.Type.PendingReject: trans('rejecting setting ' '%(field)s to %(value)s') } return lang[audit.action]
def create_user(request): data = json.loads(request.body) errors = {} for field in REQ_FIELDS: if field not in data: errors[field] = [trans('This field is required')] for inputfield in data: if inputfield not in ALL_FIELDS: errors[inputfield] = [trans('Unrecognized field')] if errors: raise ValidationError(errors) dup_username = User.objects.filter(username=data['username']) dup_email = User.objects.filter(email=data['email']) if dup_username.exists(): return _conflict_response(trans('Username is already in use')) if dup_email.exists(): # BE WARNED - The iOS application relies on this error message string. # If you change this you WILL NEED TO ALTER CODE THERE AS WELL. return _conflict_response(trans('Email is already in use')) user = User(**data) # Needed to properly hash the password user.set_password(data['password']) user.active = True user.save() RegistrationProfile.objects.create_profile(user) return {'status': 'success', 'id': user.pk}
def _context_dict_for_map_feature(request, feature): instance = request.instance if instance.pk != feature.instance_id: raise Exception("Invalid instance, does not match map feature") feature.instance = instance # save a DB lookup user = request.user if user and user.is_authenticated(): feature.mask_unauthorized_fields(user) feature.convert_to_display_units() if feature.is_plot: tree = feature.current_tree() if tree: if tree.species: title = tree.species.common_name else: title = trans("Missing Species") else: title = trans("Empty Planting Site") else: title = feature.display_name context = { 'feature': feature, 'feature_type': feature.feature_type, 'title': title, } _add_eco_benefits_to_context_dict(instance, feature, context) return context
def _get_status_panel_specs(ie): verified_panel = { 'name': 'verified', 'status': GenericImportRow.VERIFIED, 'title': trans('Ready to Add') } error_panel = { 'name': 'error', 'status': GenericImportRow.ERROR, 'title': trans('Errors') } success_panel = { 'name': 'success', 'status': GenericImportRow.SUCCESS, 'title': trans('Successfully Added') } if isinstance(ie, TreeImportEvent): warning_panel = { 'name': 'warning', 'status': TreeImportRow.WARNING, 'title': trans('Warnings') } panels = [verified_panel, error_panel, warning_panel, success_panel] else: merge_required_panel = { 'name': 'merge_required', 'status': None, 'title': trans('Merge Required') } panels = [ verified_panel, merge_required_panel, error_panel, success_panel ] return panels
class Plot(MapFeature): width = models.FloatField(null=True, blank=True, help_text=trans("Plot Width")) length = models.FloatField(null=True, blank=True, help_text=trans("Plot Length")) owner_orig_id = models.CharField(max_length=255, null=True, blank=True) objects = GeoHStoreUDFManager() @classproperty def benefits(cls): from treemap.ecobenefits import TreeBenefitsCalculator return TreeBenefitsCalculator() def nearby_plots(self, distance_in_meters=None): if distance_in_meters is None: distance_in_meters = settings.NEARBY_TREE_DISTANCE distance_filter = Plot.objects.filter( geom__distance_lte=(self.geom, D(m=distance_in_meters))) return distance_filter\ .filter(instance=self.instance)\ .exclude(pk=self.pk) def get_tree_history(self): """ Get a list of all tree ids that were ever assigned to this plot """ return Audit.objects.filter(instance=self.instance)\ .filter(model='Tree')\ .filter(field='plot')\ .filter(current_value=self.pk)\ .order_by('-model_id', '-updated')\ .distinct('model_id')\ .values_list('model_id', flat=True) def current_tree(self): """ This is a compatibility method that is used by the API to select the 'current tree'. Right now OTM only supports one tree per plot, so this method returns the 'first' tree """ trees = list(self.tree_set.all()) if trees: return trees[0] else: return None def delete_with_user(self, user, cascade=False, *args, **kwargs): if self.current_tree() and cascade is False: raise ValidationError(trans( "Cannot delete plot with existing trees.")) super(Plot, self).delete_with_user(user, *args, **kwargs) @classproperty def display_name(cls): return trans('Planting Site')
def _context_dict_for_map_feature(instance, feature): if instance.pk != feature.instance_id: raise Exception("Invalid instance, does not match map feature") feature.instance = instance # save a DB lookup if feature.is_plot: tree = feature.current_tree() if tree: if tree.species: title = tree.species.common_name else: title = trans("Missing Species") else: title = trans("Empty Planting Site") else: title = feature.display_name context = { 'feature': feature, 'feature_type': feature.feature_type, 'title': title, } _add_eco_benefits_to_context_dict(instance, feature, context) return context
def _validate_and_update_choice(self, datatype, old_choice_value, new_choice_value): if datatype['type'] != 'choice': raise ValidationError({ 'datatype': [trans("can't change choices " "on a non-choice field")] }) if old_choice_value not in datatype['choices']: raise ValidationError({ 'datatype': [ trans("choice '%(choice)s' not found") % { 'choice': old_choice_value } ] }) choices = datatype['choices'] if new_choice_value: choices = [ c if c != old_choice_value else new_choice_value for c in choices ] else: choices = [c for c in choices if c != old_choice_value] datatype['choices'] = choices return datatype
def Save(request, event_id): event = Event.objects.get(pk=event_id) form = SignUpForm() SignUpFormSet = formset_factory(SignUpForm, ) if request.method == 'POST': formset = SignUpFormSet(request.POST, request.FILES) for idx, extraform in enumerate(formset.forms): if idx != 0: extraform.empty_permitted = True if formset.is_valid(): counter = 0 for form in formset.forms: signup = form.save(commit=False) if (signup.name == ''): counter = counter + 1 continue signup.event = event signup.member = get_user(request) if counter != 0: signup.avec = True signup.save() counter = counter + 1 save_user_checkboxes(request, event, signup, counter) save_user_text_fields(request, event, signup, counter) messages.add_message(request, messages.SUCCESS, trans(u'Anmälan sparad')) return HttpResponseRedirect( reverse('event:view', args=(event_id, ))) c = {'form': form, 'event': event} messages.add_message(request, messages.ERROR, trans(u'Anmälan misslyckades')) return render(request, 'events/view.html', c)
def create(self, validated_data): """Crear pago de especialista.""" match = validated_data.pop('match') instance = Payment(**validated_data) instance.save() match.status = 5 if 'test' not in sys.argv: client_id = match.client_id specialist_id = match.specialist_id qset_client = Client.objects.filter(pk=client_id) qset_spec = Specialist.objects.filter(pk=specialist_id) dict_pending = NotificationClientSerializer(qset_client).data dict_pending_sp = NotificationSpecialistSerializer(qset_spec).data badge_count = dict_pending["queries_pending"] + dict_pending[ "match_pending"] badge_count_sp = dict_pending_sp[ "queries_pending"] + dict_pending_sp["match_pending"] disp_name = display_specialist_name(match) disp_name_to_specialist = display_client_name(match.client) data_notif_push = { "title": disp_name, "body": match.subject, "sub_text": "", "ticker": trans("successful hiring"), "badge": badge_count, "icon": match.category.image, "type": Params.TYPE_NOTIF["match_success"], "queries_pending": dict_pending["queries_pending"], "match_pending": dict_pending["match_pending"], "match_id": match.id } data_specialist = { "title": disp_name_to_specialist, "body": match.subject, "sub_text": "", "ticker": trans("successful hiring"), "badge": badge_count_sp, "icon": match.category.image, "type": Params.TYPE_NOTIF["match_success"], "queries_pending": dict_pending_sp["queries_pending"], "match_pending": dict_pending_sp["match_pending"], "match_id": match.id } # envio de notificacion push Notification.fcm_send_data(user_id=client_id, data=data_notif_push) Notification.fcm_send_data(user_id=specialist_id, data=data_specialist) match.save() sellercontact = match.client.sellercontact_set.get() sellercontact.type_contact = 3 sellercontact.save() sale = match.sale_detail.sale sale.status = 3 sale.save() return instance
def __init__(self, *args, **kwargs): super(FormContato, self).__init__(*args, **kwargs) self.fields['email'].error_messages['required'] = trans(u'O campo E-mail é obrigatório') self.fields['nome'].error_messages['required'] = trans(u'O campo Nome é obrigatório') self.fields['mensagem'].error_messages['required'] = trans(u'O campo Mensagem é obrigatório') self.fields['email'].widget.attrs['required'] = "required" self.fields['nome'].widget.attrs['required'] = "required" self.fields['mensagem'].widget.attrs['required'] = "required"
class RemoveConnectionForm(AgentNameForm): partner_name = forms.CharField(label=trans('Partner Name'), max_length=60) connection_id = forms.CharField(label=trans('connection_id'), max_length=60) def __init__(self, *args, **kwargs): super(RemoveConnectionForm, self).__init__(*args, **kwargs) self.fields['partner_name'].widget.attrs['readonly'] = True self.fields['agent_name'].widget.attrs['readonly'] = True self.fields['agent_name'].widget.attrs['hidden'] = True
def save_uploaded_image(image_data, name_prefix, thumb_size=None, degrees_to_rotate=None): # We support passing data directly in here but we # have to treat it as a file-like object if type(image_data) is str: image_data = StringIO(image_data) image_data.seek(0, os.SEEK_END) file_size = image_data.tell() if file_size > settings.MAXIMUM_IMAGE_SIZE: raise ValidationError(trans('The uploaded image is too large')) image_data.seek(0) try: image = Image.open(image_data) image.verify() except IOError: raise ValidationError(trans('Invalid image')) try: # http://pillow.readthedocs.org/en/latest/_modules/PIL/Image.html#Image.verify # NOQA # ...if you need to load the image after using verify, # you must reopen the image file. image_data.seek(0) image = Image.open(image_data) format = image.format image_data.seek(0) hash = hashlib.md5(image_data.read()).hexdigest() name = "%s-%s.%s" % (name_prefix, hash, format.lower()) if degrees_to_rotate is None: image = _rotate_image_based_on_exif(image) else: image = image.rotate(degrees_to_rotate) image_file = _get_file_for_image(image, name, format) thumb_file = None if thumb_size is not None: thumb_image = image.copy() thumb_image.thumbnail(thumb_size, Image.ANTIALIAS) thumb_file = _get_file_for_image(thumb_image, 'thumb-%s' % name, format) # Reset image position image_data.seek(0) return image_file, thumb_file except: raise ValidationError(trans('Image upload issue'))
def __init__(self, *args, **kwargs): super(SelectProofReqClaimsForm, self).__init__(*args, **kwargs) # list requested attributes and the available claims, for the user to select initial = kwargs.get('initial') if initial: available_claims = initial.get('selected_claims', '{}') proof_request = initial.get('proof_request', '{}') print("available_claims:", available_claims) print("proof_request:", proof_request) for attr in proof_request['presentation_request'][ 'requested_attributes']: field_name = 'proof_req_attr_' + attr choices = [] claim_no = 0 for claim in available_claims: if attr in claim['presentation_referents']: choices.append( ('ref::' + claim['cred_info']['referent'], json.dumps(claim['cred_info']['attrs']))) claim_no = claim_no + 1 if 0 < len(choices): self.fields[field_name] = forms.ChoiceField( label=trans('Select claim for') + attr, choices=tuple(choices), widget=forms.RadioSelect()) else: self.fields[field_name] = forms.CharField( label=trans('No claims available for') + attr + ', enter value:', max_length=80) for attr in proof_request['presentation_request'][ 'requested_predicates']: field_name = 'proof_req_attr_' + attr choices = [] claim_no = 0 for claim in available_claims: if attr in claim['presentation_referents']: choices.append( ('ref::' + claim['cred_info']['referent'], json.dumps(claim['cred_info']['attrs']))) claim_no = claim_no + 1 if 0 < len(choices): self.fields[field_name] = forms.ChoiceField( label=trans('Select claim for') + attr, choices=tuple(choices), widget=forms.RadioSelect()) else: self.fields[field_name] = forms.CharField( label=trans('No claims available for') + attr + ', enter value:', max_length=80)
class SendProofReqResponseForm(SendConversationResponseForm): # a bunch of fields that are read-only to present to the user from_partner_name = forms.CharField(label=trans('Partner Name'), max_length=60) proof_req_name = forms.CharField(label=trans('Proof Request Name'), max_length=500) def __init__(self, *args, **kwargs): super(SendProofReqResponseForm, self).__init__(*args, **kwargs) self.fields['from_partner_name'].widget.attrs['readonly'] = True self.fields['proof_req_name'].widget.attrs['readonly'] = True
class AbstractUniqueEmailUser(AbstractBaseUser, PermissionsMixin): """ An abstract base class implementing a fully featured User model with admin-compliant permissions. Username, password and email are required. Other fields are optional. """ username = models.CharField( trans('username'), max_length=30, unique=True, help_text=trans( 'Required. 30 characters or fewer. Letters, numbers and ' '@/./+/-/_ characters'), validators=[ validators.RegexValidator(re.compile('^[\w.@+-]+$'), trans('Enter a valid username.'), 'invalid') ]) email = models.EmailField(trans('email address'), blank=True, unique=True) is_staff = models.BooleanField( trans('staff status'), default=False, help_text=trans('Designates whether the user can log into this admin ' 'site.')) is_active = models.BooleanField( trans('active'), default=True, help_text=trans('Designates whether this user should be treated as ' 'active. Unselect this instead of deleting accounts.')) date_joined = models.DateTimeField(trans('date joined'), default=timezone.now) objects = UserManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email'] class Meta: verbose_name = trans('user') verbose_name_plural = trans('users') abstract = True def get_full_name(self): """ Returns the first_name plus the last_name, with a space in between. """ full_name = '%s %s' % (self.first_name, self.last_name) return full_name.strip() def get_short_name(self): "Returns the short name for the user." return self.first_name def email_user(self, subject, message, from_email=None, **kwargs): """ Sends an email to this User. """ send_mail(subject, message, from_email, [self.email], **kwargs)
def action_format_string_for_audit(cls, audit): if audit.field == "id" or audit.field is None: lang = { Audit.Type.Insert: trans("created a %(model)s entry"), Audit.Type.Update: trans("updated the %(model)s entry"), Audit.Type.Delete: trans("deleted the %(model)s entry"), Audit.Type.PendingApprove: trans("approved an edit " "to the %(model)s entry"), Audit.Type.PendingReject: trans("rejected an " "edit to the %(model)s entry"), } return lang[audit.action] return Auditable.action_format_string_for_audit(audit)
def __init__(self, *args, **kwargs): super(FormCadastroDeTemplate, self).__init__(*args, **kwargs) self.fields['descricao'].error_messages['required'] = trans(u'O campo Descrição é obrigatório') self.fields['assunto'].error_messages['required'] = trans(u'O campo Assunto é obrigatório') self.fields['texto'].error_messages['required'] = trans(u'O campo Texto é obrigatório') self.fields['descricao'].widget.attrs['placeholder'] = 'Ex.: Agendamento de entrevista.' self.fields['assunto'].widget.attrs['placeholder'] = 'Assunto do Email' self.fields['texto'].widget.attrs['placeholder'] = 'Digite a texto do Email' self.fields['descricao'].widget.attrs['required'] = "required" self.fields['assunto'].widget.attrs['required'] = "required" self.fields['texto'].auto_id = False
class SendMessageForm(AgentNameForm): connection_id = forms.CharField(label=trans('connection_id'), max_length=50) message = forms.CharField(label=trans('Message'), max_length=500, widget=forms.Textarea()) def __init__(self, *args, **kwargs): super(SendMessageForm, self).__init__(*args, **kwargs) self.fields['message'].widget.attrs['readonly'] = False self.fields['connection_id'].widget.attrs['readonly'] = True self.fields['agent_name'].widget.attrs['readonly'] = True
class EmailForm(forms.Form): helper = FormHelper() helper.form_tag = False sender = forms.EmailField( label=_("Email"), required=True, widget=forms.TextInput( attrs={'placeholder': _("Enter your email address")})) subject = forms.CharField( label=_("Subject"), max_length=100, required=False, widget=forms.TextInput(attrs={'placeholder': _("What's this about?")})) message = forms.CharField( label=_("Message"), required=True, widget=forms.Textarea(attrs={'placeholder': _("Your message here")})) cc_myself = forms.BooleanField(label=_("Send myself a copy"), required=False, widget=forms.CheckboxInput()) helper.layout = Layout( HTML("""<!-- Modal form --> <div class="modal fade" id="emailForm" tabindex="-1" role="dialog" aria-labelledby="emailForm" aria-hidden="false"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button> <h4 class="modal-title" id="emailForm">{0}</h4> </div> <form action="{{% url 'mapApp:contact' %}}" method="post" role="form"> {{% csrf_token %}} <div class="modal-body"> """.format(trans("Contact"))), Field('sender'), Field('subject'), Field('message'), Field('cc_myself'), HTML(""" </div> <div class="modal-footer"> <button type="reset" class="btn btn-default" onclick="$('#emailForm').modal('hide');$('.modal-backdrop').hide();">{0}</button> <button type="submit" class="btn btn-primary">{1} <span class="glyphicon glyphicon-send"></span></button> </div> </form> </div> </div> </div> """.format(trans("Cancel"), trans("Send"))))
def resolve_object_type(obj: Object, *_): if obj.type == "directory": return trans("Directory") file_type = { "xlsx": "Excel file", "md": "Markdown document", "ipynb": "Jupyter Notebook", "csv": "CSV file", }.get(obj.extension, "File") return trans(file_type)
def approve_or_reject_photo( request, instance, feature_id, photo_id, action): approved = action == 'approve' if approved: msg = trans('Approved') else: msg = trans('Rejected') resp = HttpResponse(msg) try: photo = (MapFeaturePhoto.objects .select_related('treephoto') .get(pk=photo_id)) try: photo = photo.treephoto except MapFeaturePhoto.DoesNotExist: pass # There is no tree photo, so use the superclass except MapFeaturePhoto.DoesNotExist: # This may be a pending tree. Let's see if there # are pending audits pending_audits = Audit.objects\ .filter(instance=instance)\ .filter(model__in=['TreePhoto', 'MapFeaturePhoto'])\ .filter(model_id=photo_id)\ .filter(requires_auth=True) if len(pending_audits) > 0: # Process as pending and quit approve_or_reject_audits_and_apply( pending_audits, request.user, approved) return resp else: # Error - no pending or regular raise Http404('Photo Not Found') # Handle the id audit first all_audits = [] for audit in photo.audits(): if audit.field == 'id': all_audits = [audit] + all_audits else: all_audits.append(audit) for audit in all_audits: approve_or_reject_existing_edit( audit, request.user, approved) return resp
class SelectProofRequestForm(AgentNameForm): connection_id = forms.CharField(widget=forms.HiddenInput()) partner_name = forms.CharField(label=trans('Partner Name'), max_length=60) proof_request = forms.ModelChoiceField( label=trans('Proof Request Type'), queryset=IndyProofRequest.objects.all()) def __init__(self, *args, **kwargs): super(SelectProofRequestForm, self).__init__(*args, **kwargs) self.fields['agent_name'].widget.attrs['readonly'] = True self.fields['agent_name'].widget.attrs['hidden'] = True self.fields['connection_id'].widget.attrs['readonly'] = True self.fields['partner_name'].widget.attrs['readonly'] = True
def action_format_string_for_audit(cls, audit): if audit.field == 'id' or audit.field is None: lang = { Audit.Type.Insert: trans('created a %(model)s entry'), Audit.Type.Update: trans('updated the %(model)s entry'), Audit.Type.Delete: trans('deleted the %(model)s entry'), Audit.Type.PendingApprove: trans('approved an edit ' 'to the %(model)s entry'), Audit.Type.PendingReject: trans('rejected an ' 'edit to the %(model)s entry') } return lang[audit.action] return Auditable.action_format_string_for_audit(audit)
def Edit(request, signup_id): u = request.user signup = SignUp.objects.get(pk=signup_id) event = signup.event if request.method == 'POST': if (u.title and u.title.styrelsePost) or u.is_superuser or ( u == signup.member and event.deadline > datetime.utcnow().replace(tzinfo=pytz.utc)): form = SignUpForm(request.POST, instance=signup) signup = form.save(commit=False) signup.save() event = signup.event delete_extra_fields(signup) save_user_checkboxes(request, event, signup, 0) save_user_text_fields(request, event, signup, 0) messages.add_message(request, messages.SUCCESS, trans(u'Anmälan uppdaterad')) return HttpResponseRedirect( reverse('event:view', args=(signup.event_id, ))) else: messages.add_message( request, messages.ERROR, trans( u'Du har tyvärr inte rättigheter att ta ändra denna anmälan,\ vänligen kontakta styrelsen')) return HttpResponseRedirect( reverse('event:view', args=(event.id, ))) form = SignUpForm(instance=signup) event = signup.event event_text_fields = TextFieldXEvent.objects.filter( event_id__exact=event.id) event_check_boxes = CheckboxXEvent.objects.filter(event_id__exact=event.id) text_fields = [] check_boxes = [] for textfield in event_text_fields: tmp, _ = TextFieldXSignup.objects.get_or_create( textfield_id=textfield.id, signUp_id=signup_id) text_fields.append(tmp) for checkbox in event_check_boxes: tmp, _ = CheckboxXSignUp.objects.get_or_create(checkbox_id=checkbox.id, signUp_id=signup_id) check_boxes.append(tmp) c = { 'form': form, 'signup': signup, 'check_boxes': check_boxes, 'text_fields': text_fields, } return render(request, 'signup/edit.html', c)
def __init__(self, *args, **kwargs): super(RegistrationForm, self).__init__(*args, **kwargs) self.fields['email'].label = trans('Email') self.fields['password2'].label = trans('Confirm Password') for field_name, field in self.fields.items(): if not isinstance(field, forms.BooleanField): field.widget.attrs['class'] = 'form-control' self.fields['password1'].widget.attrs['outer_class'] = 'field-left' self.fields['password2'].widget.attrs['outer_class'] = 'field-right' self.fields['first_name'].widget.attrs['outer_class'] = 'field-left' self.fields['last_name'].widget.attrs['outer_class'] = 'field-right'
def _action_format_string_for_location(action): """A helper that allows multiple auditable models to return the same action format string for a field value that should be displayed as a location""" lang = { Audit.Type.Insert: trans('set the location'), Audit.Type.Update: trans('updated the location'), Audit.Type.Delete: trans('deleted the location'), Audit.Type.PendingApprove: trans('approved an ' 'edit of the location'), Audit.Type.PendingReject: trans('rejected an ' 'edit of the location') } return lang[action]
def update_choice( self, old_choice_value, new_choice_value, name=None): datatype = self.datatype_dict if self.iscollection: if name is None: raise ValidationError({ 'name': trans('Name is required for collection fields')}) datatypes = {info['name']: info for info in datatype} datatype = self._validate_and_update_choice( datatypes[name], old_choice_value, new_choice_value) datatypes[name] = datatype self.datatype = json.dumps(datatypes.values()) self.save() vals = UserDefinedCollectionValue\ .objects\ .filter(field_definition=self)\ .extra(where=["data ? %s AND data->%s = %s"], params=[name, name, old_choice_value]) if new_choice_value is None: vals.hremove('data', name) else: vals.hupdate('data', {name: new_choice_value}) audits = Audit.objects.filter( model='udf:%s' % self.pk, field='udf:%s' % name) # If the string is empty we want to delete the audits # _update_choices_on_audits only does nf new_choice_value # is none if new_choice_value == '': new_choice_value = None self._update_choices_on_audits( audits, old_choice_value, new_choice_value) else: if name is not None: raise ValidationError({ 'name': trans( 'Name is allowed only for collection fields')}) self._update_choice_scalar(old_choice_value, new_choice_value) # indicate success to transaction manager return True
class SendConnectionResponseForm(SendConnectionInvitationForm): invitation_id = forms.IntegerField(widget=forms.HiddenInput()) invitation_details = forms.CharField(label=trans('Invitation'), max_length=4000, widget=forms.Textarea) invitation_url = forms.CharField(label=trans('Invitation URL'), max_length=4000, widget=forms.Textarea) def __init__(self, *args, **kwargs): super(SendConnectionResponseForm, self).__init__(*args, **kwargs) self.fields['invitation_id'].widget.attrs['readonly'] = True self.fields['invitation_details'].widget.attrs['readonly'] = True self.fields['invitation_url'].widget.attrs['readonly'] = True
class SendCredentialRevokeForm(SendConversationResponseForm): # a bunch of fields that are read-only to present to the user agent_name = forms.CharField(widget=forms.HiddenInput()) cred_rev_id = forms.CharField(label=trans('Cred_rev_id'), max_length=10) rev_reg_id = forms.CharField(widget=forms.HiddenInput()) conversation_id = forms.CharField(label=trans('conversation_id'), max_length=120) def __init__(self, *args, **kwargs): super(SendCredentialRevokeForm, self).__init__(*args, **kwargs) self.fields['agent_name'].widget.attrs['readonly'] = True self.fields['cred_rev_id'].widget.attrs['readonly'] = True self.fields['conversation_id'].widget.attrs['readonly'] = True self.fields['rev_reg_id'].widget.attrs['hidden'] = True
class BaseSignUpForm(UserCreationForm): first_name = forms.CharField(max_length=80, label=trans('First Name'), required=False, help_text='Optional.') last_name = forms.CharField(max_length=150, label=trans('Last Name'), required=False, help_text='Optional.') email = forms.EmailField( max_length=254, label=trans('Email Address'), required=True, help_text=trans('Required. Provide a valid email address.'))
def approve_or_reject_photo( request, instance, feature_id, tree_id, photo_id, action): approved = action == 'approve' if approved: msg = trans('Approved') else: msg = trans('Rejected') resp = HttpResponse(msg) tree = get_object_or_404( Tree, plot_id=feature_id, instance=instance, pk=tree_id) try: photo = TreePhoto.objects.get(pk=photo_id, tree=tree) except TreePhoto.DoesNotExist: # This may be a pending tree. Let's see if there # are pending audits pending_audits = Audit.objects\ .filter(instance=instance)\ .filter(model='TreePhoto')\ .filter(model_id=photo_id)\ .filter(requires_auth=True) if len(pending_audits) > 0: # Process as pending and quit approve_or_reject_audits_and_apply( pending_audits, request.user, approved) return resp else: # Error - no pending or regular raise Http404('Tree Photo Not Found') # Handle the id audit first all_audits = [] for audit in photo.audits(): if audit.field == 'id': all_audits = [audit] + all_audits else: all_audits.append(audit) for audit in all_audits: approve_or_reject_existing_edit( audit, request.user, approved) return resp
def approve_or_reject_photo(request, instance, feature_id, photo_id, action): approved = action == 'approve' if approved: msg = trans('Approved') else: msg = trans('Rejected') resp = HttpResponse(msg) try: photo = (MapFeaturePhoto.objects.select_related('treephoto').get( pk=photo_id)) try: photo = photo.treephoto except MapFeaturePhoto.DoesNotExist: pass # There is no tree photo, so use the superclass except MapFeaturePhoto.DoesNotExist: # This may be a pending tree. Let's see if there # are pending audits pending_audits = Audit.objects\ .filter(instance=instance)\ .filter(model__in=['TreePhoto', 'MapFeaturePhoto'])\ .filter(model_id=photo_id)\ .filter(requires_auth=True) if len(pending_audits) > 0: # Process as pending and quit approve_or_reject_audits_and_apply(pending_audits, request.user, approved) return resp else: # Error - no pending or regular raise Http404('Photo Not Found') # Handle the id audit first all_audits = [] for audit in photo.audits(): if audit.field == 'id': all_audits = [audit] + all_audits else: all_audits.append(audit) for audit in all_audits: approve_or_reject_existing_edit(audit, request.user, approved) return resp
def update_choice(self, old_choice_value, new_choice_value, name=None): datatype = self.datatype_dict if self.iscollection: if name is None: raise ValidationError( {'name': trans('Name is required for collection fields')}) datatypes = {info['name']: info for info in datatype} datatype = self._validate_and_update_choice( datatypes[name], old_choice_value, new_choice_value) datatypes[name] = datatype self.datatype = json.dumps(datatypes.values()) self.save() vals = UserDefinedCollectionValue\ .objects\ .filter(field_definition=self)\ .extra(where=["data ? %s AND data->%s = %s"], params=[name, name, old_choice_value]) if new_choice_value is None: vals.hremove('data', name) else: vals.hupdate('data', {name: new_choice_value}) audits = Audit.objects.filter(model='udf:%s' % self.pk, field='udf:%s' % name) # If the string is empty we want to delete the audits # _update_choices_on_audits only does nf new_choice_value # is none if new_choice_value == '': new_choice_value = None self._update_choices_on_audits(audits, old_choice_value, new_choice_value) else: if name is not None: raise ValidationError({ 'name': trans('Name is allowed only for collection fields') }) self._update_choice_scalar(old_choice_value, new_choice_value) # indicate success to transaction manager return True
def _no_results_response(address, inregion=False): response = HttpResponse() response.status_code = 404 if inregion: err = trans("No results found in the area for %(address)s") else: err = trans("No results found for %(address)s") content = {'error': err % {'address': address}} response.write(json.dumps(content)) response['Content-length'] = str(len(response.content)) response['Content-Type'] = "application/json" return response
def update_user(request, user_id): user = get_object_or_404(User, pk=user_id) if user.pk != request.user.pk: return HttpResponseForbidden() data = json.loads(request.body) errors = {} for field in ALL_FIELDS: if field in data: if field in REQ_FIELDS and not field: errors[field] = [trans('This field cannot be empty')] else: if field == 'password': user.set_password(data[field]) else: setattr(user, field, data[field]) if errors: raise ValidationError(errors) else: user.save() return _context_dict_for_user(user)
def context_dict_for_resource(request, resource): context = context_dict_for_map_feature(request, resource) instance = request.instance # Give them 2 for adding the resource and answering its questions total_progress_items = 3 completed_progress_items = 2 photos = resource.photos() context['photos'] = map(context_dict_for_photo, photos) has_photos = len(photos) > 0 if has_photos: completed_progress_items += 1 context['upload_photo_endpoint'] = reverse( 'add_photo_to_map_feature', kwargs={'instance_url_name': instance.url_name, 'feature_id': resource.pk}) context['progress_percent'] = int(100 * ( completed_progress_items / total_progress_items) + .5) context['progress_messages'] = [] if not has_photos: context['progress_messages'].append(trans('Add a photo')) audits = _map_feature_audits(request.user, request.instance, resource) _add_audits_to_context(audits, context) return context
def short_descr(self): cls = _get_auditable_class(self.model) format_string = cls.action_format_string_for_audit(self) return format_string % {'field': self.field_display_name, 'model': trans(self.model).lower(), 'value': self.current_display_value}
def short_descr(self): cls = _lookup_model(self.model) format_string = cls.action_format_string_for_audit(self) return format_string % {'field': self.field.replace('_', ' '), 'model': trans(self.model).lower(), 'value': self.current_display_value}
def _validate_single_datatype(self, datatype): if 'type' not in datatype: raise ValidationError(trans('type required data type definition')) if datatype['type'] not in ['float', 'int', 'string', 'user', 'choice', 'date']: raise ValidationError(trans('invalid datatype')) if datatype['type'] == 'choice': choices = datatype.get('choices', None) if choices is None: raise ValidationError(trans('missing choices key for key')) for choice in choices: if not isinstance(choice, basestring): raise ValidationError(trans('Choice must be a string')) if choice is None or choice == '': raise ValidationError(trans('empty choice not allowed')) if len(choices) == 0: raise ValidationError(trans('empty choice list')) if len(choices) != len(set(choices)): raise ValidationError(trans('duplicate choices'))
def _validate_single_datatype(self, datatype): if 'type' not in datatype: raise ValidationError(trans('type required data type definition')) if datatype['type'] not in ['float', 'int', 'string', 'user', 'choice', 'date']: raise ValidationError(trans('invalid datatype')) if datatype['type'] == 'choice': choices = datatype.get('choices', None) if choices is None: raise ValidationError(trans('missing choices key for key')) for choice in choices: if not isinstance(choice, basestring): raise ValidationError(trans('Choice must be a string')) if choice is None or choice == '': raise ValidationError(trans('empty choice not allowed')) if len(choices) == 0: raise ValidationError(trans('empty choice list')) if len(choices) != len(set(choices)): raise ValidationError(trans('duplicate choices')) if 'default' in datatype: try: self.clean_value(datatype['default'], datatype) except ValidationError as e: raise ValidationError( 'Default must be valid for field: %(underlying_error)s' % {'underlying_error': e.message})
def title_for_map_feature(feature): # Cast allows the map feature subclass to handle generating # the display name feature = feature.cast_to_subtype() if feature.is_plot: tree = feature.current_tree() if tree: if tree.species: title = tree.species.common_name else: title = trans("Missing Species") else: title = trans("Empty Planting Site") else: title = feature.display_name return title
def get_map_view_context(request, instance): resource_classes = [MapFeature.get_subclass(type) for type in instance.map_feature_types] return { 'fields_for_add_tree': [ (trans('Tree Height'), 'Tree.height') ], 'resource_classes': resource_classes[1:] }
def udf_create(params, instance): data = _parse_params(params) name, model_type, datatype = (data['name'], data['model_type'], data['datatype']) udfs = UserDefinedFieldDefinition.objects.filter( instance=instance, # TODO: why isn't this also checking model name # is there some reason the same name can't appear # on more than one model? # Too scared to change this. name=name) if udfs.exists(): raise ValidationError( {'udf.name': [trans("A user defined field with name " "'%(udf_name)s' already exists") % {'udf_name': name}]}) if model_type not in ['Tree', 'Plot']: raise ValidationError( {'udf.model': [trans('Invalid model')]}) udf = UserDefinedFieldDefinition( name=name, model_type=model_type, iscollection=False, instance=instance, datatype=datatype) udf.save() field_name = udf.canonical_name # Add a restrictive permission for this UDF to all roles in the # instance for role in Role.objects.filter(instance=instance): FieldPermission.objects.get_or_create( model_name=model_type, field_name=field_name, permission_level=FieldPermission.NONE, role=role, instance=role.instance) return udf
def clean(self): super(MapFeature, self).clean() if not self.instance.bounds.contains(self.geom): raise ValidationError({ "geom": [ trans( "%(model)ss must be created inside the map boundaries") % {'model': self.display_name}] })