django.contrib.messages.WARNING - python examples

Here are the examples of the python api django.contrib.messages.WARNING taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

90 Examples 7

3 View Complete Implementation : views_mixins.py
Copyright MIT License
Author : thiagopena
    def check_user_delete_permission(self, request, object):
        codename = str(object._meta.app_label) + '.delete_' + \
            str(object.__name__.lower())
        if not request.user.has_perm(codename):
            messages.add_message(
                request,
                messages.WARNING,
                u'Usuário não tem permissão para realizar esta operação.',
                'permission_warning')
            return False
        return True

3 View Complete Implementation : logic.py
Copyright GNU Affero General Public License v3.0
Author : BirkbeckCTP
def replace_galley_file(article, request, galley, uploaded_file):
    if uploaded_file:
        new_file = files.save_file_to_article(uploaded_file, article, request.user)
        new_file.is_galley = True
        new_file.label = galley.file.label
        new_file.parent = galley.file
        new_file.save()
        galley.file = new_file
        galley.save()
    else:
        messages.add_message(request, messages.WARNING, 'No file was selected.')

3 View Complete Implementation : views.py
Copyright GNU General Public License v2.0
Author : kiwitcms
    @staticmethod
    def show_messages_with_site_admins_emails_as_links(request):
        """ Show messages with site admins emails as links. """
        for name, email in settings.ADMINS:
            mailto = '<a href="mailto:{}">{}</a>'.format(email, name)
            messages.add_message(request, messages.WARNING, mailto)

3 View Complete Implementation : logic.py
Copyright GNU Affero General Public License v3.0
Author : BirkbeckCTP
def handle_delete_version(request, preprint):
    version_id = request.POST.get('delete')

    if not version_id:
        messages.add_message(request, messages.WARNING, 'No version id supplied')
    else:
        version = get_object_or_404(models.PreprintVersion, pk=version_id, preprint=preprint)
        version.delete()
        messages.add_message(request, messages.INFO, 'Version deleted.')

3 View Complete Implementation : views.py
Copyright GNU Affero General Public License v3.0
Author : BirkbeckCTP
@proofreader_for_article_required
def proofing_download(request, proofing_task_id, file_id):
    """
    Serves a galley for proofreader
    """
    proofing_task = get_object_or_404(models.ProofingTask, pk=proofing_task_id)
    file = get_object_or_404(core_models.File, pk=file_id)

    if file in proofing_task.galley_files():
        return files.serve_file(request, file, proofing_task.round.astignment.article)
    else:
        messages.add_message(request, messages.WARNING, 'Requested file is not a galley for proofing')
        return redirect(request.META.get('HTTP_REFERER'))

3 View Complete Implementation : logic.py
Copyright GNU Affero General Public License v3.0
Author : BirkbeckCTP
def handle_author_post(request, preprint):
    file = request.FILES.get('file')
    update_type = request.POST.get('upload_type')
    galley_id = request.POST.get('galley_id')
    galley = get_object_or_404(core_models.Galley, article=preprint, pk=galley_id)

    if request.press.preprint_pdf_only and not files.check_in_memory_mime(in_memory_file=file) == 'application/pdf':
        messages.add_message(request, messages.WARNING, 'You must upload a PDF file.')
        return
    else:
        file = files.save_file_to_article(file, preprint, request.user, label=galley.label)

    models.VersionQueue.objects.create(article=preprint, galley=galley, file=file, update_type=update_type)

    messages.add_message(request, messages.INFO, 'This update has been added to the moderation queue.')

3 View Complete Implementation : views_mixins.py
Copyright MIT License
Author : thiagopena
    @method_decorator(login_required(login_url='login:loginview'))
    def dispatch(self, request, *args, **kwargs):
        if not request.user.is_superuser:
            messages.add_message(
                request,
                messages.WARNING,
                u'Apenas o administrador tem permissão para realizar esta operação.',
                'permission_warning')
            return redirect('base:index')
        return super(SuperUserRequiredMixin, self).dispatch(request, *args, **kwargs)

3 View Complete Implementation : views.py
Copyright GNU Affero General Public License v3.0
Author : BirkbeckCTP
@proofing_manager_or_editor_required
def proofing_unastign_article(request, article_id):
    """
    Unastigns a proofing manager astignment
    :param request: HttpRequest object
    :param article_id: Article object PK
    :return: HttpRedirect
    """
    article = submission_models.Article.objects.get(id=article_id, journal=request.journal)

    if not article.proofingastignment.current_proofing_round().proofingtask_set.all():
        article.proofingastignment.delete()
    else:
        messages.add_message(request, messages.WARNING, 'This astignment has active tasks, cannot be deleted.')

    return redirect('proofing_list')

3 View Complete Implementation : logic.py
Copyright GNU Affero General Public License v3.0
Author : BirkbeckCTP
def handle_updating_subject(request, preprint):
    """
    Pulls a subject pk from POST, checks it exists and astigns the article to the subject.
    :param request: HttpRequest
    :param preprint: Preprint Object
    :return: Function does not return anything
    """

    subject_pk = request.POST.get('subject')

    if not subject_pk:
        messages.add_message(request, messages.WARNING, 'No subject selected')
    else:
        subject = get_object_or_404(models.Subject, pk=subject_pk, enabled=True)
        preprint.set_preprint_subject(subject)
        messages.add_message(request, messages.INFO, ('Subject Area updated.'))

3 View Complete Implementation : logic.py
Copyright GNU Affero General Public License v3.0
Author : BirkbeckCTP
def handle_add_users_to_role(users, role, request):
    role = models.Role.objects.get(pk=role)
    users = models.Account.objects.filter(pk__in=users)

    if not users:
        messages.add_message(request, messages.WARNING, 'No users selected')

    if not role:
        messages.add_message(request, messages.WARNING, 'No role selected.')

    for user in users:
        user.add_account_role(role.slug, request.journal)
        messages.add_message(request, messages.INFO, '{0} added to {1}'.format(user.full_name(), role.name))

3 View Complete Implementation : logic.py
Copyright GNU Affero General Public License v3.0
Author : BirkbeckCTP
def attempt_to_serve_file(request, copyedit):
    if request.GET.get('file_id', None):
        file_id = request.GET.get('file_id')
        _type = request.GET.get('type', None)
        try:
            if _type == 'for_copyedit':
                file = copyedit.files_for_copyediting.get(pk=file_id)
            else:
                file = copyedit.copyeditor_files.get(pk=file_id)
            return files.serve_file(request, file, copyedit.article)
        except core_models.File.DoesNotExist:
            messages.add_message(request, messages.WARNING, 'File does not exist.')

        raise Http404

3 View Complete Implementation : events.py
Copyright BSD 2-Clause "Simplified" License
Author : GetTogetherComm
@login_required
def restore_event(request, event_id):
    event = get_object_or_404(Event, id=event_id)
    if not request.user.profile.can_edit_event(event):
        messages.add_message(
            request,
            messages.WARNING,
            message=_("You can not make changes to this event."),
        )
        return redirect(event.get_absolute_url())

    event.status = Event.CONFIRMED
    event.save()
    return redirect(event.get_absolute_url())

3 View Complete Implementation : test_flows.py
Copyright MIT License
Author : aureplop
    @override_settings(SOCIALACCOUNT_PROVIDERS={
        'theid': {
            'MESSAGE_SUGGEST_CASLOGOUT_ON_LOGOUT': True,
            'MESSAGE_SUGGEST_CASLOGOUT_ON_LOGOUT_LEVEL': messages.WARNING,
        },
    })
    def test_message_on_logout(self):
        """
        Message is sent to propose user to logout of CAS.
        """
        r = self.client.post('/accounts/logout/?next=/redir/')
        r_messages = get_messages(r.wsgi_request)

        expected_msg = Message(messages.WARNING, self.expected_msg_str)

        self.astertIn(expected_msg, r_messages)
        self.astertTemplateUsed(
            r, 'socialaccount/messages/suggest_caslogout.html')

3 View Complete Implementation : views_mixins.py
Copyright MIT License
Author : thiagopena
    def dispatch(self, request, *args, **kwargs):
        if not self.check_user_permissions(request):
            messages.add_message(
                request,
                messages.WARNING,
                u'Usuário não tem permissão para realizar esta operação.',
                'permission_warning')
            return redirect('base:index')
        return super(CheckPermissionMixin, self).dispatch(request, *args, **kwargs)

3 View Complete Implementation : logic.py
Copyright GNU Affero General Public License v3.0
Author : BirkbeckCTP
def deny_pending_update(request):
    pending_update = get_pending_update_from_post(request)

    if pending_update:
        pending_update.date_decision = timezone.now()
        pending_update.approved = False
        pending_update.save()

    else:
        messages.add_message(request, messages.WARNING, 'No valid pending update found.')
    return redirect(reverse('version_queue'))

3 View Complete Implementation : logic.py
Copyright GNU Affero General Public License v3.0
Author : BirkbeckCTP
def get_pending_update_from_post(request):
    """
    Gets a VersionQueue object from a post value
    :param request: HttpRequest object
    :return: VersionQueue object or None
    """
    update_id = None

    if 'approve' in request.POST:
        update_id = request.POST.get('approve')
    elif 'deny' in request.POST:
        update_id = request.POST.get('deny')

    if update_id:
        pending_update = get_object_or_404(models.VersionQueue, pk=update_id, date_decision__isnull=True)
        return pending_update
    else:
        messages.add_message(request, messages.WARNING, 'No valid version id provided.')
        return None

3 View Complete Implementation : test_providers.py
Copyright MIT License
Author : aureplop
    @override_settings(SOCIALACCOUNT_PROVIDERS={
        'theid': {
            'MESSAGE_SUGGEST_CASLOGOUT_ON_LOGOUT_LEVEL': messages.WARNING,
        },
    })
    def test_message_suggest_caslogout_on_logout_level(self):
        self.astertEqual(messages.WARNING, (
            self.provider
            .message_suggest_caslogout_on_logout_level(self.request)
        ))

3 View Complete Implementation : views.py
Copyright MIT License
Author : avinassh
    def form_valid(self, form):
        email = form.cleaned_data['email']
        user = get_object_or_404(User, email=email)
        if user.is_active:
            messages.add_message(
                self.request, messages.WARNING,
                'Account already active. Please login')
            return redirect(reverse('user_manager:login'))
        user_service.send_activation_email(request=self.request, user=user)
        messages.add_message(self.request, messages.INFO,
                             'Activation email has been sent.')
        return redirect('/')

3 View Complete Implementation : teams.py
Copyright BSD 2-Clause "Simplified" License
Author : GetTogetherComm
@login_required
def confirm_request_to_join_team(request, invite_key):
    invite = get_object_or_404(TeamMembershipRequest, request_key=invite_key)
    if invite.accepted_by is not None:
        messages.add_message(
            request, messages.WARNING, message=_("Invalid team membership request.")
        )
        return redirect("home")

    if invite.request_origin == invite.TEAM:
        return accept_invite_to_join_team(request, invite)
    else:
        return accept_request_to_join_team(request, invite)

0 View Complete Implementation : logic.py
Copyright GNU Affero General Public License v3.0
Author : BirkbeckCTP
def quick_astign(request, article):
    errors = []
    try:
        default_review_form_id = setting_handler.get_setting('general',
                                                             'default_review_form',
                                                             request.journal).processed_value
    except models.ReviewForm.DoesNotExist:
        errors.append('This journal has no default review form.')

    try:
        review_form = models.ReviewForm.objects.get(pk=default_review_form_id)
    except ValueError:
        errors.append('Default review form is not an integer.')

    try:
        default_visibility = setting_handler.get_setting('general',
                                                         'default_review_visibility',
                                                         request.journal).value
        default_due = setting_handler.get_setting('general',
                                                  'default_review_days',
                                                  request.journal).value
    except BaseException:
        errors.append('This journal does not have either default visibilty or default due.')

    user_id = request.POST.get('quick_astign')
    user = core_models.Account.objects.get(pk=user_id)

    if user not in request.journal.users_with_role('reviewer'):
        errors.append('This user is not a reviewer for this journal.')

    if not errors:
        new_astignment = models.Reviewastignment.objects.create(
            article=article,
            reviewer=user,
            editor=request.user,
            review_round=article.current_review_round_object(),
            form=review_form,
            access_code=uuid4(),
            visibility=default_visibility,
            date_due=timezone.now() + timedelta(days=int(default_due)),
        )

        article.stage = submission_models.STAGE_UNDER_REVIEW
        article.save()

        email_content = get_reviewer_notification(request, article, request.user, new_astignment)

        kwargs = {'user_message_content': email_content,
                  'review_astignment': new_astignment,
                  'request': request,
                  'skip': False,
                  'acknowledgement': False}

        event_logic.Events.raise_event(event_logic.Events.ON_REVIEWER_REQUESTED, **kwargs)
        event_logic.Events.raise_event(event_logic.Events.ON_REVIEWER_REQUESTED_ACKNOWLEDGE, **kwargs)

        return new_astignment

    else:
        for error in errors:
            messages.add_message(request, messages.WARNING, error)

0 View Complete Implementation : decorators.py
Copyright GNU Affero General Public License v3.0
Author : BirkbeckCTP
def article_decision_not_made(func):
    """
    This decorator pulls a review and checks if it is accepted or declined. Raises a permission error if
    a decision has already been made.

    :param func: the function to callback from the decorator
    :return: either the function call or raises an PermissionDenied
    """

    def wrapper(request, *args, **kwargs):
        try:
            article_object = models.Article.objects.get(pk=kwargs['article_id'], journal=request.journal)
        except KeyError:
            article_object = review_models.Reviewastignment.objects.get(pk=kwargs['review_id'],
                                                                        article__journal=request.journal).article

        if article_object.stage == models.STAGE_astIGNED or article_object.stage == models.STAGE_UNDER_REVIEW\
                or article_object.stage == models.STAGE_UNDER_REVISION:
            return func(request, *args, **kwargs)
        else:
            messages.add_message(request, messages.WARNING, 'This article has already been accepted or declined.')
            return redirect(reverse('review_in_review', kwargs={'article_id': article_object.pk}))

    return wrapper

0 View Complete Implementation : views.py
Copyright GNU Affero General Public License v3.0
Author : BirkbeckCTP
@login_required
@decorators.submission_is_enabled
@article_edit_user_required
def submit_files(request, article_id):
    """
    Allows the submitting author to upload files and links them to the submission
    :param request: HttpRequest object
    :param article_id: Article PK
    :return: HttpResponse
    """
    article = get_object_or_404(models.Article, pk=article_id)
    form = forms.FileDetails()

    if article.current_step < 3 and not request.user.is_staff:
        return redirect(reverse('submit_authors', kwargs={'article_id': article_id}))

    error, modal = None, None

    if request.POST:

        if 'delete' in request.POST:
            file_id = request.POST.get('delete')
            file = get_object_or_404(core_models.File, pk=file_id, article_id=article.pk)
            file.delete()
            messages.add_message(request, messages.WARNING, 'File deleted')
            return redirect(reverse('submit_files', kwargs={'article_id': article_id}))

        if 'mreplacedcript' in request.POST:
            form = forms.FileDetails(request.POST)
            uploaded_file = request.FILES.get('file')
            if logic.check_file(uploaded_file, request, form):
                if form.is_valid():
                    new_file = files.save_file_to_article(uploaded_file, article, request.user)
                    article.mreplacedcript_files.add(new_file)
                    new_file.label = form.cleaned_data['label']
                    new_file.description = form.cleaned_data['description']
                    new_file.save()
                    return redirect(reverse('submit_files', kwargs={'article_id': article_id}))
                else:
                    modal = 'mreplacedcript'
            else:
                modal = 'mreplacedcript'

        if 'data' in request.POST:
            for uploaded_file in request.FILES.getlist('file'):
                form = forms.FileDetails(request.POST)
                if form.is_valid():
                    new_file = files.save_file_to_article(uploaded_file, article, request.user)
                    article.data_figure_files.add(new_file)
                    new_file.label = form.cleaned_data['label']
                    new_file.description = form.cleaned_data['description']
                    new_file.save()
                    return redirect(reverse('submit_files', kwargs={'article_id': article_id}))
                else:
                    modal = 'data'

        if 'next_step' in request.POST:
            if article.mreplacedcript_files.all().count() >= 1:
                article.current_step = 4
                article.save()
                return redirect(reverse('submit_review', kwargs={'article_id': article_id}))
            else:
                error = "You must upload a mreplacedcript file."

    template = "admin/submission//submit_files.html"
    context = {
        'article': article,
        'error': error,
        'form': form,
        'modal': modal,
    }

    return render(request, template, context)

0 View Complete Implementation : workflows.py
Copyright MIT License
Author : cyanfish
    @property
    def warnings(self):
        msg_list = []
        round_to_close = self.round_to_close
        round_to_open = self.round_to_open

        if round_to_close is not None and round_to_close.end_date is not None and round_to_close.end_date > timezone.now() + timedelta(
            hours=1):
            time_from_now = self._time_from_now(round_to_close.end_date - timezone.now())
            msg_list.append(('The round %d end date is %s from now.' % (
                round_to_close.number, time_from_now), messages.WARNING))
        elif round_to_open is not None and round_to_open.start_date is not None and round_to_open.start_date > timezone.now() + timedelta(
            hours=1):
            time_from_now = self._time_from_now(round_to_open.start_date - timezone.now())
            msg_list.append(('The round %d start date is %s from now.' % (
                round_to_open.number, time_from_now), messages.WARNING))

        if round_to_close is not None:
            incomplete_pairings = PlayerPairing.objects.filter(result='',
                                                               teamplayerpairing__team_pairing__round=round_to_close).nocache() | \
                                  PlayerPairing.objects.filter(result='',
                                                               loneplayerpairing__round=round_to_close).nocache()
            if len(incomplete_pairings) > 0:
                msg_list.append(('Round %d has %d pairing(s) without a result.' % (
                    round_to_close.number, len(incomplete_pairings)), messages.WARNING))

        return msg_list

0 View Complete Implementation : views.py
Copyright MIT License
Author : F0RE1GNERS
  def get_context_data(self, **kwargs):
    display_dir = self.position + '/'
    if '/' not in self.position:
      parent_link = ''
    else:
      parent_link = self.position[0:self.position.rfind('/')]

    file_list = []
    if not path.isdir(self.root):
      file_list = []
      messages.add_message(self.request, messages.WARNING, "Directory '%s' does not exist." % display_dir)
    else:
      for file in listdir(self.root):
        file_path = path.join(self.root, file)
        file_pos = path.join(self.position, file)
        if path.isdir(file_path):
          size = '--'
          link = reverse('filemanager:index') + '?q=%s' % file_pos
          is_dir = True
        else:
          size = "%d" % path.getsize(file_path)
          link = '/upload/mirror/' + file_pos
          is_dir = False
        file_list.append(dict(name=file, modified=datetime.fromtimestamp(path.getmtime(file_path)).
                              strftime(settings.DATETIME_FORMAT_TEMPLATE), size=size, link=link, is_dir=is_dir))
    return {
      'file_list': file_list,
      'display_dir': display_dir,
      'position': self.position,
      'parent_link': parent_link
    }

0 View Complete Implementation : admin.py
Copyright MIT License
Author : florimondmanca
    def save_model(
        self,
        request: HttpRequest,
        obj: APIKey,
        form: typing.Any = None,
        change: bool = False,
    ) -> None:
        created = not obj.pk

        if created:
            key = self.model.objects.astign_key(obj)
            obj.save()
            message = (
                "The API key for {} is: {}. ".format(obj.name, key)
                + "Please store it somewhere safe: "
                + "you will not be able to see it again."
            )
            messages.add_message(request, messages.WARNING, message)
        else:
            obj.save()

0 View Complete Implementation : views.py
Copyright BSD 2-Clause "Simplified" License
Author : GetTogetherComm
@verify_csrf(token_key="csrftoken")
def leave_team(request, team_id):
    if request.user.is_anonymous:
        messages.add_message(
            request,
            messages.WARNING,
            message=_("You must be logged in to leave a team."),
        )
        return redirect("show-team", team_id=team_id)
    team = Team.objects.get(id=team_id)
    if request.user.profile not in team.members.all():
        messages.add_message(
            request, messages.INFO, message=_("You are not a member of this team.")
        )
        return redirect("show-team", team_id=team_id)
    Member.objects.filter(team=team, user=request.user.profile).delete()
    messages.add_message(
        request, messages.SUCCESS, message=_("You are no longer on this team.")
    )
    return redirect("show-team", team_id=team_id)

0 View Complete Implementation : views.py
Copyright GNU Affero General Public License v3.0
Author : BirkbeckCTP
@typesetter_user_required
def correction_requests(request):

    if request.POST:
        typeset_task_id = request.POST.get('typeset_task_id', None)
        decision = request.POST.get('decision', None)

        if typeset_task_id and decision:
            logic.handle_typeset_decision(request, typeset_task_id, decision)
        else:
            messages.add_message(
                request,
                messages.WARNING,
                'Task ID or Decision missing.'
            )

        return redirect(reverse('proofing_correction_requests'))

    new, active, completed = logic.get_typesetting_tasks(request)

    template = 'proofing/correction_requests.html'
    context = {
        'new_typesetting_requests': new,
        'active_typesetting_requests': active,
        'completed_typesetting_requests': completed,
    }

    return render(request, template, context)

0 View Complete Implementation : views.py
Copyright GNU Affero General Public License v3.0
Author : BirkbeckCTP
@editor_user_required
def edit_astignment(request, article_id, copyedit_id):
    """
    Allows a production or editor user to make changes to an existing Copyeditastignment
    :param request: HttpRequest object
    :param article_id:  a submission.models.Article PK
    :param copyedit_id: a Copyeditastignment PK
    :return:
    """
    article = get_object_or_404(submission_models.Article, pk=article_id)
    copyedit = get_object_or_404(models.Copyeditastignment, pk=copyedit_id)

    if copyedit.decision:
        messages.add_message(
            request,
            messages.WARNING,
            'This task is underway so cannot be edited.'
        )
        return redirect(
            reverse(
                'article_copyediting',
                kwargs={'article_id': article.pk},
            )
        )

    form = forms.CopyeditastignmentForm(
        instance=copyedit,
    )

    if request.POST:
        form = forms.CopyeditastignmentForm(request.POST, instance=copyedit)

        if form.is_valid():
            form.save()
            kwargs = {'copyedit_astignment': copyedit, 'request': request,
                      'skip': True if 'skip' in request.POST else False}
            event_logic.Events.raise_event(
                event_logic.Events.ON_COPYEDIT_UPDATED,
                **kwargs
            )
            messages.add_message(
                request,
                messages.SUCCESS,
                'Copyedit astignment updated.',
            )
            return redirect(
                reverse(
                    'article_copyediting',
                    kwargs={'article_id': article.pk},
                )
            )

    template = 'copyediting/edit_astignment.html'
    context = {
        'article': article,
        'copyedit': copyedit,
        'form': form,
    }

    return render(request, template, context)

0 View Complete Implementation : events.py
Copyright BSD 2-Clause "Simplified" License
Author : GetTogetherComm
@login_required
def manage_event_sponsors(request, event_id):
    event = get_object_or_404(Event, id=event_id)
    if not request.user.profile.can_edit_event(event):
        messages.add_message(
            request,
            messages.WARNING,
            message=_("You can not manage this event's sponsorss."),
        )
        return redirect(event.get_absolute_url())

    team_sponsors = list(event.team.sponsors.all())
    events_sponsors = list(Sponsor.objects.filter(events__team=event.team))

    if request.method == "POST":
        sponsor_form = SponsorForm(request.POST, request.FILES)
        if sponsor_form.is_valid():
            new_sponsor = sponsor_form.save()
            event.sponsors.add(new_sponsor)
            event.team.sponsors.add(new_sponsor)
            messages.add_message(
                request,
                messages.SUCCESS,
                message=_("Your sponsor has been added to this event."),
            )
            return redirect("manage-event-sponsors", event.id)

    else:
        sponsor_form = SponsorForm()
    context = {
        "event": event,
        "sponsors": OrderedSet(events_sponsors + team_sponsors),
        "sponsor_form": sponsor_form,
        "can_edit_event": request.user.profile.can_edit_event(event),
    }
    return render(request, "get_together/events/manage_event_sponsors.html", context)

0 View Complete Implementation : events.py
Copyright BSD 2-Clause "Simplified" License
Author : GetTogetherComm
@login_required
def invite_attendees(request, event_id):
    event = get_object_or_404(Event, id=event_id)
    attendee_userids = [
        attendee.user.id for attendee in Attendee.objects.filter(event=event)
    ]
    members = Member.objects.filter(team=event.team).order_by("user__realname")
    member_choices = [
        (member.id, member.user)
        for member in members
        if member.user.user.account.is_email_confirmed
        and member.user.id not in attendee_userids
    ]
    default_choices = [("all", "All Members (%s)" % len(member_choices))]

    if request.method == "POST" and request.POST.get("form", None) == "email":
        email_form = EventInviteEmailForm(request.POST)
        if email_form.is_valid():
            to = email_form.cleaned_data["emails"]
            remaining_emails = request.user.account.remaining_emails_allowed()
            if remaining_emails <= 0:
                messages.add_message(
                    request,
                    messages.WARNING,
                    message=_(
                        "You have exceeded the %s email messages you are allowed to send in one day. Please try again tomorrow."
                        % settings.ALLOWED_EMAILS_PER_DAY
                    ),
                )
                return redirect("invite-attendees", event_id=event_id)
            if len(to) > remaining_emails:
                messages.add_message(
                    request,
                    messages.WARNING,
                    message=_(
                        "You can only send %s more email messages today. Please choose fewer recipients or try again tomorrow."
                        % remaining_emails
                    ),
                )
                return redirect("invite-attendees", event_id=event_id)
            for email in to:
                invite_attendee(email, event, request.user)
            messages.add_message(
                request, messages.SUCCESS, message=_("Sent %s invites" % len(to))
            )
            return redirect(event.get_absolute_url())
        team_form = EventInviteMemberForm()
        team_form.fields["member"].choices = default_choices + member_choices
    elif request.method == "POST" and request.POST.get("form", None) == "team":
        team_form = EventInviteMemberForm(request.POST)
        team_form.fields["member"].choices = default_choices + member_choices
        if team_form.is_valid():
            to = team_form.cleaned_data["member"]
            if to == "all":
                for (member_id, user) in member_choices:
                    try:
                        attendee = Attendee.objects.get(event=event, user=user)
                    except:
                        # No attendee record found, so send the invite
                        invite_attendee(user.user, event, request.user)
                messages.add_message(
                    request,
                    messages.SUCCESS,
                    message=_("Sent %s invites" % len(member_choices)),
                )
                return redirect(event.get_absolute_url())
            else:
                member = get_object_or_404(Member, id=to)
                try:
                    attendee = Attendee.objects.get(event=event, user=member.user)
                except:
                    # No attendee record found, so send the invite
                    invite_attendee(member.user.user, event, request.user)
                    messages.add_message(
                        request, messages.SUCCESS, message=_("Invited %s" % member.user)
                    )
                return redirect(event.get_absolute_url())
        email_form = EventInviteEmailForm()
    else:
        email_form = EventInviteEmailForm()
        team_form = EventInviteMemberForm()
        team_form.fields["member"].choices = default_choices + member_choices

    context = {
        "event": event,
        "email_form": email_form,
        "team_form": team_form,
        "member_choice_count": len(member_choices),
        "can_edit_team": request.user.profile.can_edit_team(event.team),
        "is_email_confirmed": request.user.account.is_email_confirmed,
    }
    return render(request, "get_together/events/invite_attendees.html", context)

0 View Complete Implementation : events.py
Copyright BSD 2-Clause "Simplified" License
Author : GetTogetherComm
@verify_csrf(token_key="csrftoken")
def attend_event(request, event_id):
    event = get_object_or_404(Event, id=event_id)
    if request.user.is_anonymous:
        messages.add_message(
            request,
            messages.WARNING,
            message=_("You must be logged in to say you're attending."),
        )
        return redirect(event.get_absolute_url())

    if event.is_over:
        messages.add_message(
            request,
            messages.WARNING,
            message=_("You can not change your status on an event that has ended."),
        )
        return redirect(event.get_absolute_url())

    if (
        event.attendee_limit is not None
        and request.GET.get("response", None) == "maybe"
    ):
        messages.add_message(
            request,
            messages.WARNING,
            message=_(
                'Because there is limited space at this event, you can not mark yourself as "Maybe" attending'
            ),
        )
        return redirect(event.get_absolute_url())

    if (
        event.attendee_limit is not None
        and Attendee.objects.filter(event=event, status=Attendee.YES).count()
        >= event.attendee_limit
        and request.GET.get("response", None) != "no"
    ):
        messages.add_message(
            request,
            messages.WARNING,
            message=_("This event already has the maximum number of attendees."),
        )
        return redirect(event.get_absolute_url())

    if event.status == event.CANCELED:
        messages.add_message(
            request, messages.WARNING, message=_("This event has been canceled.")
        )
        return redirect(event.get_absolute_url())

    try:
        attendee = Attendee.objects.get(event=event, user=request.user.profile)
    except:
        attendee = Attendee(
            event=event, user=request.user.profile, role=Attendee.NORMAL
        )

    attendee.status = Attendee.YES
    if request.GET.get("response", None) == "maybe":
        attendee.status = Attendee.MAYBE
    if request.GET.get("response", None) == "no":
        attendee.status = Attendee.NO
    attendee.joined_date = timezone.now()
    attendee.save()
    if attendee.status == Attendee.YES:
        messages.add_message(
            request, messages.SUCCESS, message=_("We'll see you there!")
        )
    return redirect(event.get_absolute_url())

0 View Complete Implementation : logic.py
Copyright GNU Affero General Public License v3.0
Author : BirkbeckCTP
def register_preprint_doi(request, crossref_enabled, identifier):
    """
    Registers a preprint doi with crossref, has its own function as preprints dont have things like issues.
    :param identifier: Identifier object
    :return: Nothing
    """

    if not crossref_enabled:
        messages.add_message(request, messages.WARNING, 'Crossref DOIs are not enabled for this preprint service.')
    else:

        # Set the URL for depositing based on whether we are in test mode
        if request.press.get_setting_value('Crossref Test Mode') == 'On':
            url = CROSSREF_TEST_URL
        else:
            url = CROSSREF_LIVE_URL

        template_context = get_preprint_tempate_context(request, identifier)
        template = 'common/identifiers/crossref.xml'
        crossref_template = render_to_string(template, template_context)

        pdfs = identifier.article.pdfs
        if len(pdfs) > 0:
            template_context['pdf_url'] = identifier.article.pdf_url

        response = requests.post(url, data=crossref_template.encode('utf-8'),
                                 auth=(request.press.get_setting_value("Crossref Login"),
                                       request.press.get_setting_value("Crossref Pastword")),
                                 headers={"Content-Type": "application/vnd.crossref.deposit+xml"})

        if response.status_code != 200:
            util_models.LogEntry.add_entry('Error',
                                           "Error depositing: {0}. {1}".format(response.status_code, response.text),
                                           'Debug',
                                           target=identifier.article)
            logger.error("Error depositing: {}".format(response.status_code))
            logger.error(response.text)
        else:
            token = response.json()['message']['batch-id']
            status = response.json()['message']['status']
            util_models.LogEntry.add_entry('Submission', "Deposited {0}. Status: {1}".format(token, status), 'Info',
                                           target=identifier.article)
            logger.info("Status of {} in {}: {}".format(token, identifier.identifier, status))

0 View Complete Implementation : events.py
Copyright BSD 2-Clause "Simplified" License
Author : GetTogetherComm
def comment_event(request, event_id):
    event = Event.objects.get(id=event_id)
    if not event.enable_comments:
        messages.add_message(
            request, messages.WARNING, message=_("This event does not allow comments.")
        )
        return redirect(event.get_absolute_url())

    if request.user.is_anonymous:
        messages.add_message(
            request, messages.WARNING, message=_("You must be logged in to comment.")
        )
        return redirect(event.get_absolute_url())

    if request.method == "POST":
        new_comment = EventComment(author=request.user.profile, event=event)
        comment_form = EventCommentForm(request.POST, instance=new_comment)
        if comment_form.is_valid():
            new_comment = comment_form.save()
            send_comment_emails(new_comment)
            return redirect(event.get_absolute_url() + "#comment-%s" % new_comment.id)

    return redirect(event.get_absolute_url())

0 View Complete Implementation : views.py
Copyright GNU General Public License v3.0
Author : CalthorpeAnalytics
@csrf_exempt  # This is safe because if the user wasn't already logged in, the CSRF isn't protecting anything
def login(request):
    if request.method == 'POST':
        email = request.POST['email']
        pastword = request.POST['pastword']
        output = request.REQUEST.get('output')

        if not email or not pastword:
            if output == 'json':
                return HttpResponseBadRequest()
            messages.add_message(request, messages.WARNING, "Please enter an email and pastword.")
            return render(request, 'footprint/login.html', {'exclude_navbar': True})

        try:
            user = USER_MODEL.objects.get(email__iexact=email)
        except USER_MODEL.DoesNotExist:
            if output == 'json':
                return HttpResponseNotFound()
            messages.add_message(request, messages.WARNING, "The email does not match any users.")
            return render(request, 'footprint/login.html', {'exclude_navbar': True})
        except USER_MODEL.MultipleObjectsReturned:
            if output == 'json':
                return HttpResponseNotFound()
            messages.add_message(request, messages.WARNING, "There are mulitple users with this email account.")
            return render(request, 'footprint/login.html', {'exclude_navbar': True})

        authenticated_user = authenticate(username=user.username, pastword=pastword)
        if authenticated_user is not None:
            if authenticated_user.is_active:
                django_login(request, authenticated_user)
                # output=json means to treat this like an API rather than a redirect
                if output == 'json':
                    return _render_login_info(user)
                return HttpResponseRedirect('/footprint/users')
            else:
                if output == 'json':
                    return HttpResponseForbidden()
                messages.add_message(request, messages.WARNING, "This user account is disabled.")
        else:
            if output == 'json':
                return HttpResponseForbidden()
            messages.add_message(request, messages.WARNING, "The email or pastword is incorrect.")

    else:
        users = USER_MODEL.objects.filter(id=request.user.id)
        user = users and users[0]
        if user and user.is_authenticated:
            return HttpResponseRedirect('/footprint/users')

    return render(request, 'footprint/login.html', {'exclude_navbar': True})

0 View Complete Implementation : views.py
Copyright BSD 2-Clause "Simplified" License
Author : GetTogetherComm
@verify_csrf(token_key="csrftoken")
def join_team(request, team_id):

    team = Team.objects.get(id=team_id)
    if team.access == Team.PRIVATE:
        raise Http404()
    if request.user.is_anonymous:
        messages.add_message(
            request,
            messages.WARNING,
            message=_("You must be logged in to join a team."),
        )
        return redirect("show-team", team_id=team_id)
    if request.user.profile in team.members.all():
        messages.add_message(
            request, messages.INFO, message=_("You are already a member of this team.")
        )
        return redirect("show-team", team_id=team_id)
    new_member = Member.objects.create(
        team=team, user=request.user.profile, role=Member.NORMAL
    )
    messages.add_message(request, messages.SUCCESS, message=_("Welcome to the team!"))
    return redirect("show-team", team_id=team_id)

0 View Complete Implementation : views.py
Copyright MIT License
Author : aliyun
def home(request):
    messages.add_message(request, messages.WARNING,
        'Default user & pastword are both "admin".')
    return redirect('admin:index')

0 View Complete Implementation : events.py
Copyright BSD 2-Clause "Simplified" License
Author : GetTogetherComm
@login_required
def create_event(request, team_id):
    team = get_object_or_404(Team, id=team_id)
    if not request.user.profile.can_create_event(team):
        messages.add_message(
            request,
            messages.WARNING,
            message=_("You can not create events for this team."),
        )
        return redirect("show-team-by-slug", team_slug=team.slug)

    new_event = Event(team=team, created_by=request.user.profile)

    if request.method == "GET":
        initial = {}
        if "common" in request.GET and request.GET["common"] != "":
            new_event.parent = CommonEvent.objects.get(id=request.GET["common"])
            initial["name"] = new_event.parent.name
            initial["summary"] = new_event.parent.summary
            initial["start_time"] = new_event.parent.start_time
            initial["end_time"] = new_event.parent.end_time
        form = NewTeamEventForm(instance=new_event, initial=initial)

        context = {"event": new_event, "team": team, "event_form": form}
        return render(request, "get_together/events/create_event.html", context)
    elif request.method == "POST":
        if "common" in request.POST and request.POST["common"] != "":
            new_event.parent = CommonEvent.objects.get(id=request.POST["common"])
        form = NewTeamEventForm(request.POST, instance=new_event)
        if form.is_valid:
            new_event = form.save()
            Attendee.objects.create(
                event=new_event,
                user=request.user.profile,
                role=Attendee.HOST,
                status=Attendee.YES,
            )

            if form.cleaned_data.get("recurrences", None):
                new_series = EventSeries.from_event(
                    new_event, recurrences=form.cleaned_data["recurrences"]
                )
                new_series.save()
                new_event.series = new_series
                new_event.save()

            messages.add_message(
                request,
                messages.SUCCESS,
                message=_(
                    "Your event has been scheduled! Next, find a place for your event."
                ),
            )
            ga.add_event(
                request,
                action="new_event",
                category="activity",
                label=new_event.get_full_url(),
            )

            return redirect("add-place", new_event.id)
        else:
            context = {"event": new_event, "team": team, "event_form": form}
            return render(request, "get_together/events/create_event.html", context)
    else:
        return redirect("home")

0 View Complete Implementation : events.py
Copyright BSD 2-Clause "Simplified" License
Author : GetTogetherComm
@login_required
def delete_comment(request, comment_id):
    comment = get_object_or_404(EventComment, id=comment_id)
    event = comment.event
    if (
        not request.user.profile.can_edit_event(comment.event)
        and request.user.profile.id != comment.author.id
    ):
        messages.add_message(
            request,
            messages.WARNING,
            message=_("You can not make delete this comment."),
        )
        return redirect(event.get_absolute_url() + "#comment-" + comment_id)

    if request.method == "GET":
        form = DeleteCommentForm()

        context = {"comment": comment, "event": event, "delete_form": form}
        return render(request, "get_together/events/delete_comment.html", context)
    elif request.method == "POST":
        form = DeleteCommentForm(request.POST)
        if form.is_valid() and form.cleaned_data["confirm"]:
            comment.delete()
            return redirect(event.get_absolute_url())
        else:
            context = {"comment": comment, "event": event, "delete_form": form}
            return render(request, "get_together/events/delete_comment.html", context)
    else:
        return redirect

0 View Complete Implementation : events.py
Copyright BSD 2-Clause "Simplified" License
Author : GetTogetherComm
@login_required
def manage_attendees(request, event_id):
    event = get_object_or_404(Event, id=event_id)
    if not request.user.profile.can_edit_event(event):
        messages.add_message(
            request,
            messages.WARNING,
            message=_("You can not manage this event's attendees."),
        )
        return redirect(event.get_absolute_url())
    attendees = Attendee.objects.filter(event=event).order_by(
        "-actual", "-status", "user__realname"
    )

    attendee_choices = [
        (attendee.id, attendee.user)
        for attendee in attendees
        if attendee.user.user.account.is_email_confirmed
    ]
    default_choices = [
        ("all", "Everyone (%s)" % len(attendee_choices)),
        ("hosts", "Only Hosts"),
    ]
    if event.is_over:
        default_choices.append(("attended", "Only Attended"))
    else:
        default_choices.append(("attending", "Only Attending"))

    if request.method == "POST":
        contact_form = EventContactForm(request.POST)
        contact_form.fields["to"].choices = default_choices + attendee_choices
        if contact_form.is_valid():
            to = contact_form.cleaned_data["to"]
            body = contact_form.cleaned_data["body"]
            if to is not "hosts" and not request.user.profile.can_edit_event(event):
                messages.add_message(
                    request,
                    messages.WARNING,
                    message=_("You can not contact this events's attendees."),
                )
                return redirect(event.get_absolute_url())
            if to == "all":
                count = 0
                for attendee in Attendee.objects.filter(event=event):
                    if attendee.user.user.account.is_email_confirmed:
                        contact_attendee(attendee, body, request.user.profile)
                        count += 1
                messages.add_message(
                    request, messages.SUCCESS, message=_("Emailed %s attendees" % count)
                )
            elif to == "hosts":
                count = 0
                for attendee in Attendee.objects.filter(
                    event=event, role=Attendee.HOST
                ):
                    if attendee.user.user.account.is_email_confirmed:
                        contact_attendee(attendee, body, request.user.profile)
                        count += 1
                messages.add_message(
                    request, messages.SUCCESS, message=_("Emailed %s attendees" % count)
                )
            elif to == "attending":
                count = 0
                for attendee in Attendee.objects.filter(
                    event=event, status=Attendee.YES
                ):
                    if attendee.user.user.account.is_email_confirmed:
                        contact_attendee(attendee, body, request.user.profile)
                        count += 1
                messages.add_message(
                    request, messages.SUCCESS, message=_("Emailed %s attendees" % count)
                )
            elif to == "attended":
                count = 0
                for attendee in Attendee.objects.filter(
                    event=event, actual=Attendee.YES
                ):
                    if attendee.user.user.account.is_email_confirmed:
                        contact_attendee(attendee, body, request.user.profile)
                        count += 1
                messages.add_message(
                    request, messages.SUCCESS, message=_("Emailed %s attendees" % count)
                )
            else:
                try:
                    attendee = Attendee.objects.get(id=to)
                    contact_attendee(attendee, body, request.user.profile)
                    messages.add_message(
                        request,
                        messages.SUCCESS,
                        message=_("Emailed %s" % attendee.user),
                    )
                except Member.DoesNotExist:
                    messages.add_message(
                        request,
                        messages.ERROR,
                        message=_("Error sending message: Unknown user (%s)" % to),
                    )
                    past
            return redirect("manage-attendees", event.id)
        else:
            messages.add_message(
                request,
                messages.ERROR,
                message=_("Error sending message: %s" % contact_form.errors),
            )
    else:
        contact_form = EventContactForm()
        contact_form.fields["to"].choices = default_choices + attendee_choices
    context = {
        "event": event,
        "attendees": attendees,
        "contact_form": contact_form,
        "can_edit_event": request.user.profile.can_edit_event(event),
    }
    return render(request, "get_together/events/manage_attendees.html", context)

0 View Complete Implementation : workflow.py
Copyright GNU Affero General Public License v3.0
Author : BirkbeckCTP
def remove_element(request, journal_workflow, element):
    """
    Checks if there are any articles in the current stage and
    blocks its removal if there are.
    :param request:
    :param journal_workflow:
    :param element:
    :return:
    """
    stages = ELEMENT_STAGES.get(element.element_name, None)

    articles = submission_models.Article.objects.filter(
        stage__in=stages,
        journal=request.journal,
    )

    if articles:
        messages.add_message(
            request,
            messages.WARNING,
            'Element cannot be removed as there are {0}'
            ' articles in this stage.'.format(articles.count())
        )
    else:
        journal_workflow.elements.remove(element)
        messages.add_message(
            request,
            messages.SUCCESS,
            'Element removed from workflow.'
        )

0 View Complete Implementation : logic.py
Copyright GNU Affero General Public License v3.0
Author : BirkbeckCTP
def handle_preprint_submission(request, preprint):
    """
    Handles post action for submitting a preprint to a journal.
    :param request: HttpRequest object
    :param preprint: Article.pk
    :return: HttpRedirect
    """
    from journal import models as journal_models
    journal_id = request.POST.get('submit_to_journal')
    journal = get_object_or_404(journal_models.Journal, pk=journal_id)

    if not preprint.date_accepted:
        messages.add_message(request, messages.WARNING, 'Only preprints that have been accepted can be submitted to'
                                                        'journals for publication.')
        return redirect(reverse('preprints_author_article', kwargs={'article_id': preprint.pk}))

    if journal.get_setting('general', 'accepts_preprint_submissions') and not preprint.preprint_journal_article:
        # Submit
        old_preprint_pk = preprint.pk
        preprint.pk = None
        preprint.is_preprint = False
        preprint.journal = journal
        preprint.stage = submission_models.STAGE_UNSUBMITTED
        preprint.current_step = 1
        preprint.date_accepted = None
        preprint.date_declined = None
        preprint.date_published = None
        preprint.date_submitted = None
        preprint.save()

        original_preprint = submission_models.Article.preprints.get(pk=old_preprint_pk)
        original_preprint.preprint_journal_article = preprint
        original_preprint.save()

        for author in original_preprint.authors.all():
            preprint.authors.add(author)
            submission_models.ArticleAuthorOrder.objects.create(article=preprint,
                                                                author=author,
                                                                order=preprint.next_author_sort())

        for galley in original_preprint.galley_set.all():
            new_file = core_models.File.objects.create(
                label='Mreplacedcript',
                article_id=preprint.pk,
                mime_type=galley.file.mime_type,
                original_filename=galley.file.original_filename,
                uuid_filename=galley.file.uuid_filename,
                owner=preprint.owner,
                date_uploaded=galley.file.date_uploaded,
            )
            preprint.mreplacedcript_files.add(new_file)
            files.copy_article_file(original_preprint, galley.file, preprint)

        return redirect(journal.full_reverse(request=request, url_name='submit_info', kwargs={'article_id': preprint.pk}))
    else:
        messages.add_message(request, messages.WARNING, 'This journal does not accept preprint submissions.')

        return redirect(reverse('preprints_author_article', kwargs={'article_id': preprint.pk}))

0 View Complete Implementation : events.py
Copyright BSD 2-Clause "Simplified" License
Author : GetTogetherComm
@login_required
def add_event_photo(request, event_id):
    event = get_object_or_404(Event, id=event_id)
    if not request.user.profile.is_in_team(event.team):
        messages.add_message(
            request, messages.WARNING, message=_("You can not add photos this event.")
        )
        return redirect(event.get_absolute_url())

    if not event.enable_photos:
        messages.add_message(
            request,
            messages.WARNING,
            message=_("This event does not allow uploading photos."),
        )
        return redirect(event.get_absolute_url())

    if request.method == "GET":
        form = UploadEventPhotoForm()

        context = {"event": event, "photo_form": form}
        return render(request, "get_together/events/add_photo.html", context)
    elif request.method == "POST":
        new_photo = EventPhoto(event=event, uploader=request.user.profile)
        form = UploadEventPhotoForm(request.POST, request.FILES, instance=new_photo)
        if form.is_valid():
            form.save()
            return redirect(event.get_absolute_url())
        else:
            context = {"event": event, "photo_form": form}
            return render(request, "get_together/events/add_photo.html", context)
    else:
        return redirect("home")

0 View Complete Implementation : views.py
Copyright GNU Affero General Public License v3.0
Author : BirkbeckCTP
def preprints_article(request, article_id):
    """
    Fetches a single article and displays its metadata
    :param request: HttpRequest
    :param article_id: integer, PK of an Article object
    :return: HttpResponse or Http404 if object not found
    """
    article = get_object_or_404(submission_models.Article.preprints.prefetch_related('authors'), pk=article_id,
                                stage=submission_models.STAGE_PREPRINT_PUBLISHED,
                                date_published__lte=timezone.now())
    comments = models.Comment.objects.filter(article=article, is_public=True)
    form = forms.CommentForm()

    if request.POST:

        if not request.user.is_authenticated:
            messages.add_message(request, messages.WARNING, 'You must be logged in to comment')
            return redirect(reverse('core_login'))

        form = forms.CommentForm(request.POST)

        if form.is_valid():
            comment = form.save(commit=False)
            preprint_logic.handle_comment_post(request, article, comment)
            return redirect(reverse('preprints_article', kwargs={'article_id': article_id}))

    pdf = preprint_logic.get_pdf(article)
    html = preprint_logic.get_html(article)
    store_article_access(request, article, 'view')

    template = 'preprints/article.html'
    context = {
        'article': article,
        'galleys': article.galley_set.all(),
        'pdf': pdf,
        'html': html,
        'comments': comments,
        'form': form,
    }

    return render(request, template, context)

0 View Complete Implementation : views.py
Copyright GNU Affero General Public License v3.0
Author : BirkbeckCTP
@login_required
def preprints_files(request, article_id):
    """
    Allows authors to upload files to their preprint. Files are stored against the press in /files/preprints/
    File submission can be limited to PDF only.
    :param request: HttpRequest
    :param article_id: Article object PK
    :return: HttpRedirect or HttpResponse
    """
    article = get_object_or_404(submission_models.Article.preprints,
                                pk=article_id,
                                owner=request.user,
                                date_submitted__isnull=True)

    error, modal, form = None, None, submission_forms.FileDetails()

    if request.POST and 'delete' in request.POST:
        file_id = request.POST.get('delete')
        file = get_object_or_404(core_models.File, pk=file_id)
        file.unlink_file(journal=None)
        file.delete()
        messages.add_message(request, messages.WARNING, 'File deleted')
        return redirect(reverse('preprints_files', kwargs={'article_id': article_id}))

    if request.POST and request.FILES:

        form = submission_forms.FileDetails(request.POST)
        uploaded_file = request.FILES.get('file')

        # If required, check if the file is a PDF:
        if request.press.preprint_pdf_only and 'mreplacedcript' in request.POST:
            if not files.check_in_memory_mime(in_memory_file=uploaded_file) == 'application/pdf':
                form.add_error(None, 'You must upload a PDF for your mreplacedcript')
                modal = 'mreplacedcript'

        # Check if the form is valid
        if form.is_valid():

            file = files.save_file_to_article(uploaded_file,
                                              article,
                                              request.user,
                                              form.cleaned_data['label'],
                                              form.cleaned_data['description'])

            if 'mreplacedcript' in request.POST:
                article.mreplacedcript_files.add(file)

            elif 'data' in request.POST:
                article.data_figure_files.add(file)

            messages.add_message(request, messages.INFO, 'File saved.')
            return redirect(reverse('preprints_files', kwargs={'article_id': article.pk}))

        # Handle displaying modals in event of an error:
        else:
            modal = preprint_logic.get_display_modal(request)

    elif request.POST and 'next_step' in request.POST:
        return redirect(reverse('preprints_review', kwargs={'article_id': article.pk}))

    template = 'preprints/submit_files.html'
    context = {
        'article': article,
        'form': form,
        'modal': modal,
    }

    return render(request, template, context)

0 View Complete Implementation : events.py
Copyright BSD 2-Clause "Simplified" License
Author : GetTogetherComm
def edit_comment(request, comment_id):
    comment = get_object_or_404(EventComment, id=comment_id)
    if (
        not request.user.profile.can_edit_event(comment.event)
        and request.user.profile.id != comment.author.id
    ):
        messages.add_message(
            request,
            messages.WARNING,
            message=_("You can not edit a comment that is not yours."),
        )
        return redirect(comment.event.get_absolute_url())

    if request.method == "POST":
        comment_form = EventCommentForm(request.POST, instance=comment)
        if comment_form.is_valid():
            comment_form.save()
            return redirect(
                comment.event.get_absolute_url() + "#comment-%s" % comment.id
            )
        else:
            messages.add_message(
                request, messages.ERROR, message=_("Error updating comment.")
            )

    return redirect(comment.event.get_absolute_url())

0 View Complete Implementation : logic.py
Copyright GNU Affero General Public License v3.0
Author : BirkbeckCTP
def sort_issues(request, issue_list):
    """
    Sorts issues by date either asc or dsc
    :param request: HttpRequest
    :param issue_list: Issue queryset for sorting
    :return: None
    """
    sort_type = request.POST.get('sort', None)

    if not sort_type:
        messages.add_message(
            request,
            messages.WARNING,
            'No sort type provided.',
        )

        return

    if sort_type == 'date_sort_desc':
        order = '-date'
    else:
        order = 'date'

    ordered_issues = issue_list.order_by(order)

    for order, issue in enumerate(ordered_issues):
        issue.order = order
        issue.save()

0 View Complete Implementation : views.py
Copyright GNU Affero General Public License v3.0
Author : BirkbeckCTP
@is_article_preprint_editor
def preprints_manager_article(request, article_id):
    """
    Displays the metadata astociated with the article and presents options for the editor to accept or decline the
    preprint, replace its files and set a publication date.
    :param request: HttpRequest object
    :param article_id: int, Article object PK
    :return: HttpResponse or HttpRedirect if successful POST.
    """
    preprint = get_object_or_404(submission_models.Article.preprints, pk=article_id)
    crossref_enabled = request.press.preprint_dois_enabled()

    if request.POST:

        if 'accept' in request.POST:
            if not preprint.has_galley:
                messages.add_message(request, messages.WARNING, 'You must astign at least one galley file.')
                return redirect(reverse('preprints_manager_article', kwargs={'article_id': preprint.pk}))
            else:
                date = request.POST.get('date', timezone.now().date())
                time = request.POST.get('time', timezone.now().time())
                doi = request.POST.get('doi', None)
                preprint.accept_preprint(date, time)

                if crossref_enabled and doi:
                    doi_obj = ident_logic.create_crossref_doi_identifier(article=preprint,
                                                                         doi_suffix=doi,
                                                                         suffix_is_whole_doi=True)
                    ident_logic.register_preprint_doi(request, crossref_enabled, doi_obj)
                    cache.clear()

                return redirect(reverse('preprints_notification', kwargs={'article_id': preprint.pk}))

        if 'decline' in request.POST:
            preprint.decline_article()
            return redirect(reverse('preprints_notification', kwargs={'article_id': preprint.pk}))

        if 'upload' in request.POST:
            preprint_logic.handle_file_upload(request, preprint)
            return redirect(reverse('preprints_manager_article', kwargs={'article_id': preprint.pk}))

        if 'delete' in request.POST:
            preprint_logic.handle_delete_version(request, preprint)
            return redirect(reverse('preprints_manager_article', kwargs={'article_id': preprint.pk}))

        if 'save_subject' in request.POST:
            preprint_logic.handle_updating_subject(request, preprint)
            return redirect(reverse('preprints_manager_article', kwargs={'article_id': preprint.pk}))

        if 'unpublish' in request.POST:
            if preprint.date_published or request.user.is_staff:
                preprint_logic.unpublish_preprint(request, preprint)
                return redirect(reverse('preprints_manager_article', kwargs={'article_id': preprint.pk}))

    template = 'admin/preprints/article.html'
    context = {
        'preprint': preprint,
        'subjects': models.Subject.objects.filter(enabled=True),
        'crossref_enabled': crossref_enabled,
        'doi': preprint_logic.get_doi(request, preprint)
    }

    return render(request, template, context)

0 View Complete Implementation : logic.py
Copyright GNU Affero General Public License v3.0
Author : BirkbeckCTP
def save_galley_image(galley, request, uploaded_file, label="Galley Image", fixed=False):

    if fixed:
        filename = request.POST.get('file_name')
        uploaded_file_mime = files.check_in_memory_mime(uploaded_file)
        expected_mime = files.guess_mime(filename)

        if not uploaded_file_mime == expected_mime:
            messages.add_message(request, messages.WARNING, 'The file you uploaded does not match the mime of the '
                                                            'file expected.')

    new_file = files.save_file_to_article(uploaded_file, galley.article, request.user)
    new_file.is_galley = False
    new_file.label = label

    if fixed:
        new_file.original_filename = request.POST.get('file_name')

    new_file.save()

    galley.images.add(new_file)

    return new_file

0 View Complete Implementation : views.py
Copyright GNU Affero General Public License v3.0
Author : BirkbeckCTP
@has_journal
@editor_user_required
@article_stage_production_required
def production_astign_article(request, user_id, article_id):
    """
    Allows an editor to astign a production manager to an article.
    :param request: HttpRequest object
    :param user_id: Account object PK
    :param article_id: Article object PK
    :return: HttpRedirect
    """
    article = submission_models.Article.objects.get(
        id=article_id,
        journal=request.journal,
    )
    user = core_models.Account.objects.get(id=user_id)

    if user.is_production(request):
        url = request.journal.site_url(
            path=reverse(
                'production_article',
                kwargs={'article_id': article.id},
            )
        )
        html = logic.get_production_astign_content(user, request, article, url)

        prod = models.Productionastignment(
            article=article,
            production_manager=user,
            editor=request.user,
        )
        prod.save()

        cron_task.CronTask.add_email_task(
            user.email,
            'Production astignment',
            html,
            request,
            article,
        )
    else:
        messages.add_message(
            request,
            messages.WARNING,
            'User is not a production manager.',
        )

    return redirect(reverse('production_list'))

0 View Complete Implementation : views.py
Copyright GNU Affero General Public License v3.0
Author : BirkbeckCTP
@editor_user_required
def non_workflow_astign_article(request, article_id):
    """
    Allows users to astign themselves as production manager outside the
    standard workflow process.
    :param request: HttpRequest object
    :param article_id: Article object PK
    :return: HttpResponse or HttpRedirect
    """
    article = get_object_or_404(
        submission_models.Article,
        pk=article_id,
        journal=request.journal,
    )

    if article.production_astignment_or_none():
        messages.add_message(
            request,
            messages.WARNING,
            'This article already has a production astignment.',
        )

        return redirect(
            reverse(
                'production_article',
                kwargs={'article_id': article.pk},
            )
        )

    if request.POST and 'astign' in request.POST:
        models.Productionastignment.objects.create(
            article=article,
            editor=request.user,
            production_manager=request.user,
            astigned=timezone.now(),
            notified=True,
        )

        messages.add_message(
            request,
            messages.SUCCESS,
            'Production astignment created.',
        )

        return redirect(
            reverse(
                'production_article',
                kwargs={'article_id': article.pk},
            )
        )

    template = 'production/non_workflow_astign.html'
    context = {
        'article': article,
    }

    return render(request, template, context)