def save(self, parent_pk, current_user): record = m.cfd.objects.get(pk=parent_pk) formset_length = len(self) records = [record] records.extend(record.get_subsequent_contracts(formset_length - 1)) for index, item in enumerate(self.forms): if item.is_valid(): current_record = records[index] item.set_instance_values(current_record) with reversion.create_revision(): reversion.set_user(current_user) changed_fields = current_record.get_changed_fields() comments = "" for field in changed_fields.keys(): old_value, new_value = changed_fields[field] comments += f"Changed {m.cfd._meta.get_field(field).verbose_name} from {old_value} to {new_value};\n" reversion.set_comment(comments) current_record.save()
def validate_action(spending_request, user): """Valide la requête pour vérification pour l'administration, ou confirme la demande de paiement :param spending_request: :param user: :return: whether the spending request was successfully sent for review """ if spending_request.status == SpendingRequest.STATUS_VALIDATED: try: with reversion.create_revision(atomic=True): reversion.set_user(user) spending_request.operation = Spending.objects.create( group=spending_request.group, amount=-spending_request.amount) spending_request.status = SpendingRequest.STATUS_TO_PAY spending_request.save() except IntegrityError: return False return True if spending_request.status not in TRANSFER_STATES_MAP or not can_send_for_review( spending_request, user): return False with reversion.create_revision(): reversion.set_user(user) spending_request.status = TRANSFER_STATES_MAP[spending_request.status] if spending_request.status == SpendingRequest.STATUS_AWAITING_REVIEW: send_spending_request_to_review_email.delay(spending_request.pk) spending_request.save() return True
def form_valid(self, form): self.object = form.save(commit=False) # Generate files for field in self.object._meta.fields: if isinstance(field, FileField): obj_field = getattr(self.object, field.name) if obj_field: obj_field.save( obj_field.path, ContentFile(obj_field.read()), save=False ) if 'tags' in form.cleaned_data: self.object._tags = ','.join(form.cleaned_data['tags']) suggestion = Suggestion.objects.create( user=self.request.user, title=form.cleaned_data['title'], content_object=self.object, serialized_data=base64.b64encode(pickle.dumps(self.object)), status=u'pending', ) if self.request.user.has_perm('wiki.can_publish'): with reversion.create_revision(): suggestion.publish(is_auto=True) reversion.set_user(self.request.user) return HttpResponseRedirect(self.success_published) return HttpResponseRedirect(self.success_url)
def reactivate(request, id): name = _("Reactivate a Deactivated Enumeration") e = get_object_or_404(Enumeration, id=id) if e.status == "D": #Remove all gatekeeper errors. GateKeeperError.objects.filter(enumeration=e).delete() # Status A e.status = "A" e.last_updated_ip=request.META['REMOTE_ADDR'] e.enumerated_by = request.user e.save() msg = "This record has been reactivated by %s" % (request.user) Event.objects.create(enumeration=e, event_type="REACTIVATION", note= msg, details = msg, subject=REACTIVATED_SUBJECT, body = REACTIVATED_BODY) reversion.set_user(request.user) reversion.set_comment(msg) messages.success(request, msg) elif e.status == "A": messages.info(request, "This record was not deactivated. Nothing was done.") else: messages.info(request, "This record was not deactivated. Nothing was done.") return HttpResponseRedirect(reverse('report_index'))
def add_reference(request, slug=None): try: with reversion.create_revision(): doi = request.POST.get("reference_doi").lower() P = Protein.objects.get(slug=slug) ref, created = Reference.objects.get_or_create(doi=doi) P.references.add(ref) if not request.user.is_staff: P.status = "pending" msg = "User: {}\nProtein: {}\nReference: {}. {}\n\n{}".format( request.user.username, P, ref, ref.title, request.build_absolute_uri(P.get_absolute_url()), ) mail_managers("Reference Added", msg, fail_silently=True) P.save() reversion.set_user(request.user) reversion.set_comment("Added Reference: {}".format(ref)) try: uncache_protein_page(slug, request) except Exception as e: logger.error("failed to uncache protein: {}".format(e)) return JsonResponse({"status": "success"}) except Exception as e: return JsonResponse({"status": "failed", "msg": e})
def destroy(self, request, pk=None): ''' Deletes a person record if not associated with a user ''' queryset = Person.objects.filter(family_id=request.user.family_id) with reversion.create_revision(): person = get_object_or_404(queryset, pk=pk) if person.user_id: raise PermissionDenied( 'Profile is a user and cannot be deleted') person.delete() # Store some meta-information. reversion.set_user(request.user) reversion.set_comment('Delete ' + request.META.get('HTTP_X_REAL_IP')) message = { 'family_id': request.user.family_id, 'person_id': int(pk) } message_encoded = json.dumps(message) create_message('person_deleted_update_face_model', message_encoded) return Response(status=status.HTTP_204_NO_CONTENT)
def update(self, request, *args, **kwargs): """ Update object """ try: self.require_data(request) org_key = get_org_key_from_request(request) user_key = get_user_key_from_request(request) with reversion.create_revision(): if request.user and request.user.is_authenticated: reversion.set_user(request.user) if org_key: reversion.set_comment(f"API-key: {org_key.prefix}") if user_key: reversion.set_comment(f"API-key: {user_key.prefix}") r = super().update(request, *args, **kwargs) if "_grainy" in r.data: del r.data["_grainy"] return r except PermissionDenied as inst: return Response(status=status.HTTP_403_FORBIDDEN) except TypeError as inst: return Response(status=status.HTTP_400_BAD_REQUEST, data={"detail": str(inst)}) except ValueError as inst: return Response(status=status.HTTP_400_BAD_REQUEST, data={"detail": str(inst)}) finally: self.get_serializer().finalize_update(request)
def add_excerpt(request, pk=None): if not request.is_ajax(): return HttpResponseNotAllowed([]) try: with reversion.create_revision(): ref = Reference.objects.get(pk=pk) content = request.POST.get("excerpt_content") if content: # P.references.add(ref) Excerpt.objects.create(reference=ref, content=strip_tags(content), created_by=request.user) if not request.user.is_staff: msg = "User: {}\nReference: {}, {}\nExcerpt: {}\n{}".format( request.user.username, ref, ref.title, strip_tags(content), request.build_absolute_uri(ref.get_absolute_url()), ) mail_managers("Excerpt Added", msg, fail_silently=True) reversion.set_user(request.user) reversion.set_comment("Excerpt from {} added".format(ref)) return JsonResponse({"status": "success"}) except Exception as e: return JsonResponse({"status": "failed", "msg": e})
def form_valid(self, form): with transaction.atomic(), reversion.create_revision(): self.make_exam(form) self.exam.save() reversion.set_user(self.exam.editoritem.author) return redirect(self.get_success_url())
def edit_pii(request, id): name = _("Birtday, SSN, and ITIN") e = get_enumeration_user_manages_or_404(Enumeration, id, request.user) #Do not let this function work if the PII is already locked. if e.pii_lock: raise Http404() if request.method == 'POST': form = IndividualPIIForm(request.POST, instance=e) if form.is_valid(): e = form.save(commit=False) e.last_updated_ip=request.META['REMOTE_ADDR'] e.status="E" e.save() reversion.set_user(request.user) reversion.set_comment("Edit personal PII.") return HttpResponseRedirect(reverse('edit_enumeration', args=(id,))) else: #The form is invalid messages.error(request,_("Please correct the errors in the form.")) context = {'form': form,'name':name,} return render(request, 'generic/bootstrapform.html', context) #this is a GET context= {'name':name, 'form': IndividualPIIForm(instance=e)} return render(request, 'generic/bootstrapform.html', context)
def add_company(request): # FIXME: Make this view honor the returned_url if any for other apps that # will call it return_url = request.GET.get('return_url', None) form = EnterpriseForm(request.POST or None) if form.is_valid(): customer = form.save(commit=False) try: customer.id_user = Users.objects.get(login=request.user.email) except Users.DoesNotExist: try: # FIXME: Remove these and do it just when the connection is first made user = Users.objects.create(email=request.user.email, login=request.user.email) customer.id_user = user except: # The login is not the email ('admin'), if this fail then crash. customer.id_user = Users.objects.get(email=request.user.email) #Cyril wants this to be always 1 customer.company_type = CompanyTypes.objects.get(pk=1) with reversion.create_revision(): customer.save() reversion.set_user(request.user) reversion.set_comment("Company added from %s" % request.META.get('REMOTE_ADDR', None)) manager = Roles.objects.get(name='manager') Clients2Users.objects.create(user=customer.id_user, client=customer, role=manager) if return_url: return redirect(return_url) return redirect('home') return render(request, fo_get_template(request.get_host(), 'enterprise/add_company.html'), {'form':form, 'title':_("Add company")})
def make_profile(backend, user, response, is_new=False, *args, **kwargs): if is_new: if not hasattr(user, 'profile'): profile = Profile(user=user) profile.language = Language.get_python2() if backend.name == 'google-oauth2': profile.name = response['displayName'] elif backend.name in ('github', 'facebook') and 'name' in response: profile.name = response['name'] else: logger.info('Info from %s: %s', backend.name, response) profile.save() form = ProfileForm(instance=profile) else: data = backend.strategy.request_data() logger.info(data) form = ProfileForm(data, instance=user.profile) if form.is_valid(): with transaction.atomic(), reversion.create_revision(): form.save() reversion.set_user(user) reversion.set_comment('Updated on registration') return return render(backend.strategy.request, 'registration/profile_creation.jade', { 'title': 'Create your profile', 'form': form })
def deactivate(request, id): name = _("Deactivate") e = get_object_or_404(Enumeration, id=id) #If status is already deactivated then redirect. if e.status == "D": messages.info(request, "This record was not deactive so nothing was done. The record was not rejected.") return HttpResponseRedirect(reverse('report_index')) if request.method == 'POST': form = DeactivationForm(request.POST, instance=e) if form.is_valid(): e = form.save(commit=False) e.last_updated_ip=request.META['REMOTE_ADDR'] e.status="D" e.deactivation_date = datetime.date.today() e.save() msg = "Enumeration %s has been deactivated by %s." % (e.number, request.user) Event.objects.create(enumeration=e, event_type="DEACTIVATION", note= msg, details=msg, body = DEACTIVATED_BODY, subject = DEACTIVATED_SUBJECT) reversion.set_user(request.user) comment = "Deactivation of %s" % (e.number) reversion.set_comment(comment) messages.success(request, msg) return HttpResponseRedirect(reverse('report_index')) else: #The form is invalid messages.error(request,_("Please correct the errors in the form.")) context = {'form': form,'name':name,} return render(request, 'generic/bootstrapform.html', context) #this is a GET context= {'name':name, 'form': DeactivationForm(instance=e)} return render(request, 'generic/bootstrapform.html', context)
def save(self, commit=True): article = super(CreateNewsBlogArticleForm, self).save(commit=False) # Set owner to current user article.owner = self.user # If 'content' field has value, create a TextPlugin with same and add # it to the PlaceholderField content = clean_html(self.cleaned_data.get('content', ''), False) if content and permissions.has_plugin_permission( self.user, 'TextPlugin', 'add'): # If the article has not been saved, then there will be no # Placeholder set-up for this article yet, so, ensure we have saved # first. if not article.pk: article.save() if article and article.content: add_plugin( placeholder=article.content, plugin_type='TextPlugin', language=self.language_code, body=content, ) with transaction.atomic(): with create_revision(): article.save() if self.user: set_user(self.user) set_comment(ugettext("Initial version.")) return article
def edit_enhanced_enumeration(request, id): name = _("Edit Enhanced Profile Information") e = get_enumeration_user_manages_or_404(Enumeration, id, request.user) if request.method == 'POST': form = EnumerationEnhancementForm(request.POST, request.FILES, instance=e) if form.is_valid(): e = form.save(commit=False) e.last_updated_ip=request.META['REMOTE_ADDR'] e.status="E" e.save() reversion.set_user(request.user) reversion.set_comment("Edit Enhancements.") return HttpResponseRedirect(reverse('edit_enumeration', args=(e.id,))) else: #The form is invalid messages.error(request,_("Please correct the errors in the form.")) context = {'form': form,'name':name,} return render(request, 'generic/bootstrapform.html', context) #this is a GET context= {'name':name, 'form': EnumerationEnhancementForm(instance=e)} return render(request, 'generic/bootstrapform.html', context)
def save(self, *args, **kwargs): author = None if 'author' in kwargs.keys(): author = kwargs.pop('author') if 'at' in kwargs.keys(): at = kwargs.pop('at') else: at = timezone.now() create_revision = False try: last_version = reversion.get_unique_for_object(self)[0].field_dict except (IndexError, AttributeError, TypeError): create_revision = True last_version = {} for field in ('role', 'location', 'is_active'): if field == 'is_active': current_value = getattr(self, field, False) else: current_value = getattr(getattr(self, field), 'slug') if last_version.get(field, current_value) != current_value: create_revision = True break if create_revision: self.access_since = at with reversion.create_revision(): super(Provider, self).save(*args, **kwargs) reversion.set_user(author) else: super(Provider, self).save(*args, **kwargs)
def patch(self, request, *args, **kwargs): """ custom patch method to support django-reversion """ with reversion.create_revision(): reversion.set_user(request.user) reversion.set_comment('changed through the RESTful API from ip %s' % request.META['REMOTE_ADDR']) kwargs['partial'] = True return self.update(request, *args, **kwargs)
def reject(request, id): name = _("Activate an Enumeration") e = get_object_or_404(Enumeration, id=id) if e.status == "P": #Remove all gatekeeper errors. GateKeeperError.objects.filter(enumeration=e).delete() e.status = "R" e.last_updated_ip=request.META['REMOTE_ADDR'] e.enumerated_by = request.user e.save() msg = "This record has been rejected by %s" % (request.user) Event.objects.create(enumeration=e, event_type="REJECTION", note= msg, details=msg, body = RECJECTION_BODY, subject = REJECTION_SUBJECT) reversion.set_user(request.user) comment = "Application rejected" reversion.set_comment(comment) messages.success(request, "This record has been successfully been rejected.") else: messages.info(request, "This record was not pending so nothing was done. The record was not rejected.") return HttpResponseRedirect(reverse('report_index'))
def giro_status_ventar(modeladmin, request, queryset): with reversion.create_revision(): for g in queryset: g.status='V' g.save() reversion.set_comment("Giro status ventar admin action") reversion.set_user(request.user)
def submit(request, form): """ Ingest a piece of text into the database """ args = {'user': request.user, 'form': form, 'authenticated': request.user.is_authenticated()} (text, sentences) = parse_text_from_request(request) if None in (text, sentences): return _render(request, 'invalid.html', args) source_text = source_text_from_form(form) if source_text.is_dirty(): source_text.save() volume = volume_from_form(source_text, form, text) if volume.is_dirty(): volume.save() volume.sourcetextsentence_set.all().delete() with reversion.create_revision(): reversion.set_user(request.user) for sent in sentences: (text, begin, end) = sent SourceTextSentence.objects.create(volume=volume, sentence=text, start_line=begin, end_line=end) return _render(request, 'submitted.html', args)
def edit_item(request,iid,*args,**kwargs): item = get_object_or_404(MDR._concept,pk=iid).item if not user_can_edit(request.user, item): if request.user.is_anonymous(): return redirect(reverse('django.contrib.auth.views.login')+'?next=%s' % request.path) else: raise PermissionDenied base_form = MDRForms.wizards.subclassed_edit_modelform(item.__class__) if request.method == 'POST': # If the form has been submitted... form = base_form(request.POST,instance=item,user=request.user) if form.is_valid(): with transaction.atomic(), reversion.create_revision(): change_comments = form.data.get('change_comments',None) item = form.save() reversion.set_user(request.user) if not change_comments: change_comments = construct_change_message(request,form,None) reversion.set_comment(change_comments) return HttpResponseRedirect(url_slugify_concept(item)) else: form = base_form(instance=item,user=request.user) return render(request,"aristotle_mdr/actions/advanced_editor.html", {"item":item, "form":form, } )
def setup_revision(user, status): if user is not None: updater = django.contrib.auth.models.User.objects.get(username=user) else: updater = None reversion.set_user(updater) reversion.set_comment("Set status to %s" % (status.name, ))
def update_entities(model_dict, model_objects, appendable_keys): ''' model_dict is the key value store of updated elements model_objects are the models, these can be of type Actor, Bulletin or Incident delegates actual updating of fields to update_entity where the field is to be replaced and to update_entity_appendable where the field is to be added to ''' appendable_dict, remainder_dict = separate_field_types( model_dict, appendable_keys) for model in model_objects: model_dict_copy = remainder_dict.copy() model_dict_copy = update_related_actors(model_dict_copy, model) model = update_entity_appendable(appendable_dict, model) model = update_entity_status(model_dict, model) model = update_entity(model_dict_copy, model) user = model_dict['user'] with reversion.create_revision(): model.save() reversion.add_meta( VersionStatus, status='edited', user=user ) reversion.set_user(user) comment_text = model_dict['comment'] reversion.set_comment(comment_text)
def create_aggregated(cls, period, entity, author, *args, **kwargs): agg_report = cls.start(period, entity, author, \ type=Report.TYPE_AGGREGATED, *args, **kwargs) sources = ProvidedServicesReport.validated.filter(period=period, \ entity__in=entity.get_children()) if sources.count() == 0: agg_report.fill_blank() agg_report.save() for report in sources: for key, value in report.to_dict().items(): pv = getattr(agg_report, key) if not pv: nv = value elif pv in (cls.YES, cls.NO): if pv == cls.YES: nv = pv else: nv = value else: nv = pv + value setattr(agg_report, key, nv) agg_report.save() for report in sources: agg_report.sources.add(report) with reversion.create_revision(): agg_report.save() reversion.set_user(author.user) return agg_report
def military_address(request, address_id, enumeration_id): a = Address.objects.get(id=address_id) e = Enumeration.objects.get(id=enumeration_id) name = "Edit Military %s for %s" % (a.get_address_purpose_display(), e.name()) e = get_enumeration_user_manages_or_404(Enumeration, enumeration_id, request.user) address = Address.objects.get(id=address_id) if request.method == 'POST': form = MilitaryAddressForm(request.POST, instance=address) if form.is_valid(): a = form.save(commit=False) a.last_updated_ip=request.META['REMOTE_ADDR'] a.save() e.status="E" e.save() reversion.set_user(request.user) reversion.set_comment("Create/Edit Military Address") return HttpResponseRedirect(reverse('edit_enumeration', args=(enumeration_id, ))) else: #The form is invalid messages.error(request,_("Please correct the errors in the form.")) context = {'form': form,'name':name,} return render(request, 'generic/bootstrapform.html', context) #this is a GET context= {'name':name, 'form': MilitaryAddressForm(instance=address)} return render(request, 'generic/bootstrapform.html', context)
def self_take_over(request): name = "Take control of your individual provider identifer" if request.method == 'POST': form = SelfTakeOverForm(request.POST) if form.is_valid(): e = form.get_enumeration() #Give ownership to the individual e.managers.add(request.user) #make sure this user is also the surrogate s = Surrogate.objects.get(user=request.user) s.save() s.enumerations.add(e) s.save() reversion.set_user(request.user) reversion.set_comment("Self Take Over") messages.success(request,_("You are now in control of your own record.")) return HttpResponseRedirect(reverse('edit_enumeration', args=(e.id,))) else: #The form is invalid messages.error(request,_("Please correct the errors in the form.")) context = {'form': form,'name':name,} return render(request, 'generic/bootstrapform.html', context) #this is a GET context= {'name':name, 'form': SelfTakeOverForm()} return render(request, 'generic/bootstrapform.html', context)
def add_other_taxonomies(request, enumeration_id): name = _("Add Other Taxonomies") e = get_enumeration_user_manages_or_404(Enumeration, enumeration_id, request.user) if request.method == 'POST': form = OtherTaxonomyForm(request.POST, instance=e) if form.is_valid(): e = form.save(commit=False) e.last_updated_ip=request.META['REMOTE_ADDR'] e.save() form.save() form.save_m2m() reversion.set_user(request.user) reversion.set_comment("Added/Changed other taxonomies.") messages.success(request,_("Other taxonomies were added/changed.")) return HttpResponseRedirect(reverse('edit_enumeration', args=(enumeration_id,))) else: #The form is invalid messages.error(request,_("Please correct the errors in the form.")) context = {'form': form,'name':name,} return render(request, 'generic/bootstrapform.html', context) #this is a GET context= {'name':name, 'form': OtherTaxonomyForm(instance=e)} return render(request, 'generic/bootstrapform.html', context)
def run_merge_tables(self, **kwargs): source_config_entity = self.config_entity target_config_entity = self.target_config_entity print " source" print source_config_entity print " target" print target_config_entity source_feature_class = source_config_entity.db_entity_feature_class(self.db_entity_key) source_db_entity = source_config_entity.db_entity_by_key(self.db_entity_key) # resolve the target table by looking at the import table of the source db_entity target_db_entity_key = source_db_entity.feature_class_configuration_as_dict.get("import_from_db_entity_key") target_feature_class = target_config_entity.db_entity_feature_class(target_db_entity_key) # filter the target features by their approval status source_features = source_feature_class.objects.filter(approval_status="approved") # iterate over the features and merge approved rows into the target table for source_feature in source_features: with transaction.commit_on_success(), reversion.create_revision(): target_feature = target_feature_class.objects.get(id=source_feature.id) target_feature.__dict__.update(**source_feature.__dict__) target_feature.save() target_feature.comment = "Merge from ConfigEntity %s" % source_config_entity.key # If we have comments defined on the base table if hasattr(target_feature, "comments"): target_feature.comments = target_feature.comment reversion.set_user(self.updater) reversion.set_comment(target_feature.comment) # reset the approval field to null after changes are committed to the target source_feature.approval_status = None source_feature.save()
def handle_edit(request, document): context = RequestContext(request) if request.method == "POST": form = TextForm(request.POST) if form.is_valid(): cleaned_data = form.cleaned_data document.text = cleaned_data["text"] document.type = cleaned_data["type"] document.author = request.user if document.title != cleaned_data["title"]: # if the user changed the title we have to delete the old version # because the url_title will change, too... document.title = cleaned_data["title"] new_document = Document( title=document.title, text=document.text, type=document.type, author=document.author ) document.delete() document = new_document # save the document and also save the user and the comment the user added with transaction.atomic(), reversion.create_revision(): document.save() reversion.set_user(request.user) reversion.set_comment(cleaned_data["comment"]) raise FormValidException else: context["errors"] = form.errors context["form"] = form else: form_data = {"title": document.title, "text": document.text, "type": document.type} context["form"] = TextForm(form_data) context["document"] = document return context
def curriculum_view(request, slug): pdf = request.GET.get('pdf', False) try: curriculum = get_object_or_404(Curriculum, slug=slug) except Curriculum.DoesNotExist: raise ContinueResolving if request.user.is_staff: units = Unit.objects.filter(curriculum=curriculum) else: units = Unit.objects.filter(curriculum=curriculum, login_required=False) # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = ChangelogForm(request.POST) # check whether it's valid: if form.is_valid(): with reversion.create_revision(): changelog_user = User.objects.get(username=settings.CHANGELOG_USER) curriculum.save() # Store some meta-information. reversion.set_user(changelog_user) reversion.set_comment(form.cleaned_data['comment']) return HttpResponseRedirect(curriculum.get_absolute_url()) # if a GET (or any other method) we'll create a blank form form = ChangelogForm() changelog = Version.objects.get_for_object(curriculum).filter(revision__user__username=settings.CHANGELOG_USER) return render(request, 'curricula/curriculum.html', {'curriculum': curriculum, 'pdf': pdf, 'units': units, 'form': form, 'changelog': changelog})
def create_from(cls, period, entity, author): # create empty agg_report = cls.start(entity, period, author) # find list of sources indiv_sources = ChildrenMortalityReport \ .objects \ .filter(dod__gte=period.start_on, dod__lte=period.end_on, death_location__in=entity.get_children()) agg_sources = cls.objects.filter(period=period, entity__in=entity.get_children()) sources = list(indiv_sources) + list(agg_sources) # loop on all sources for source in sources: if isinstance(source, ChildrenMortalityReport): cls.update_instance_with_indiv(agg_report, source) elif isinstance(source, cls): cls.update_instance_with_agg(agg_report, source) # keep a record of all sources for report in indiv_sources: agg_report.indiv_sources.add(report) for report in agg_sources: agg_report.agg_sources.add(report) with reversion.create_revision(): agg_report.save() reversion.set_user(author.user) return agg_report
def delete_study(request, pk): try: study = Study.objects.get(pk=pk) except ObjectDoesNotExist: msg = "Error study matching query does not exist." messages.add_message(request, messages.ERROR, ugettext(msg)) return redirect('/lifespan/studies/') form = DeleteStudyForm(request.POST or None) if request.method == "POST" and form.is_valid: if 'cancel' in request.POST: return redirect('/lifespan/study/%s' % pk) else: with reversion.create_revision(): try: if 'delete_study' in request.POST: study.delete() if 'delete_reference' in request.POST: study.delete() study.reference.delete() except AttributeError: msg = "Error study did not have a reference associated." messages.add_message(request, messages.ERROR, ugettext(msg)) reversion.set_user(request.user) comment = request.POST['comment'] or "Deleted study" reversion.set_comment(comment) log(request, study, comment) return redirect('/lifespan/studies/') ctx = {'study': study, 'form': form} return render_to_response('lifespan/delete_study.html', ctx, context_instance=RequestContext(request))
def obj_create(self, bundle, **kwargs): username = bundle.request.GET['username'] user = User.objects.filter(username=username)[0] status_update = StatusUpdate.objects.get(status_en='Human Created') if can_assign_users(user) is False and 'assigned_user' in bundle.data: del(bundle.data['assigned_user']) comment_uri = self.create_comment( bundle.data['comment'], status_update.id, user ) bundle.data['incident_comments'] = [ comment_uri ] with reversion.create_revision(): bundle = super(IncidentResource, self)\ .obj_create(bundle, **kwargs) reversion.add_meta( VersionStatus, status='created', user=user ) reversion.set_user(user) reversion.set_comment(bundle.data['comment']) update_object.delay(username) return bundle
def registration_step_personal_details(request, eventid=None): """ Step in registration process where user fills in personal details """ event = get_object_or_404(Event, pk=eventid) address = None if hasattr(request.user, 'address'): address = request.user.address if request.method == 'POST': pd_form = PersonalDetailForm(request.POST, instance=address) if pd_form.is_valid(): with reversion.create_revision(): address = pd_form.save(commit=False) # We can't save yet because user needs to be set address.user = request.user address.save() reversion.set_user(request.user) reversion.set_comment(_("Personal info updated via frontend. The following " "fields changed: %(fields)s" % {'fields': ", ".join(pd_form.changed_data)})) messages.success(request, _('Your personal information was successfully updated!'), extra_tags='bg-success') # add bootstrap css class # TODO: send verification e-mail for e-address after figuring out what to use # Make registration and set status to 'in STATUS_PREPARATION_IN_PROGRESS' registration = Registration.objects.create(user=request.user, event=event, status=Registration.STATUS_PREPARATION_IN_PROGRESS) registration.save() return redirect('events:medicaldetailform', eventid=event.id) else: messages.error(request, _('Please correct the error below.'), extra_tags='bg-danger') else: pd_form = PersonalDetailForm(instance=address) return render(request, 'events/editpersonaldetails.html', { 'pd_form': pd_form, 'event': event, })
def registration_step_medical_details(request, eventid=None): """ Step in registration process where user fills in medical details """ mdetails = None if hasattr(request.user, 'medicaldetails'): mdetails = request.user.medicaldetails event = get_object_or_404(Event, pk=eventid) if request.method == 'POST': md_form = MedicalDetailForm(request.POST, instance=mdetails) if md_form.is_valid(): with reversion.create_revision(): details = md_form.save(commit=False) details.user = request.user details.save() reversion.set_user(request.user) reversion.set_comment(_("Medical info updated via frontend. The following " "fields changed: %(fields)s" % {'fields': ", ".join(md_form.changed_data)})) messages.success(request, _('Your medical information was successfully updated!'), extra_tags='bg-success') # add bootstrap css class return redirect('events:optionsform', eventid=event.id) else: messages.error(request, _('Please correct the error below.'), extra_tags='bg-danger') else: md_form = MedicalDetailForm(instance=mdetails) return render(request, 'events/editmedicaldetails.html', { 'md_form': md_form, 'event': event, })
def form(request, issue): form = IssueForm(instance=issue) if request.method == "POST": form = IssueForm(request.POST, instance=issue) if form.is_valid(): with reversion.create_revision(): reversion.set_user(request.user) issue = form.save() # django-reversion detects changes by listening for post_save # signals; thus it doesn't get up-to-date tags as they're saved # after the Issue. Call save to fire a signal and fix this. issue.save() logging.getLogger("email").info("Issue Saved", extra={"body": "%s %s an issue.\n\nhttp://govmonitor.org%s" % ( request.user.get_full_name(), "saved", reverse("core:issues:show", args=(issue.pk, issue.slug)) ) }) return redirect("core:issues:show", issue_pk=issue.pk, issue_slug=issue.slug) return {"form": form}
def save(self, bundle, skip_errors=False): """ This is a copy of the parent method, but with the object save modified for versioning :param bundle: :param skip_errors: :return: """ self.is_valid(bundle) if bundle.errors and not skip_errors: raise ImmediateHttpResponse(response=self.error_response(bundle.request, bundle.errors)) # Check if they're authorized. if bundle.obj.pk: self.authorized_update_detail(self.get_object_list(bundle.request), bundle) else: self.authorized_create_detail(self.get_object_list(bundle.request), bundle) # Save FKs just in case. self.save_related(bundle) # Save the main object. with transaction.commit_on_success(), reversion.create_revision(): bundle.obj.save() reversion.set_user(self.resolve_user(bundle.request.GET)) reversion.set_comment(bundle.data['comment'] or '') # Comment cannot be null bundle.objects_saved.add(self.create_identifier(bundle.obj)) # Now pick up the M2M bits. m2m_bundle = self.hydrate_m2m(bundle) self.save_m2m(m2m_bundle) return bundle
def post(self, request, *args, **kwargs): data = request.POST.dict().copy() try: self.model, editable_fields = self.get_editable_model_and_fields(data) except NoPermission as e: return HttpResponseForbidden( json.dumps(dict(message=e.message)), content_type='application/json') if 'slugfield' in data: self.slug_field = data.pop('slugfield') self.kwargs.update(data) obj = self.get_object() for fieldname in editable_fields: if fieldname in data: obj.__setattr__(fieldname, data.pop(fieldname)) if REVERSION_INSTALLED: with reversion.create_revision(): obj.save() reversion.set_user(request.user) reversion.set_comment("Contenteditable") else: obj.save() # TODO only save if changed return HttpResponse( json.dumps(dict(message='ok')), content_type='application/json')
def add_protein_excerpt(request, slug=None): try: with reversion.create_revision(): doi = request.POST.get("excerpt_doi").lower() P = Protein.objects.get(slug=slug) content = request.POST.get("excerpt_content") if content: ref, created = Reference.objects.get_or_create(doi=doi) P.references.add(ref) excerpt = Excerpt.objects.create(reference=ref, content=strip_tags(content), created_by=request.user) excerpt.proteins.add(P) if not request.user.is_staff: msg = "User: {}\nProtein: {}\nReference: {}, {}\nExcerpt: {}\n{}".format( request.user.username, P, ref, ref.title, strip_tags(content), request.build_absolute_uri(P.get_absolute_url()), ) mail_managers("Excerpt Added", msg, fail_silently=True) P.save() reversion.set_user(request.user) reversion.set_comment("Added Excerpt from {}".format(ref)) try: uncache_protein_page(slug, request) except Exception as e: logger.error("failed to uncache protein: {}".format(e)) return JsonResponse({"status": "success"}) except Exception as e: return JsonResponse({"status": "failed", "msg": e})
def edit(request, pk): if request.method == 'GET': post = Post.objects.get(pk__exact=pk) form = PostForm(instance=post) Post.text = post.text elif request.method == 'POST': post = Post.objects.get(pk__exact=pk) # Tracking changes: changes = [] if post.title != request.POST['title']: s1 = post.title s2 = request.POST['title'] changes.append( 'title (%s)' % "".join(["-"] + s1.split(s2) if len(s1) > len(s2) else ["+"] + s2.split(s1))) if post.text != request.POST['text']: changes.append('text') if set([tag.name for tag in post.tags.all()]) != set( request.POST['tags'].split(', ')): changes.append('tags') if "images" in request.POST: dict = {} dict.update(request.POST) pre_images = set(dict['images']) post_images = set( [unicode(image.pk) for image in post.images.all()]) if pre_images != post_images: changes.append('images (%s)' % "; ".join(pre_images - post_images)) if "published" in request.POST: if not post.published: changes.append('published to True') elif post.published: changes.append('published to False') form = PostForm(request.POST, instance=post) if form.is_valid(): if changes: with reversion.create_revision(): post = form.save(commit=False) post.updater = request.user form.save() reversion.set_user(request.user) comment = 'Changed %s. %s' % ( ', '.join(changes), request.POST['comment'] or '') reversion.set_comment(comment) log(request, post, comment) else: post = form.save(commit=False) post.updater = request.user form.save() return HttpResponseRedirect('/blog/%s' % pk) return render_to_response('blog/edit.html', {'form': form}, context_instance=RequestContext(request))
def post(self, request, *args, **kwargs): """ custom put method to support django-reversion """ with reversion.create_revision(): reversion.set_user(request.user) reversion.set_comment( 'created through the RESTful API from ip %s' % request.META['REMOTE_ADDR']) return self.create(request, *args, **kwargs)
def form_valid(self, form): with transaction.atomic(), reversion.create_revision(): self.object = form.save(commit=False) self.object.extensions.set(form.cleaned_data['extensions']) self.object.save() reversion.set_user(self.request.user) return http.HttpResponse(json.dumps(self.form_valid_response_dict(form)), content_type='application/json')
def perform_update(self, serializer): with reversion.create_revision(): instance = serializer.save() reversion.set_user(self.request.user) reversion.set_comment('Updated using the API.') # TODO somehow check that the order is actually modified before sending the notification? instance.send_modified_notification(request=self.request)
def save(self): instance = None with transaction.atomic(), reversion.create_revision(): reversion.set_comment('API Save') reversion.set_user(self.context['request'].user) instance = super().save() return instance
def version(user=None, comment=None): with reversion.create_revision(): yield if user is not None: reversion.set_user(user) if comment is not None: reversion.set_comment(comment)
def form_valid(self, form): self.object = form.save(commit=False) self.object.set_change_user(self.request.user) with transaction.atomic(), reversion.create_revision(): reversion.set_user(self.request.user) self.object.save() return HttpResponseRedirect(self.get_success_url())
def delete_study(request, pk): """Depricated.""" with reversion.create_revision(): study = Study.objects.get(pk=pk) study.delete() reversion.set_user(request.user) reversion.set_comment(request.POST['comment'] or "Deleted study") return redirect('/lifespan/studies/')
def form_valid(self, form): marca = form.save() with reversion.create_revision(): reversion.set_user(self.request.user) reversion.set_comment("La marca '" + marca.nombre + "' ah sido creada") return super().form_valid(form)
def setUp(self): self.user = mommy.make(UserProfile, is_superuser=True) self.document = mommy.prepare(InformationDocument) with transaction.atomic(), reversion.create_revision(): self.document.save() reversion.set_user(self.user) reversion.set_comment('test version')
def form_valid(self, form): unidadmedida = form.save() with reversion.create_revision(): reversion.set_user(self.request.user) reversion.set_comment("La unidad de medida '" + unidadmedida.nombre + "' ah sido modificada") return super().form_valid(form)
def form_valid(self, form): categoria = form.save() with reversion.create_revision(): reversion.set_user(self.request.user) reversion.set_comment("La categoria '" + categoria.nombre + "' ah sido modificada") return super().form_valid(form)
def save(self, *args, **kwargs): with transaction.atomic(), reversion.create_revision(): if self.id: reversion.set_comment("updated ModelA") else: reversion.set_comment("created ModelA") reversion.set_user(self.updated_by_user) super(ModelA, self).save(*args, **kwargs)
def form_valid(self, form): producto = form.save() with reversion.create_revision(): reversion.set_user(self.request.user) reversion.set_comment("El producto '" + producto.nombre + "' ah sido creado") return super().form_valid(form)
def form_valid(self, form): with reversion.create_revision(): valid = super().form_valid(form) reversion.set_user(self.request.user) reversion.set_comment("Decision updated") msg = 'Decyzja dla "{}" została zaktualizowana.'.format(self.application.title) messages.success(self.request, msg) return valid
def post_save_hook(self, bundle, **kwargs): """ updates target graphs when creating new dependencies """ # TODO decide when to make a new version if True: with reversion.create_revision(): # TODO increment version number reversion.set_user(bundle.request.user) reversion.set_comment('change "' + bundle.obj.source.title + '" dependency') bundle.obj.target.save() if self.isnew: otarget = bundle.obj.target osource = bundle.obj.source concepts_to_traverse = [ ol.target for ol in otarget.dep_source.all() ] os_tgraph, created = TargetGraph.objects.get_or_create( leaf=osource) if created: os_tgraph.concepts.add(osource) add_concepts = os_tgraph.concepts.all() ot_tgraph, created = TargetGraph.objects.get_or_create( leaf=otarget) if created: ot_tgraph.concepts.add(otarget) prev_depth = ot_tgraph.depth ot_tgraph.depth = max(os_tgraph.depth + 1, prev_depth) depth_inc = 0 if ot_tgraph.depth > prev_depth: depth_inc = ot_tgraph.depth - prev_depth ot_tgraph.save() otarget.tgraph_leaf.concepts.add(*add_concepts) otarget.tgraph_leaf.dependencies.add( *osource.tgraph_leaf.dependencies.all()) otarget.tgraph_leaf.dependencies.add(bundle.obj) add_dependencies = otarget.tgraph_leaf.dependencies.all() concepts_traversed = {} # DFS to add concept/deps to the tgraph of concepts that have the target concept as a preq while len(concepts_to_traverse): cur_con = concepts_to_traverse.pop(0) if cur_con.id in concepts_traversed: continue concepts_traversed[cur_con.id] = True # add all concepts cur_con.tgraph_leaf.concepts.add(*add_concepts) if depth_inc: cur_con.tgraph_leaf.depth += depth_inc cur_con.tgraph_leaf.save() # add all deps cur_con.tgraph_leaf.dependencies.add(*add_dependencies) for ol in cur_con.dep_source.all(): concepts_to_traverse.append(ol.target) return bundle
def section_edit_view(request, section_id): section = get_object_or_404(m.Section, id=section_id) if request.method == 'POST': section_form = f.SectionEditForm(data=request.POST, instance=section) sources_formset = f.SectionSourcesFormSet(request.POST, instance=section, prefix="sources") web_resources_formset = f.SectionWebpageResourcesFormSet( request.POST, instance=section, prefix="wp_resources") # doc_resources_formset = f.SectionDocumentResourcesFormSet( # request.POST, instance=section, prefix="doc_resources") if section_form.is_valid() \ and sources_formset.is_valid() \ and web_resources_formset.is_valid(): # and doc_resources_formset.is_valid(): with reversion.create_revision(): section = section_form.save() sources_formset.save() # doc_resources_formset.save() web_resources_formset.save() section.compact_indexes() reversion.set_user(request.user) # Redirect user to the updated section return HttpResponseRedirect( reverse('learning:section', args=[section.id])) else: section_form = f.SectionEditForm(instance=section) sources_formset = f.SectionSourcesFormSet(instance=section, prefix="sources") web_resources_formset = f.SectionWebpageResourcesFormSet( instance=section, prefix="wp_resources") doc_resources_formset = f.SectionDocumentResourcesFormSet( instance=section, prefix="doc_resources") context = build_base_context(request) context['pcode'] = 'l_synopses_section' context['title'] = 'Editar %s' % section.title context['section'] = section context['form'] = section_form context['sources_formset'] = sources_formset context['web_resources_formset'] = web_resources_formset # context['doc_resources_formset'] = doc_resources_formset context['action_page'] = reverse('learning:section_edit', args=[section_id]) context['action_name'] = 'Editar' context['sub_nav'] = [{ 'name': 'Sínteses', 'url': reverse('learning:areas') }, { 'name': '...', 'url': '#' }, { 'name': section.title, 'url': reverse('learning:section', args=[section_id]) }, { 'name': 'Editar' }] return render(request, 'learning/section_management.html', context)
def person_detail(request, person_id=None): try: person = Person.objects.get(pk=person_id) except Person.DoesNotExist: person = None if person and hasattr(person, 'paypal'): paypal = person.paypal else: paypal = None if request.method == 'POST': person_form = PersonForm(request.POST, prefix='person', instance=person) paypal_form = PayPalForm(request.POST, prefix='paypal', instance=paypal) # avoid short circuit evaluation person_form_is_valid = person_form.is_valid() paypal_form_is_valid = person_form.is_valid() if person_form_is_valid and paypal_form_is_valid: with transaction.atomic(), reversion.create_revision(): person = person_form.save() paypal = paypal_form.save(commit=False) paypal.person = person paypal.save() reversion.set_user(request.user) messages.success(request, 'Saved Changes Successfully') if '_save_and_check_id' in request.POST: return HttpResponseRedirect( reverse(id_check, kwargs={'person_id': person.pk})) elif '_save_and_send_email' in request.POST: email_template_id = request.POST['_save_and_send_email'] email_template = EmailTemplate.objects.get( id=email_template_id) count = email_template.send(request.user, person) if count == 1: messages.success( request, 'Sent "{}" to "{}'.format(email_template, person)) elif count == 0: messages.error( request, 'Failed to Send "{}" to "{}'.format( email_template, person)) return HttpResponseRedirect(person.get_absolute_url()) else: return HttpResponseRedirect(person.get_absolute_url()) else: person_form = PersonForm(prefix='person', instance=person) paypal_form = PayPalForm(prefix='paypal', instance=paypal) data = {} data['person_form'] = person_form data['paypal_form'] = paypal_form data['email_records'] = EmailRecord.objects.filter(recipient=person) data['person'] = person data['id_checks'] = IDCheck.objects.filter(person=person) data['email_templates'] = EmailTemplate.objects.individual_recipient() return render(request, 'member_management/detail.html', data)
def replace(request, id): name = _("Replace an issued Enumeration number with a new number.") e = get_object_or_404(Enumeration, id=id) if e.has_ever_been_active: #create a candidate eumeration eight_digits = random.randrange(10000000, 19999999) prefixed_eight_digits = "%s%s" % (settings.LUHN_PREFIX, eight_digits) checkdigit = generate(prefixed_eight_digits) new_number = "%s%s" % (eight_digits, checkdigit) while Enumeration.objects.filter(number=new_number).count() > 0: eight_digits = random.randrange(10000000, 19999999) prefixed_eight_digits = "%s%s" % (settings.LUHN_PREFIX, eight_digits) checkdigit = generate(prefixed_eight_digits) new_number = "%s%s" % (eight_digits, checkdigit) #create a message msg = "The number %s has been replaced with %s" % (e.number, new_number) #Append the old number to the old_numbers field. e.old_numbers = "%s, %s" % (e.old_numbers, e.number) #Remove any command or whitespace from the begining if e.old_numbers.startswith(","): e.old_numbers = e.old_numbers[1:] if e.old_numbers.startswith(" "): e.old_numbers = e.old_numbers[1:] #Set the new number e.number = new_number #flag this recors as having been replaced e.is_number_replaced = True e.last_updated_ip = request.META['REMOTE_ADDR'] e.save() msg = "A new enumeration number %s was assigned." % (e.number) #Create an event Event.objects.create(enumeration=e, event_type="REENUMERATION", note=msg, details=msg, body=RENUMBERED_BODY, subject=RENUMBERED_SUBJECT) reversion.set_user(request.user) rmsg = "Replacement: %s", (msg) reversion.set_comment(rmsg) messages.success(request, msg) else: messages.info( request, "This record has never been active so a replacement is not allowed." ) return HttpResponseRedirect(reverse('report_index'))
def unit_view(request, slug, unit_slug): pdf = request.GET.get('pdf', False) try: curriculum = get_object_or_404(Curriculum, slug=slug) except Curriculum.DoesNotExist: raise ContinueResolving if request.user.is_staff: unit = get_object_or_404(Unit, curriculum=curriculum, slug=unit_slug) else: unit = get_object_or_404(Unit, curriculum=curriculum, slug=unit_slug, login_required=request.user.is_staff) # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = ChangelogForm(request.POST) # check whether it's valid: if form.is_valid(): with reversion.create_revision(): changelog_user = User.objects.get( username=settings.CHANGELOG_USER) unit.save() # Store some meta-information. reversion.set_user(changelog_user) reversion.set_comment(form.cleaned_data['comment']) return HttpResponseRedirect(unit.get_absolute_url()) # if a GET (or any other method) we'll create a blank form form = ChangelogForm() changelog = Version.objects.get_for_object(unit).filter( revision__user__username=settings.CHANGELOG_USER) if pdf: if curriculum.unit_template_override == 'curricula/pl_unit.html': template = 'curricula/pl_unit_lessons.html' else: template = 'curricula/unit_lessons.html' else: if curriculum.unit_template_override: template = unit.curriculum.unit_template_override else: template = 'curricula/unit.html' return render( request, template, { 'curriculum': curriculum, 'unit': unit, 'pdf': pdf, 'form': form, 'changelog': changelog })