Python django.http.HttpResponseRedirect() Examples

The following are 30 code examples of django.http.HttpResponseRedirect(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.http , or try the search function .
Example #1
Source File: evidence.py    From open-synthesis with GNU General Public License v3.0 8 votes vote down vote up
def toggle_source_tag(request, evidence_id, source_id):
    """Toggle source tag for the given source and redirect to the evidence detail page for the associated evidence."""
    # May want to put in a sanity check here that source_id actually corresponds to evidence_id
    # Inefficient to have to do the DB lookup before making a modification. May want to have the client pass in
    # whether or not they're adding/removing the tag
    if request.method == 'POST':
        with transaction.atomic():
            source = get_object_or_404(EvidenceSource, pk=source_id)
            tag = EvidenceSourceTag.objects.get(tag_name=request.POST['tag'])
            user_tag = AnalystSourceTag.objects.filter(source=source, tagger=request.user, tag=tag)
            if user_tag.count() > 0:
                user_tag.delete()
                messages.success(request, _('Removed "{name}" tag from source.').format(name=tag.tag_name))
            else:
                AnalystSourceTag.objects.create(source=source, tagger=request.user, tag=tag)
                messages.success(request, _('Added "{name}" tag to source.').format(name=tag.tag_name))
            return HttpResponseRedirect(reverse('openach:evidence_detail', args=(evidence_id,)))
    else:
        # Redirect to the form where the user can toggle a source tag
        return HttpResponseRedirect(reverse('openach:evidence_detail', args=(evidence_id,))) 
Example #2
Source File: auth.py    From hummer with Apache License 2.0 7 votes vote down vote up
def login_required(login_url=None):
    """
    Decorator for views that checks that the user is authenticated, redirecting
    to login_url page if necessary.
    """
    def decorator(view_func):
        @wraps(view_func)
        def _wrapped_view(request, *args, **kwargs):
            is_login, username, is_staff = is_authenticated(request)
            if is_login:
                kwargs['username'] = username
                kwargs['is_staff'] = is_staff
                return view_func(request, *args, **kwargs)

            resolved_login_url = (login_url or settings.LOGIN_URL)
            return HttpResponseRedirect(resolved_login_url)
        return _wrapped_view
    return decorator 
Example #3
Source File: public.py    From donation-tracker with Apache License 2.0 6 votes vote down vote up
def runindex(request, event=None):
    event = viewutil.get_event(event)

    if not event.id:
        return HttpResponseRedirect(
            reverse('tracker:runindex', args=(Event.objects.latest().short,))
        )

    searchParams = {}
    searchParams['event'] = event.id

    runs = filters.run_model_query('run', searchParams)
    runs = runs.annotate(hasbids=Sum('bids'))

    return views_common.tracker_response(
        request, 'tracker/runindex.html', {'runs': runs, 'event': event},
    ) 
Example #4
Source File: views.py    From coursys with GNU General Public License v3.0 6 votes vote down vote up
def delete_ra(request, ra_slug):
    appointment = get_object_or_404(RAAppointment, slug=ra_slug, unit__in=request.units)
    if request.method == 'POST':
        appointment.deleted = True
        appointment.save()
        messages.success(request, "Deleted RA appointment." )
        l = LogEntry(userid=request.user.username,
              description="Deleted RA appointment %s." % (str(appointment),),
              related_object=appointment)
        l.save()              
    
    return HttpResponseRedirect(reverse('ra:student_appointments', kwargs={'userid': appointment.person.emplid}))




# Methods relating to Account creation. These are all straight forward. 
Example #5
Source File: views.py    From coursys with GNU General Public License v3.0 6 votes vote down vote up
def reject(request, course_slug, group_slug):
    course = get_object_or_404(CourseOffering, slug=course_slug)
    group = get_object_or_404(Group, courseoffering = course, slug = group_slug)
    person = get_object_or_404(Person, userid = request.user.username)
    member = get_object_or_404(Member, person = person, offering=course)

    if request.method != "POST":
        return HttpResponseForbidden()

    # delete membership on reject
    GroupMember.objects.filter(group = group, student = member).delete()

    #LOG EVENT#
    l = LogEntry(userid=request.user.username,
    description="rejected membership in group %s." % (group.name,),
    related_object=group )
    l.save()
    messages.add_message(request, messages.SUCCESS, 'You have left the group "%s".' % (group.name))
    return HttpResponseRedirect(reverse('offering:groups:groupmanage', kwargs={'course_slug': course_slug})) 
Example #6
Source File: views.py    From coursys with GNU General Public License v3.0 6 votes vote down vote up
def semester_config(request, semester_name=None):
    if semester_name:
        semester = get_object_or_404(Semester, name=semester_name)
    else:
        semester = Semester.next_starting()

    unit_choices = [(u.id, u.name) for u in request.units]
    if request.method == 'POST':
        form = SemesterConfigForm(request.POST)
        form.fields['unit'].choices = unit_choices
        if form.is_valid():
            config = SemesterConfig.get_config(units=[form.cleaned_data['unit']], semester=semester)
            config.set_start_date(form.cleaned_data['start_date'])
            config.set_end_date(form.cleaned_data['end_date'])
            config.save()
            messages.success(request, 'Updated semester configuration for %s.' % (semester.name))
            return HttpResponseRedirect(reverse('ra:search'))
    else:
        config = SemesterConfig.get_config(units=request.units, semester=semester)
        form = SemesterConfigForm(initial={'start_date': config.start_date(), 'end_date': config.end_date()})
        form.fields['unit'].choices = unit_choices

    return render(request, 'ra/semester_config.html', {'semester': semester, 'form': form}) 
Example #7
Source File: views.py    From coursys with GNU General Public License v3.0 6 votes vote down vote up
def new_attachment(request, ra_slug):
    appointment = get_object_or_404(RAAppointment, slug=ra_slug, unit__in=request.units)
    editor = get_object_or_404(Person, userid=request.user.username)

    form = RAAppointmentAttachmentForm()
    context = {"appointment": appointment,
               "attachment_form": form}

    if request.method == "POST":
        form = RAAppointmentAttachmentForm(request.POST, request.FILES)
        if form.is_valid():
            attachment = form.save(commit=False)
            attachment.appointment = appointment
            attachment.created_by = editor
            upfile = request.FILES['contents']
            filetype = upfile.content_type
            if upfile.charset:
                filetype += "; charset=" + upfile.charset
            attachment.mediatype = filetype
            attachment.save()
            return HttpResponseRedirect(reverse('ra:view', kwargs={'ra_slug': appointment.slug}))
        else:
            context.update({"attachment_form": form})

    return render(request, 'ra/appointment_attachment_form.html', context) 
Example #8
Source File: views.py    From coursys with GNU General Public License v3.0 6 votes vote down vote up
def select_letter(request, ra_slug, print_only=None):
    appointment = get_object_or_404(RAAppointment, slug=ra_slug, deleted=False, unit__in=request.units)
    # Forcing sorting of the letter choices so the Standard template is first.
    letter_choices = sorted(RAAppointment.letter_choices(request.units))
    if request.method == 'POST':
        filled_form = LetterSelectForm(data=request.POST, choices=letter_choices)
        if filled_form.is_valid():
            appointment.build_letter_text(filled_form.cleaned_data['letter_choice'])
        if print_only == 'print':
            return HttpResponseRedirect(reverse('ra:letter', kwargs=({'ra_slug': ra_slug})))
        else:
            return HttpResponseRedirect(reverse('ra:edit_letter', kwargs=({'ra_slug': ra_slug})))

    else:
        new_form = LetterSelectForm(choices=letter_choices)
        context = {'form': new_form, 'ra_slug': ra_slug, 'print_only': print_only}
        return render(request, 'ra/select_letter.html', context)


#View RA Appointment 
Example #9
Source File: views.py    From coursys with GNU General Public License v3.0 6 votes vote down vote up
def new_program(request):
    if request.method == 'POST':
        form = ProgramForm(request.POST)
        if form.is_valid():
            program = form.save()
            messages.add_message(request,
                                 messages.SUCCESS,
                                 'Program was created')
            l = LogEntry(userid=request.user.username,
                         description="Added program %s" % program,
                         related_object=program)
            l.save()
            return HttpResponseRedirect(reverse('ra:programs_index'))
    else:
        form = ProgramForm()
        form.fields['unit'].choices = [(u.id, u.name) for u in request.units]
    return render(request, 'ra/new_program.html', {'form': form}) 
Example #10
Source File: views.py    From figures with MIT License 6 votes vote down vote up
def figures_home(request):
    '''Renders the JavaScript SPA dashboard


    TODO: Should we make this a view class?

    '''
    # We probably want to roll this into a decorator
    if not figures.permissions.is_site_admin_user(request):
        return HttpResponseRedirect('/')

    # Placeholder context vars just to illustrate returning API hosts to the
    # client. This one uses a protocol relative url
    context = {
        'figures_api_url': '//api.example.com',
    }
    return render(request, 'figures/index.html', context)


#
# Mixins for API views
# 
Example #11
Source File: views.py    From coursys with GNU General Public License v3.0 6 votes vote down vote up
def edit_program(request, program_slug):
    program = get_object_or_404(Program, slug=program_slug, unit__in=request.units)
    if request.method == 'POST':
        form = ProgramForm(request.POST, instance=program)
        if form.is_valid():
            program = form.save()
            messages.add_message(request,
                                 messages.SUCCESS,
                                 'Program was created')
            l = LogEntry(userid=request.user.username,
                         description="Added program %s" % program,
                         related_object=program)
            l.save()
            return HttpResponseRedirect(reverse('ra:programs_index'))
    else:
        form = ProgramForm(instance=program)
        form.fields['unit'].choices = [(u.id, u.name) for u in request.units]
    return render(request, 'ra/edit_program.html', {'form': form, 'program': program}) 
Example #12
Source File: views.py    From coursys with GNU General Public License v3.0 6 votes vote down vote up
def join(request, course_slug, group_slug):
    course = get_object_or_404(CourseOffering, slug=course_slug)
    group = get_object_or_404(Group, courseoffering = course, slug = group_slug)
    person = get_object_or_404(Person, userid = request.user.username)
    member = get_object_or_404(Member, person = person, offering=course)
    
    if request.method != "POST":
        return HttpResponseForbidden()

    for groupMember in GroupMember.objects.filter(group = group, student = member):
        groupMember.confirmed = True
        groupMember.save()

    #LOG EVENT#
    l = LogEntry(userid=request.user.username,
    description="joined group %s." % (group.name,),
    related_object=group )
    l.save()
    messages.add_message(request, messages.SUCCESS, 'You have joined the group "%s".' % (group.name))
    return HttpResponseRedirect(reverse('offering:groups:groupmanage', kwargs={'course_slug': course_slug})) 
Example #13
Source File: views.py    From coursys with GNU General Public License v3.0 6 votes vote down vote up
def edit_letter(request, ra_slug):
    appointment = get_object_or_404(RAAppointment, slug=ra_slug, deleted=False, unit__in=request.units)

    if request.method == 'POST':
        form = RALetterForm(request.POST, instance=appointment)
        if form.is_valid():
            form.save()
            messages.success(request, 'Updated RA Letter Text for ' + appointment.person.first_name + " " + appointment.person.last_name)
            return HttpResponseRedirect(reverse('ra:student_appointments', kwargs=({'userid': appointment.person.userid})))
    else:
        if not appointment.offer_letter_text:
            letter_choices = RAAppointment.letter_choices(request.units)
            if len(letter_choices) == 1: # why make them select from one?
                appointment.build_letter_text(letter_choices[0][0])
            else:
                return HttpResponseRedirect(reverse('ra:select_letter', kwargs=({'ra_slug': ra_slug})))
        form = RALetterForm(instance=appointment)
    
    context = {'appointment': appointment, 'form': form}
    return render(request, 'ra/edit_letter.html', context)

# If we don't have an appointment letter yet, pick one. 
Example #14
Source File: views.py    From coursys with GNU General Public License v3.0 6 votes vote down vote up
def search(request, student_id=None):
    if student_id:
        student = get_object_or_404(Person, id=student_id)
    else:
        student = None
    if request.method == 'POST':
        form = RASearchForm(request.POST)
        if not form.is_valid():
            return HttpResponseRedirect(reverse('ra:found') + "?search=" + urllib.parse.quote_plus(form.data['search']))
        search = form.cleaned_data['search']
        # deal with people without active computing accounts
        if search.userid:
            userid = search.userid
        else:
            userid = search.emplid
        return HttpResponseRedirect(reverse('ra:student_appointments', kwargs={'userid': userid}))
    if student_id:
        form = RASearchForm(instance=student, initial={'student': student.userid})
    else:
        form = RASearchForm()
    context = {'form': form}
    return render(request, 'ra/search.html', context) 
Example #15
Source File: admin.py    From django-usersettings2 with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def changelist_view(self, request, extra_context=None):
        sites_count = Site.objects.count()
        if sites_count == 1:
            site = Site.objects.get()
            try:
                obj = self.model.objects.get(site=site)
                change_url = reverse(
                    'admin:%s_%s_change' % self.get_model_info(), args=(obj.pk,),
                    current_app=self.admin_site.name)
                return HttpResponseRedirect(change_url)
            except self.model.DoesNotExist:
                add_url = '%s?site_id=%s' % (
                    reverse('admin:%s_%s_add' % self.get_model_info(),
                            current_app=self.admin_site.name), site.pk)
                return HttpResponseRedirect(add_url)

        else:
            return super(SettingsAdmin, self).changelist_view(request, extra_context) 
Example #16
Source File: admin.py    From django-usersettings2 with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def add_view(self, request, form_url='', extra_context=None):
        site_id = request.GET.get('site_id', None)

        if not site_id:
            return self.select_site_view(request)
        else:
            try:
                site_id = self.model._meta.pk.to_python(site_id)
                site = Site.objects.get(pk=site_id)
            except (Site.DoesNotExist, ValidationError, ValueError):
                return self.select_site_view(request)
            else:
                try:
                    obj = self.model.objects.get(site=site)
                    change_url = reverse(
                        'admin:%s_%s_change' % self.get_model_info(), args=(obj.pk,),
                        current_app=self.admin_site.name)
                    msg = _('{0} for "{1}" already exists. You may edit it below.')\
                        .format(self.opts.verbose_name, site.domain)
                    self.message_user(request, msg)
                    return HttpResponseRedirect(change_url)
                except self.model.DoesNotExist:
                    pass
        return super(SettingsAdmin, self).add_view(request, form_url, extra_context) 
Example #17
Source File: views.py    From MPContribs with MIT License 6 votes vote down vote up
def manual_qmc_record_submission(request):
    if request.method == "POST":
        mat_form = MaterialSubmissionForm(request.POST)

        if mat_form.is_valid():
            mat_form.save()
            return HttpResponseRedirect("/thanks/")
    else:
        mat_form = MaterialSubmissionForm()

    return render(request, "materialsubmissionform.html", {"form": mat_form}) 
Example #18
Source File: public.py    From donation-tracker with Apache License 2.0 6 votes vote down vote up
def prizeindex(request, event=None):
    event = viewutil.get_event(event)

    if not event.id:
        return HttpResponseRedirect(
            reverse('tracker:prizeindex', args=(Event.objects.latest().short,))
        )

    searchParams = {}
    searchParams['event'] = event.id

    prizes = filters.run_model_query('prize', searchParams)
    prizes = prizes.select_related('startrun', 'endrun', 'category').prefetch_related(
        'prizewinner_set'
    )
    return views_common.tracker_response(
        request, 'tracker/prizeindex.html', {'prizes': prizes, 'event': event},
    ) 
Example #19
Source File: rps_list.py    From wanggeService with MIT License 6 votes vote down vote up
def get_name(request):
    # 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 = RPSForm(request.POST)
        # check whether it's valid:
        if form.is_valid():
            # process the data in form.cleaned_data as required
            # ...
            # redirect to a new URL:
            return HttpResponseRedirect('/thanks/')

    # if a GET (or any other method) we'll create a blank form
    else:
        form = RPSForm()

    return render(request, 'name.html', {'form': form}) 
Example #20
Source File: proxyview.py    From wanggeService with MIT License 6 votes vote down vote up
def get_proxy_name(request, pk):
    # 如果form通过POST方法发送数据
    if request.method == 'POST':
        # 接受request.POST参数构造form类的实例
        a = Proxy.objects.get(pk=1)
        form = ProxylistModelForm(request.POST, instance=a)
        # 验证数据是否合法
        if form.is_valid():
            # 处理form.cleaned_data中的数据
            # form.save()
            # 重定向到一个新的URL
            return HttpResponseRedirect('/thanks/')

    # 如果是通过GET方法请求数据,返回一个空的表单
    else:
        form = ProxylistModelForm()

    return render(request, 'stocks/proxyform.html', {'form': form}) 
Example #21
Source File: bid.py    From donation-tracker with Apache License 2.0 6 votes vote down vote up
def merge_bids_view(request, *args, **kwargs):
        if request.method == 'POST':
            objects = [int(x) for x in request.POST['objects'].split(',')]
            form = forms.MergeObjectsForm(
                model=models.Bid, objects=objects, data=request.POST
            )
            if form.is_valid():
                viewutil.merge_bids(
                    form.cleaned_data['root'], form.cleaned_data['objects']
                )
                logutil.change(
                    request,
                    form.cleaned_data['root'],
                    'Merged bid {0} with {1}'.format(
                        form.cleaned_data['root'],
                        ','.join([str(d) for d in form.cleaned_data['objects']]),
                    ),
                )
                return HttpResponseRedirect(reverse('admin:tracker_bid_changelist'))
        else:
            objects = [int(x) for x in request.GET['objects'].split(',')]
            form = forms.MergeObjectsForm(model=models.Bid, objects=objects)
        return render(request, 'admin/merge_bids.html', {'form': form}) 
Example #22
Source File: donation.py    From donation-tracker with Apache License 2.0 6 votes vote down vote up
def merge_donors_view(request):
        if request.method == 'POST':
            objects = [int(x) for x in request.POST['objects'].split(',')]
            form = forms.MergeObjectsForm(
                model=models.Donor, objects=objects, data=request.POST
            )
            if form.is_valid():
                viewutil.merge_donors(
                    form.cleaned_data['root'], form.cleaned_data['objects']
                )
                logutil.change(
                    request,
                    form.cleaned_data['root'],
                    'Merged donor {0} with {1}'.format(
                        form.cleaned_data['root'],
                        ','.join([str(d) for d in form.cleaned_data['objects']]),
                    ),
                )
                return HttpResponseRedirect(reverse('admin:tracker_donor_changelist'))
        else:
            objects = [int(x) for x in request.GET['objects'].split(',')]
            form = forms.MergeObjectsForm(model=models.Donor, objects=objects)
        return render(request, 'admin/merge_donors.html', {'form': form}) 
Example #23
Source File: teams.py    From open-synthesis with GNU General Public License v3.0 6 votes vote down vote up
def join_team(request, team_id):
    team = get_object_or_404(Team, pk=team_id)

    if team.members.filter(id=request.user.id).exists():
        raise SuspiciousOperation(_('User is already a member of the team'))
    elif TeamRequest.objects.filter(invitee=request.user, inviter__isnull=False, team=team).exists() or not team.invitation_required:
        team.members.add(request.user)
        team.save()
        TeamRequest.objects.filter(invitee=request.user, team=team).delete()
        messages.success(request, _('Joined team {name}').format(name=team.name))
        return HttpResponseRedirect(reverse('openach:view_team', args=(team.id,)))
    elif TeamRequest.objects.filter(invitee=request.user, team=team).exists():
        return HttpResponseBadRequest(_('User already has a membership request with the team'))
    else:
        TeamRequest.objects.create(invitee=request.user, team=team)
        if team.owner:
            notify.send(request.user, recipient=team.owner, actor=request.user, verb='request_membership', target=team)
        messages.success(request, _('Requested invitation to team {name}').format(name=team.name))
        return HttpResponseRedirect(reverse('openach:view_team', args=(team.id,))) 
Example #24
Source File: teams.py    From open-synthesis with GNU General Public License v3.0 6 votes vote down vote up
def revoke_membership(request, team_id, member_id):
    team = get_object_or_404(Team, pk=team_id)
    user = get_object_or_404(User, pk=member_id)

    if team.owner_id is None or team.owner_id != request.user.id:
        raise SuspiciousOperation(_('User is not the owner of the team'))
    elif user == team.owner:
        raise SuspiciousOperation(_('Cannot remove the owner from the team'))
    elif not team.invitation_required:
        raise SuspiciousOperation(_('Cannot remove user from teams that don\'t require an invitation'))

    team.members.remove(user)
    team.save()
    notify.send(request.user, recipient=user, actor=request.user, verb='remove', action_object=team, target=user)
    messages.success(request, _('Removed {name} from team').format(name=user.username))
    return HttpResponseRedirect(reverse('openach:view_team', args=(team.id,))) 
Example #25
Source File: teams.py    From open-synthesis with GNU General Public License v3.0 6 votes vote down vote up
def decide_invitation(request, invite_id):
    invite = get_object_or_404(TeamRequest, pk=invite_id)
    team = invite.team

    if team.owner_id is None or team.owner_id != request.user.id:
        raise SuspiciousOperation(_('User is not the owner of the team'))
    elif 'accept' in request.POST:
        invite.team.members.add(invite.invitee)
        invite.team.save()
        notify.send(request.user, recipient=invite.invitee, actor=request.user, verb='accept', action_object=team, target=invite.invitee)
        messages.success(request, _('Added {name} to the team').format(name=invite.invitee.username))
    elif 'reject' in request.POST:
        notify.send(request.user, recipient=invite.invitee, actor=request.user, verb='reject', action_object=team, target=invite.invitee)
        messages.success(request, _('Ignored {name}\'s team membership request').format(name=invite.invitee.username))
    else:
        return HttpResponseBadRequest(_('POST request must include either "{accept}" or "{reject}"').format(accept='accept', reject='reject'))

    invite.delete()
    return HttpResponseRedirect(reverse('openach:view_team', args=(team.id,))) 
Example #26
Source File: teams.py    From open-synthesis with GNU General Public License v3.0 6 votes vote down vote up
def invite_members(request, team_id):
    """Return a team edit view, or handle the form submission."""
    team = get_object_or_404(Team, pk=team_id)

    if team.owner_id is None or team.owner_id != request.user.id:
        raise SuspiciousOperation(_('User is not the owner of the team'))

    if request.method == 'POST':
        form = TeamInviteForm(request.POST, team=team)
        if form.is_valid():
            to_invite = form.cleaned_data['members']
            invites = [TeamRequest(team=team, inviter=request.user, invitee=x) for x in to_invite]
            TeamRequest.objects.bulk_create(invites)
            for user in to_invite:
                notify.send(request.user, recipient=user, actor=request.user, verb='invite', action_object=team, target=user)
            messages.success(request, _('Invited {count} members to the team').format(count=len(to_invite)))
            return HttpResponseRedirect(reverse('openach:view_team', args=(team.id,)))
    else:
        form = TeamInviteForm(team=team)
    return render(request, 'teams/invite.html', context={
        'team': team,
        'form': form
    }) 
Example #27
Source File: teams.py    From open-synthesis with GNU General Public License v3.0 6 votes vote down vote up
def edit_team(request, team_id):
    """Return a team edit view, or handle the form submission."""
    # TODO: if user turns off invitation-required, let everyone in who had outstanding membership requests

    team = get_object_or_404(Team, pk=team_id)

    if team.owner_id is None or team.owner_id != request.user.id:
        raise SuspiciousOperation(_('User is not the owner of the team'))

    if request.method == 'POST':
        form = TeamCreateForm(request.POST, instance=team)
        if form.is_valid():
            form.save()
            messages.success(request, _('Updated team information'))
            return HttpResponseRedirect(reverse('openach:view_team', args=(team.id,)))
    else:
        form = TeamCreateForm(instance=team)
    return render(request, 'teams/edit_team.html', context={
        'team': team,
        'form': form
    }) 
Example #28
Source File: boards.py    From open-synthesis with GNU General Public License v3.0 6 votes vote down vote up
def edit_permissions(request, board_id):
    """View board permissions form and handle form submission."""
    board = get_object_or_404(Board, pk=board_id)

    if 'edit_board' not in board.permissions.for_user(request.user):
        raise PermissionDenied()

    if request.method == 'POST':
        form = BoardPermissionForm(request.POST, instance=board.permissions, user=request.user)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse('openach:detail', args=(board.id,)))
    else:
        form = BoardPermissionForm(instance=board.permissions, user=request.user)

    context = {
        'board': board,
        'form': form,
    }
    return render(request, 'boards/edit_permissions.html', context) 
Example #29
Source File: evidence.py    From open-synthesis with GNU General Public License v3.0 6 votes vote down vote up
def add_source(request, evidence_id):
    """Return a view for adding a corroborating/contradicting source, or handle form submission."""
    evidence = get_object_or_404(Evidence, pk=evidence_id)
    if request.method == 'POST':
        form = EvidenceSourceForm(request.POST)
        if form.is_valid():
            source = form.save(commit=False)
            source.evidence = evidence
            source.uploader = request.user
            source.save()
            fetch_source_metadata.delay(source.id)
            return HttpResponseRedirect(reverse('openach:evidence_detail', args=(evidence_id,)))
        else:
            corroborating = form.data['corroborating'] == 'True'
    else:
        corroborating = request.GET.get('kind') is None or request.GET.get('kind') != 'conflicting'
        form = EvidenceSourceForm(initial={'corroborating': corroborating})

    context = {
        'form': form,
        'evidence': evidence,
        'corroborating': corroborating
    }

    return render(request, 'boards/add_source.html', context) 
Example #30
Source File: views.py    From coursys with GNU General Public License v3.0 5 votes vote down vote up
def new(request, course_slug):
    course = get_object_or_404(CourseOffering, slug=course_slug)
    student_choices = [
            (m.person.userid,
               "%s (%s, %s)" % (m.person.sortname(), m.person.emplid, m.person.userid))
            for m in
            Member.objects.filter(offering=course, role="STUD").select_related('person')]
    group_choices = [('', '\u2014')] + [(g.id, g.name) for g in DisciplineGroup.objects.filter(offering=course)]

    if request.method == 'POST':
        form = DisciplineCaseForm(offering=course, data=request.POST)
        form.fields['student'].choices = student_choices
        form.fields['group'].choices = group_choices
        if form.is_valid():
            instructor = Person.objects.get(userid=request.user.username)
            case = form.save(commit=False)
            case.owner = instructor
            case.offering = course
            case.save()
            form.save_m2m()
            #LOG EVENT#
            l = LogEntry(userid=request.user.username,
                  description=("created a discipline case for %s in %s") % (case.student.name(), course),
                  related_object=case)
            l.save()
            return HttpResponseRedirect(reverse('offering:discipline:show', kwargs={'course_slug': course_slug, 'case_slug': case.slug}))

    else:
        form = DisciplineCaseForm(offering=course)

    form.fields['student'].choices = student_choices
    form.fields['group'].choices = group_choices
    context = {'course': course, 'form': form}
    return render(request, "discipline/new.html", context)