Python django.shortcuts.get_object_or_404() Examples

The following are code examples for showing how to use django.shortcuts.get_object_or_404(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: athena-backend   Author: ippolab   File: views.py    MIT License 9 votes vote down vote up
def document_view(model):
    @api_view(["GET"])
    def view(request: Request, pk, document: str):
        if request.user.is_only_student:
            report = get_object_or_404(model, pk=pk, student=request.user)
        else:
            report = get_object_or_404(model, pk=pk)
        if document == "file":
            document = report.file
        elif document == "attachment":
            document = report.attachment
        else:
            raise Http404()
        if document:
            return FileResponse(open(document.path, "rb"))
        raise Http404()

    return view 
Example 2
Project: noke-platform   Author: NokeCodes   File: views.py    MIT License 8 votes vote down vote up
def join(request, slug):
    """Toggles whether user has an active membership in the project while maintaining the membership type."""
    if request.method == 'POST' and request.user.is_authenticated() and request.user.is_active:
        project = get_object_or_404(Project, slug=slug)
        action = request.POST.get('action')
        if action == 'unjoin':
            try:
                membership = Membership.objects.get(user=request.user, project=project)
                membership.is_active = False
                membership.save()
            except Membership.DoesNotExist:
                pass
        elif action == 'join':
            membership, _ = Membership.objects.update_or_create(user=request.user, project=project,
                                                                defaults={'is_active': True})

    return HttpResponseRedirect(reverse('projects:details', args=(slug,))) 
Example 3
Project: aurora   Author: carnby   File: views.py    MIT License 7 votes vote down vote up
def follow(request):
    #print 'follow'
    #print request.POST
    auth_user = request.user

    source_user = request.POST.get('source', '')
    if not source_user or auth_user.username != source_user:
        print(auth_user.username, len(auth_user.username), source_user, len(source_user))
        raise PermissionDenied

    portrait = get_object_or_404(Portrait, auth_screen_name=auth_user.username.lower())

    target_user_id = request.POST.get('target', '')[:100]
    if not target_user_id:
        raise Http404

    try:
        followed = portrait_follow(portrait, target_user_id)
    except:
        followed = False

    return render_json(request, followed) 
Example 4
Project: django-ajax-contacts   Author: cuducos   File: views.py    The Unlicense 6 votes vote down vote up
def contact_detail(request, pk):
    if request.method == 'POST':
        data = (request.POST.get(key) for key in ('name', 'fone', 'email'))
        contact = Contact.objects.get(pk=pk)
        contact.name, contact.fone, contact.email = data
        contact.save()
    else:
        contact = get_object_or_404(Contact, pk=pk)

    response = dict(
        name=contact.name,
        avatar=contact.avatar(),
        email=contact.email,
        phone=contact.fone,
        url=resolve_url('contact-details', pk=contact.pk)
    )
    return JsonResponse(response) 
Example 5
Project: aurora   Author: carnby   File: views.py    MIT License 6 votes vote down vote up
def share(request):
    auth_user = request.user

    source_user = request.POST.get('source', '')
    if not source_user or auth_user.username.lower() != source_user.lower():
        print(auth_user.username, len(auth_user.username), source_user, len(source_user))
        raise PermissionDenied

    portrait = get_object_or_404(Portrait, auth_screen_name=auth_user.username.lower())

    try:
        followed = portrait_share(portrait)
    except Exception as err:
        print(err)
        followed = False

    print('share result', followed)

    return render_json(request, followed) 
Example 6
Project: i-portalen   Author: I-sektionen   File: views.py    MIT License 6 votes vote down vote up
def question_details(request, qg_pk, q_pk):
    q = get_object_or_404(Question, pk=q_pk)
    if not q.can_vote(request.user):
        messages.warning(request, _("Du har redan röstat i den frågan."))
        return redirect(reverse("votings:question group", kwargs={'qg_pk': qg_pk}))
    form = VotingForm(q_pk, request.POST or None)
    if request.method == 'POST':
        if form.is_valid():
            votes = list(map(int, form.cleaned_data['options']))
            try:
                q.vote(request.user, votes)
                messages.success(request, _("Du har nu röstat, tack för din röst!"))
                return redirect(reverse("votings:question group", kwargs={'qg_pk': qg_pk}))
            except CouldNotVoteException as e:
                messages.error(request, e.reason)
    return render(request, "votings/question_details.html", {"form": form, "question": q}) 
Example 7
Project: i-portalen   Author: I-sektionen   File: views.py    MIT License 6 votes vote down vote up
def summarise_noshow(request,pk):
    event = get_object_or_404(Event,pk=pk)
    if not event.can_administer(request.user):
        raise PermissionDenied
    if not event.finished:
        event.finished = True
    noshows = event.no_show
    for user in noshows:
        noshow = EntryAsPreRegistered.objects.get(event=event, user=user)
        noshow.no_show = True
        noshow.save()
    for user in noshows:
        if len(EntryAsPreRegistered.objects.get_noshow(user=user)) == 2:
            subject = "Du har nu missat ditt andra event"
            body = "<p>Hej du har missat 2 event som du har anmält dig på. Om du missar en tredje gång så blir vi tvungna att stänga av dig från " \
                   "framtida event fram tills ett halv år framåt.</p>"
            send_mail(subject, "", settings.EMAIL_HOST_USER, [user.email, ], fail_silently=False, html_message=body)
        elif len(EntryAsPreRegistered.objects.get_noshow(user=user)) == 3:
            subject = "Du har nu missat ditt tredje event"
            body = "<p>Hej igen du har missat 3 event som du har anmält dig på. Du kommer härmed att blir avstängd från " \
                   "framtida event fram tills ett halv år framåt. Ha en bra dag :)</p>"
            send_mail(subject, "", settings.EMAIL_HOST_USER, [user.email, ], fail_silently=False, html_message=body)
    event.save()
    return redirect("events:administer event", pk=pk) 
Example 8
Project: i-portalen   Author: I-sektionen   File: views.py    MIT License 6 votes vote down vote up
def cancel(request, pk=None):
    event = get_object_or_404(Event, pk=pk)
    if event.can_administer(request.user):
        if request.method == 'POST':
            form = DeleteForm(request.POST)
            if form.is_valid():
                event.status = Event.BEING_CANCELD
                event.cancel_message = form.cleaned_data["cancel"]
                event.save()
                form_user = form.cleaned_data["cancel"]
                body = "<h1>Hej!</h1><br><br><p>Det finns nya event att ställa in på i-Portalen.<br><a href='https://www.i-portalen.se/article/unapproved/'>Klicka här!</a></p><br><br><p>Med vänliga hälsningar, <br><br>Admins @ webgroup" + form_user
                send_mail('Nytt event att ställa in', '', settings.EMAIL_HOST_USER, ['[email protected]'], fail_silently=False, html_message=body)
                messages.success(request, _("Dina ändringar har skickats för granskning."))
            #     vill låsa radera knapp
            else:
                messages.error(request, _("Det har ej fyllts i varför eventet önskas raderas."))
                return redirect("events:administer event", pk=pk)
        #         vill stanna kvar på sidan

        return render(request, 'events/administer_event.html', {'event': event, 'form':form, 'form_user':form_user, })
    raise PermissionDenied 
Example 9
Project: xadmin_bugfix   Author: vip68   File: xversion.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def init_request(self, object_id, version_id):
        self.detail = self.get_model_view(
            DetailAdminView, self.model, object_id)
        self.org_obj = self.detail.obj
        self.version = get_object_or_404(
            Version, pk=version_id, object_id=smart_text(self.org_obj.pk))

        self.prepare_form() 
Example 10
Project: xadmin_bugfix   Author: vip68   File: xversion.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def init_request(self, version_id):
        if not self.has_change_permission() and not self.has_add_permission():
            raise PermissionDenied

        self.version = get_object_or_404(Version, pk=version_id)
        self.org_obj = self.version._object_version.object

        self.prepare_form() 
Example 11
Project: django-xadmin   Author: MarkHoo   File: xversion.py    MIT License 5 votes vote down vote up
def init_request(self, object_id, version_id):
        self.detail = self.get_model_view(
            DetailAdminView, self.model, object_id)
        self.org_obj = self.detail.obj
        self.version = get_object_or_404(
            Version, pk=version_id, object_id=smart_text(self.org_obj.pk))

        self.prepare_form() 
Example 12
Project: django-xadmin   Author: MarkHoo   File: xversion.py    MIT License 5 votes vote down vote up
def init_request(self, version_id):
        if not self.has_change_permission() and not self.has_add_permission():
            raise PermissionDenied

        self.version = get_object_or_404(Version, pk=version_id)
        self.org_obj = self.version._object_version.object

        self.prepare_form() 
Example 13
Project: django-xadmin   Author: MarkHoo   File: xversion.py    MIT License 5 votes vote down vote up
def init_request(self, object_id, version_id):
        self.detail = self.get_model_view(
            DetailAdminView, self.model, object_id)
        self.org_obj = self.detail.obj
        self.version = get_object_or_404(
            Version, pk=version_id, object_id=smart_text(self.org_obj.pk))

        self.prepare_form() 
Example 14
Project: django-xadmin   Author: MarkHoo   File: xversion.py    MIT License 5 votes vote down vote up
def init_request(self, version_id):
        if not self.has_change_permission() and not self.has_add_permission():
            raise PermissionDenied

        self.version = get_object_or_404(Version, pk=version_id)
        self.org_obj = self.version._object_version.object

        self.prepare_form() 
Example 15
Project: django-xadmin   Author: MarkHoo   File: xversion.py    MIT License 5 votes vote down vote up
def init_request(self, object_id, version_id):
        self.detail = self.get_model_view(
            DetailAdminView, self.model, object_id)
        self.org_obj = self.detail.obj
        self.version = get_object_or_404(
            Version, pk=version_id, object_id=smart_text(self.org_obj.pk))

        self.prepare_form() 
Example 16
Project: django-project-template   Author: kagxin   File: generics.py    MIT License 5 votes vote down vote up
def get_object_or_404(queryset, *filter_args, **filter_kwargs):
    """
    Same as Django's standard shortcut, but make sure to also raise 404
    if the filter_kwargs don't match the required types.
    """
    try:
        return _get_object_or_404(queryset, *filter_args, **filter_kwargs)
    except (TypeError, ValueError, ValidationError):
        raise Http404 
Example 17
Project: noke-platform   Author: NokeCodes   File: views.py    MIT License 5 votes vote down vote up
def details(request, slug):
    project = get_object_or_404(Project, slug=slug)
    context = {
        'project': project,
    }
    if request.user.is_authenticated():
        try:
            membership = Membership.objects.get(user=request.user, project=project)
        except Membership.DoesNotExist:
            membership = None
        context['membership'] = membership
    return render(request, 'projects/details.html', context) 
Example 18
Project: pinax-documents   Author: pinax   File: views.py    MIT License 5 votes vote down vote up
def get(self, request, *args, **kwargs):
        if "p" in request.GET:
            qs = self.model.objects.for_user(request.user)
            self.parent = get_object_or_404(qs, pk=request.GET["p"])
        else:
            self.parent = None
        return super(FolderCreate, self).get(request, *args, **kwargs) 
Example 19
Project: pinax-documents   Author: pinax   File: views.py    MIT License 5 votes vote down vote up
def get(self, request, *args, **kwargs):
        if "f" in request.GET:
            qs = Folder.objects.for_user(request.user)
            self.folder = get_object_or_404(qs, pk=request.GET["f"])
        else:
            self.folder = None
        return super(DocumentCreate, self).get(request, *args, **kwargs) 
Example 20
Project: pythonjobs.ie   Author: kimeraapp   File: views.py    GNU General Public License v2.0 5 votes vote down vote up
def get_object(self, queryset=None):
        pk = self.kwargs.get(self.pk_url_kwarg, None)
        return get_object_or_404(Job, pk=pk, status=1) 
Example 21
Project: django-image-renderer   Author: rouk1   File: views.py    Do What The F*ck You Want To Public License 5 votes vote down vote up
def get_last_modified(request, image_id, target_width=0, target_height=0):
    im = get_object_or_404(MasterImage, pk=image_id)
    return im.last_modified 
Example 22
Project: django-image-renderer   Author: rouk1   File: views.py    Do What The F*ck You Want To Public License 5 votes vote down vote up
def get_rendition_url(request, image_id, target_width=0, target_height=0):
    '''
    get a rendition url

    if the rendition does nto exist it will be created in the storage
    if dimensions do not fit master's aspect ratio
    then image will be cropped with a centered anchor

    if one dimensions is omitted (0)
    the other one will be generated accordind to master's aspect ratio

    :param request: http GET request
        /renderer/rendition/url/<image_id>/<target_width>/<target_height>/
    :param image_id: the master image primary key
    :param target_width: target image width
        if 0 renderer will use target_height
        to generate a image with correct aspect ratio
    :param target_height: target image height
        if 0 renderer will use target_width
        to generate a image height correct aspect ratio
    :return: rendition url in a json dictionary
    '''
    im = get_object_or_404(MasterImage, pk=image_id)

    return JsonResponse({
        'url': im.get_rendition_url(target_width, target_height)
    }) 
Example 23
Project: django-image-renderer   Author: rouk1   File: views.py    Do What The F*ck You Want To Public License 5 votes vote down vote up
def get_master_url(request, image_id):
    '''
    get image's master url

    ...

    :param request: http GET request /renderer/master/url/<image_id>/
    :param image_id: the master image primary key
    :return: master url in a json dictionary
    '''
    im = get_object_or_404(MasterImage, pk=image_id)

    return JsonResponse({'url': im.get_master_url()}) 
Example 24
Project: kagi   Author: justinmayer   File: totp_devices.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def post(self, request):
        assert "delete" in self.request.POST
        device = get_object_or_404(
            self.get_queryset(), pk=self.request.POST["device_id"]
        )
        device.delete()
        messages.success(request, _("Device removed."))
        return HttpResponseRedirect(reverse("kagi:totp-devices")) 
Example 25
Project: kagi   Author: justinmayer   File: webauthn_keys.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def post(self, request):
        assert "delete" in self.request.POST
        key = get_object_or_404(self.get_queryset(), pk=self.request.POST["key_id"])
        key.delete()
        messages.success(request, _("Key removed."))
        return HttpResponseRedirect(reverse("kagi:webauthn-keys")) 
Example 26
Project: umklapp_site   Author: mohrm   File: views.py    MIT License 5 votes vote down vote up
def continue_story(request, story_id):
    s = get_object_or_404(Story.objects, id=story_id)

    if s.is_finished:
        return HttpResponseBadRequest("Story already finished")

    if not s.participates_in(request.user):
        raise PermissionDenied

    t = get_object_or_404(s.tellers, user=request.user)

    if s.whose_turn != t.position:
        return HttpResponseBadRequest("Not your turn")

    finish = 'finish' in request.POST
    form = ExtendStoryForm(request.POST)
    if form.is_valid():
        if 'finish' in form.data:
            if form.cleaned_data['nextSentence']:
                s.continue_story(form.cleaned_data['nextSentence'])
            s.finish()
            return redirect('show_story', story_id=s.id)
        else:
            s.continue_story(form.cleaned_data['nextSentence'])
            messages.success(request, u"Geschichte „%s“ weitergeführt" % s.title)
            return redirect('overview')
    else:
        context = {
            'story': s,
            'form': form
        }
        return render(request, 'umklapp/extend_story.html', context) 
Example 27
Project: umklapp_site   Author: mohrm   File: views.py    MIT License 5 votes vote down vote up
def skip_always(request, story_id):
    s = get_object_or_404(Story.objects, id=story_id)
    u = request.user

    if s.is_finished:
        return HttpResponseBadRequest("Story already finished")
    if not s.participates_in(u):
        raise PermissionDenied

    try:
        s.set_always_skip(u)
        messages.success(request, u"Du wirst nun automatisch übersprungen bei „%s“." % s.title)
    except NotEnoughActivePlayers as e:
        messages.success(request, u"Zuwenig aktive Spieler, als dass du überspringen kannst bei „%s“." % s.title)
    return redirect('overview') 
Example 28
Project: umklapp_site   Author: mohrm   File: views.py    MIT License 5 votes vote down vote up
def unskip_always(request, story_id):
    s = get_object_or_404(Story.objects, id=story_id)
    u = request.user

    if not s.participates_in(u):
        raise PermissionDenied
    if s.is_finished:
        return HttpResponseBadRequest("Story already finished")

    messages.success(request, u"Du schreibst wieder aktiv mit bei „%s“." % s.title)
    s.unset_always_skip(u)
    return redirect('overview') 
Example 29
Project: umklapp_site   Author: mohrm   File: views.py    MIT License 5 votes vote down vote up
def skip_story(request, story_id):
    s = get_object_or_404(Story.objects, id=story_id)
    if not request.user.is_staff and s.waiting_for() != request.user:
        raise PermissionDenied
    s.advance_teller()
    return redirect('overview')

# Nota bene: This view is available without logging in! 
Example 30
Project: umklapp_site   Author: mohrm   File: views.py    MIT License 5 votes vote down vote up
def show_story(request, story_id):
    s = get_object_or_404(Story.objects, id=story_id)

    if s.is_finished:
        if not s.participates_in(request.user) and not s.is_public:
            raise PermissionDenied

        anonym = not s.participates_in(request.user)

        if request.user.is_authenticated() and not request.user in s.read_by.all():
            s.read_by.add(request.user)

        context = {
            'story': s,
            'anonymized' : anonym,
            'has_upvoted' : s.has_upvoted(request.user),
            'upvote_count' : s.upvote_count(),
        }
        return render(request, 'umklapp/show_story.html', context)
    else:
        # unfinished business
        assert not s.is_finished

        if not s.participates_in(request.user):
            raise PermissionDenied

        form = None
        t = get_object_or_404(s.tellers, user=request.user)

        if s.whose_turn == t.position:
            # only show form if its the user's turn
            form = ExtendStoryForm()

        context = {
            'story': s,
            'form': form,
            'always_skip' : s.does_always_skip(request.user),
        }
        return render(request, 'umklapp/extend_story.html', context) 
Example 31
Project: umklapp_site   Author: mohrm   File: views.py    MIT License 5 votes vote down vote up
def downvote_story(request, story_id):
    s = get_object_or_404(Story.objects, id=story_id)

    if not s.is_finished:
        return HttpResponseBadRequest("Story not finished yet")

    s.downvote_story(request.user)

    return redirect('show_story', story_id=s.id) 
Example 32
Project: umklapp_site   Author: mohrm   File: views.py    MIT License 5 votes vote down vote up
def upvote_storypart(request, storypart_id):
    s = get_object_or_404(StoryPart.objects, id=storypart_id)

    if request.user == s.teller.user:
        messages.warning(request, u"Du kannst deine eigenen Beiträge nicht upvoten.")
        return redirect('show_story', story_id=s.teller.corresponding_story.id)

    s.upvote(request.user)

    return redirect('show_story', story_id=s.teller.corresponding_story.id) 
Example 33
Project: umklapp_site   Author: mohrm   File: views.py    MIT License 5 votes vote down vote up
def downvote_storypart(request, storypart_id):
    s = get_object_or_404(StoryPart.objects, id=storypart_id)

    s.downvote(request.user)

    return redirect('show_story', story_id=s.teller.corresponding_story.id) 
Example 34
Project: umklapp_site   Author: mohrm   File: views.py    MIT License 5 votes vote down vote up
def publish_story(request, story_id):
    s = get_object_or_404(Story.objects, id=story_id)

    if not s.is_finished:
        return HttpResponseBadRequest("Story not finished yet")
    if not s.started_by == request.user:
        raise PermissionDenied

    s.public(True)

    return redirect('show_story', story_id=s.id) 
Example 35
Project: umklapp_site   Author: mohrm   File: views.py    MIT License 5 votes vote down vote up
def unpublish_story(request, story_id):
    s = get_object_or_404(Story.objects, id=story_id)

    if not s.is_finished:
        return HttpResponseBadRequest("Story not finished yet")
    if not s.started_by == request.user:
        raise PermissionDenied

    s.public(False)

    return redirect('show_story', story_id=s.id) 
Example 36
Project: aurora   Author: carnby   File: views.py    MIT License 5 votes vote down vote up
def get_portrait(request, screen_name):
    portrait = get_object_or_404(Portrait, auth_screen_name=screen_name.lower(), active=True)

    if not portrait.public_access_enabled:
        if request.user.username.lower() != screen_name.lower():
            raise PermissionDenied()

    return render_json(request, portrait.portrait_content, dumped=True) 
Example 37
Project: aurora   Author: carnby   File: views.py    MIT License 5 votes vote down vote up
def get_recommendations(request, screen_name):
    if request.user.username.lower() == screen_name.lower():
        portrait = get_object_or_404(Portrait, auth_screen_name=screen_name.lower(), active=True)
        return render_json(request, portrait.portrait_recommendations, dumped=True)

    raise PermissionDenied()


# @login_required 
Example 38
Project: fleeg-platform   Author: Fleeg   File: views.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def links(request, username):
        session_account = None
        notify_count = None
        profile = get_object_or_404(User, username=username)
        profile_account = Account.get_by_user(user=profile)
        profile.user_avatar = profile_account.user_avatar
        if request.user.is_authenticated:
            session_account = Account.get_by_user(request.user)
            request.user.is_following = session_account.is_following(profile_account)
            notify_count = Notification.objects.filter(owner=session_account, viewed=False).count()
        posts = Post.links_by_user(username, session_account)
        return render(request, 'link/link.html', {'profile': profile, 'posts': posts, 'links': True,
                                                  'notify_count': notify_count}) 
Example 39
Project: fleeg-platform   Author: Fleeg   File: views.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def following(request, username):
        notify_count = None
        profile = get_object_or_404(User, username=username)
        accounts = Account.objects.filter(followers__owner__user__username=username)
        profile_account = Account.get_by_user(user=profile)
        profile.user_avatar = profile_account.user_avatar
        if request.user.is_authenticated:
            session_account = Account.get_by_user(request.user)
            request.user.is_following = session_account.is_following(profile_account)
            notify_count = Notification.objects.filter(owner=session_account, viewed=False).count()
        return render(request, 'account/user.html', {'profile': profile, 'accounts': accounts,
                                                     'following': True,
                                                     'notify_count': notify_count}) 
Example 40
Project: fleeg-platform   Author: Fleeg   File: views.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def followers(request, username):
        notify_count = None
        profile = get_object_or_404(User, username=username)
        accounts = Account.objects.filter(following__follow__user__username=username)
        profile_account = Account.get_by_user(user=profile)
        profile.user_avatar = profile_account.user_avatar
        if request.user.is_authenticated:
            session_account = Account.get_by_user(request.user)
            request.user.is_following = session_account.is_following(profile_account)
            notify_count = Notification.objects.filter(owner=session_account, viewed=False).count()
        return render(request, 'account/user.html', {'profile': profile, 'accounts': accounts,
                                                     'followers': True,
                                                     'notify_count': notify_count}) 
Example 41
Project: athena-backend   Author: ippolab   File: views.py    MIT License 5 votes vote down vote up
def set_password_admin_view(request, username):
    new_pass = request.data.get("new_password", None)
    if not new_pass:
        return HttpResponseBadRequest()
    user = get_object_or_404(User, username=username)
    user.set_password(new_pass)
    user.save()
    return HttpResponse(status=200) 
Example 42
Project: athena-backend   Author: ippolab   File: views.py    MIT License 5 votes vote down vote up
def report_from_task_view(request: Request, task_pk: uuid):
    if request.user.is_student:
        report = get_object_or_404(Report, task=task_pk, student__id=request.user.id)
    else:
        raise Http404()

    serializer = ReportSerializer(report, context={"request": request})
    return Response(data=serializer.data) 
Example 43
Project: i-portalen   Author: I-sektionen   File: views.py    MIT License 5 votes vote down vote up
def invoice(request, invoice_ids):
    try:
        invoice_ids = ast.literal_eval(invoice_ids)
    except (SyntaxError, TypeError, ValueError):
        raise Http404
    if type(invoice_ids) is not list:
        temp = invoice_ids
        invoice_ids = []
        invoice_ids.append(temp)

    invoice_list = []
    for invoice_id in invoice_ids:
        inv = get_object_or_404(Invoice, pk=invoice_id)
        booking = inv.booking

        #  Must be have permission or be correct user.
        if not (request.user.has_perm("bookings.manage_bookings") or booking.user == request.user):
            return HttpResponseForbidden

        bookable = booking.bookable
        fixed_costs = FixedCostAmount.objects.filter(invoice=inv)
        variable_costs = VariableCostAmount.objects.filter(invoice=inv)
        invoice_list.append({
            'invoice': inv,
            'booking': booking,
            'bookable': bookable,
            'fixed_costs': fixed_costs,
            'variable_costs': variable_costs})

    return render(request, 'bookings/invoice.html', {'invoice_list': invoice_list}) 
Example 44
Project: i-portalen   Author: I-sektionen   File: views.py    MIT License 5 votes vote down vote up
def remove_booking(request, booking_id):
    booking = get_object_or_404(Booking, pk=booking_id)
    if request.user.pk == booking.user.pk:
        booking.delete()
    return redirect("bookings:my bookings") 
Example 45
Project: i-portalen   Author: I-sektionen   File: views.py    MIT License 5 votes vote down vote up
def create_invoice(request, booking_pk):
    booking = get_object_or_404(Booking, pk=booking_pk)
    q = Invoice.objects.filter(booking=booking)
    if not q.exists():
        i = Invoice(status=Invoice.CREATED,
                    booking=booking,
                    )
        i.save()
    else:
        i = q[0]  # take the first one.
    return redirect(reverse("iportalenadmin:bookings_invoice_change", args=[i.pk])) 
Example 46
Project: i-portalen   Author: I-sektionen   File: views.py    MIT License 5 votes vote down vote up
def send_invoice_email(request, invoice_id):
    i = get_object_or_404(Invoice, pk=invoice_id)
    subject = "".join([_("Faktura för"), " {name}"]).format(name=i.booking.bookable, )
    msg = _("En ny faktura finns nu tillgänglig åt dig på i-portalen.se."
            " Du behöver logga in på ditt konto för att ta del av fakturan,"
            " klicka på bokningar upp till höger för att se dina fakturor.")
    frm = "[email protected]"  # Todo: Is this reasonable?
    to = i.booking.user.email
    send_mail(subject, msg, frm, [to])
    if i.status == Invoice.CREATED:
        i.status = Invoice.SENT
        i.save()
    messages.success(request, _("Ett email har skickats till användaren om fakturan, "
                                "denna faktura har markerats som skickad."))
    return redirect(reverse("iportalenadmin:bookings_invoice_change", args=[i.pk])) 
Example 47
Project: i-portalen   Author: I-sektionen   File: views.py    MIT License 5 votes vote down vote up
def single_article(request, pk):
    article = get_object_or_404(Alumni_Article, pk=pk)
    if article.can_administer(request.user):
        admin = True
    else:
        admin = False
    if article.show_article_before_experation or admin:
        # attachments = article.otherattachment_set
        # image_attachments = article.imageattachment_set
        return render(request, 'model/alumni_article.html', {
            'article': article,
            # 'attachments': attachments,
            # 'image_attachments': image_attachments,
            'can_administer': admin}) 
Example 48
Project: i-portalen   Author: I-sektionen   File: views.py    MIT License 5 votes vote down vote up
def speaker_list_user_remove_self(request, pk):
    event = get_object_or_404(Event, pk=pk)
    try:
        SpeakerList.objects.remove(event=event, user=request.user)
        messages.success(request, _("Du har strukit dig från talarlistan!"))
    except SpeakerListException as e:
        messages.error(request, str(e.reason))
    return redirect(reverse('events:user view', kwargs={'pk': event.pk})) 
Example 49
Project: i-portalen   Author: I-sektionen   File: views.py    MIT License 5 votes vote down vote up
def speaker_list_display(request, pk):
    event = get_object_or_404(Event, pk=pk)
    return render(request, 'speaker_list/display_speaker_list.html', {
        'speaker_list': SpeakerList.objects.show_queue(event=event), 'event': event
    }) 
Example 50
Project: i-portalen   Author: I-sektionen   File: views.py    MIT License 5 votes vote down vote up
def administer_speaker_list(request, pk):
    event = get_object_or_404(Event, pk=pk)
    return render(request, 'speaker_list/administer_speaker_list.html', {
        'event': event
    }) 
Example 51
Project: i-portalen   Author: I-sektionen   File: views.py    MIT License 5 votes vote down vote up
def question_group(request, qg_pk):
    qg = get_object_or_404(QuestionGroup, pk=qg_pk)
    return render(request, "votings/question_group.html", {"question_group": qg}) 
Example 52
Project: i-portalen   Author: I-sektionen   File: views.py    MIT License 5 votes vote down vote up
def create_from_event(request, event_pk):
    e = get_object_or_404(Event, pk=event_pk)
    if e.can_administer(request.user):
        qg = QuestionGroup.objects.create(name=e.headline,
                                          question_status=QuestionGroup.EVENT,
                                          event=e,
                                          creator=request.user)
        return redirect(reverse('iportalenadmin:votings_questiongroup_change', args=(qg.pk,)))
    else:
        raise PermissionDenied() 
Example 53
Project: i-portalen   Author: I-sektionen   File: views.py    MIT License 5 votes vote down vote up
def admin_from_event(request, event_pk):
    e = get_object_or_404(Event, pk=event_pk)
    if e.can_administer(request.user):
        qg = get_object_or_404(QuestionGroup, event_id=event_pk)
        return redirect(reverse('iportalenadmin:votings_questiongroup_change', args=(qg.pk,)))
    else:
        raise PermissionDenied() 
Example 54
Project: i-portalen   Author: I-sektionen   File: views.py    MIT License 5 votes vote down vote up
def get_from_event(request, event_pk):
    qg = get_object_or_404(QuestionGroup, event_id=event_pk)
    return redirect(reverse('votings:question group', args=(qg.pk,))) 
Example 55
Project: i-portalen   Author: I-sektionen   File: forms.py    MIT License 5 votes vote down vote up
def __init__(self, question_id, *args, **kwargs):
        self.question_id = question_id
        q = get_object_or_404(Question, pk=question_id)
        super(VotingForm, self).__init__(*args, **kwargs)

        if q.verification:
            self.fields['verification'].required = True
        self.fields['options'].choices = [(a.pk, a.name) for a in Option.objects.filter(question_id=question_id)] 
Example 56
Project: i-portalen   Author: I-sektionen   File: views.py    MIT License 5 votes vote down vote up
def organisation(request, organisation_name):
    org = get_object_or_404(Organisation, name=organisation_name)
    members = OrganisationPost.objects.filter(org=org)
    return render(request, "organisations/organisation.html", {
        'organisation': org,
        'members': members
    }) 
Example 57
Project: i-portalen   Author: I-sektionen   File: views.py    MIT License 5 votes vote down vote up
def single_travel_story(request, pk):
    travel_story = get_object_or_404(Travel_Story, pk=pk)
    return render(request, 'exchange_portal/travel_story.html', {'travel_story': travel_story})
    #Add all travel stories to show 
Example 58
Project: i-portalen   Author: I-sektionen   File: views.py    MIT License 5 votes vote down vote up
def single_article(request, pk):
    article = get_object_or_404(Article, pk=pk)
    if article.can_administer(request.user):
        admin = True
    else:
        admin = False
    if (article.status == Article.APPROVED and article.show_article_before_experation) or admin:
        attachments = article.otherattachment_set
        image_attachments = article.imageattachment_set
        return render(request, 'articles/article.html', {
            'article': article,
            'attachments': attachments,
            'image_attachments': image_attachments,
            'can_administer': admin})
    raise PermissionDenied 
Example 59
Project: i-portalen   Author: I-sektionen   File: views.py    MIT License 5 votes vote down vote up
def view_event(request, pk):
    event = get_object_or_404(Event, pk=pk)
    if (event.status == Event.APPROVED and event.show_event_before_experation) or event.can_administer(request.user):
        return render(request, "events/event.html", {"event": event})
    raise PermissionDenied 
Example 60
Project: i-portalen   Author: I-sektionen   File: views.py    MIT License 5 votes vote down vote up
def register_to_event(request, pk):
    if request.method == "POST":
        event = get_object_or_404(Event, pk=pk)
        try:
            event.register_user(request.user)
            messages.success(request, _("Du är nu registrerad på eventet."))
        except CouldNotRegisterException as err:
            messages.error(request,
                           _("Fel, kunde inte registrera dig på ") + err.event.headline + _(" för att ") + err.reason + ".")
    return redirect("events:event", pk=pk) 
Example 61
Project: i-portalen   Author: I-sektionen   File: views.py    MIT License 5 votes vote down vote up
def import_registrations(request, pk):
    event = get_object_or_404(Event, pk=pk)
    if not event.can_administer(request.user):
        raise PermissionDenied
    if request.method == 'POST':
        form = ImportEntriesForm(request.POST)
        if form.is_valid():
            list_of_liu_id = form.cleaned_data['users'].splitlines()
            for liu_id in list_of_liu_id:
                try:
                    event.register_user(IUser.objects.get(username=liu_id))
                except CouldNotRegisterException as err:
                    messages.error(
                        request,
                        "".join([_("Fel, kunde inte registrera"),
                                 " {liu_id} ",
                                 _("på"),
                                 " {hedline} ",
                                 _("för att"),
                                 " {reason}."]).format(
                            liu_id=liu_id,
                            hedline=err.event.headline,
                            reason=err.reason))
                except ObjectDoesNotExist:
                    messages.error(request, "".join(["{liu_id} ", _("finns inte i databasen.")]).format(liu_id))
    else:
        form = ImportEntriesForm()
    return render(request, "events/import_users.html", {'form': form}) 
Example 62
Project: i-portalen   Author: I-sektionen   File: views.py    MIT License 5 votes vote down vote up
def register_as_reserve(request, pk):
    if request.method == "POST":
        event = get_object_or_404(Event, pk=pk)
        entry = event.register_reserve(request.user)
        messages.success(request,
                         _("Du är nu anmäld som reserv på eventet, du har plats nr. ") + str(entry.position()) + ".")
    return redirect("events:event", pk=pk) 
Example 63
Project: i-portalen   Author: I-sektionen   File: views.py    MIT License 5 votes vote down vote up
def preregistrations_list(request, pk):
    event = get_object_or_404(Event, pk=pk)
    if event.can_administer(request.user):
        return render(request, 'events/event_preregistrations.html', {
            'event': event,
        })
    else:
        raise PermissionDenied  # Nope. 
Example 64
Project: i-portalen   Author: I-sektionen   File: views.py    MIT License 5 votes vote down vote up
def participants_list(request, pk):
    event = get_object_or_404(Event, pk=pk)
    if event.can_administer(request.user):
        return render(request, 'events/event_participants.html', {
            'event': event,
        })
    else:
        raise PermissionDenied  # Nope. 
Example 65
Project: i-portalen   Author: I-sektionen   File: views.py    MIT License 5 votes vote down vote up
def speech_nr_list(request, pk):
    event = get_object_or_404(Event, pk=pk)
    if event.can_administer(request.user):
        return render(request, 'events/event_speech_nr_list.html', {
            'event': event,
        })
    else:
        raise PermissionDenied  # Nope. 
Example 66
Project: i-portalen   Author: I-sektionen   File: views.py    MIT License 5 votes vote down vote up
def reserves_list(request, pk):
    event = get_object_or_404(Event, pk=pk)
    event_reserves = event.reserves_object()
    if event.can_administer(request.user):
        return render(request, 'events/event_reserves.html', {
            'event': event,
            'event_reserves': event_reserves,
        })
    else:
        raise PermissionDenied  # Nope. 
Example 67
Project: i-portalen   Author: I-sektionen   File: views.py    MIT License 5 votes vote down vote up
def check_in(request, pk):
    event = get_object_or_404(Event, pk=pk)
    can_administer = event.can_administer(request.user)
    if can_administer:
        form = CheckForm()
        return render(request, 'events/event_check_in.html', {
            'form': form, 'event': event, "can_administer": can_administer,
        })
    else:
        raise PermissionDenied 
Example 68
Project: i-portalen   Author: I-sektionen   File: views.py    MIT License 5 votes vote down vote up
def CSV_view_preregistrations(request, pk):
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="preregistrations.txt"'

    writer = csv.writer(response)
    writer.writerow(['These are your preregistrations:'])

    event = get_object_or_404(Event, pk=pk)
    preregistrations = event.preregistrations

    for user in preregistrations:
        writer.writerow([user.username, user.first_name, user.last_name, user.email])

    return response 
Example 69
Project: i-portalen   Author: I-sektionen   File: views.py    MIT License 5 votes vote down vote up
def unregister(request, pk):
    if request.method == "POST":
        event = get_object_or_404(Event, pk=pk)
        try:
            event.deregister_user(request.user)
            messages.success(request, _("Du är nu avregistrerad på eventet."))
        except CouldNotRegisterException as err:
            messages.error(request,
                           "".join([_("Fel, kunde inte avregistrera dig på "),
                                    err.event.headline,
                                    _(" för att "),
                                    err.reason,
                                    "."]))
    return redirect("events:event", pk=pk) 
Example 70
Project: i-portalen   Author: I-sektionen   File: views.py    MIT License 5 votes vote down vote up
def personal_calendar_feed(request, liu_id):
    u = get_object_or_404(IUser, username=liu_id)
    events = Event.objects.events_by_user(u)
    response = render(request,
                      template_name='events/feed.ics',
                      context={'liu_user': u, 'events': events},
                      content_type='text/calendar; charset=UTF-8')
    response['Filename'] = 'feed.ics'
    response['Content-Disposition'] = 'attachment; filename=feed.ics'
    return response 
Example 71
Project: i-portalen   Author: I-sektionen   File: views.py    MIT License 5 votes vote down vote up
def profile_page(request, liu_id):
    u = get_object_or_404(IUser, username=liu_id)
    return render(request, 'user_managements/profile_page.html', {'user': u}) 
Example 72
Project: i-portalen   Author: I-sektionen   File: views.py    MIT License 5 votes vote down vote up
def single_article(request, pk):
    article = get_object_or_404(Thesis_Article, pk=pk)
    if article.can_administer(request.user):
        admin = True
    else:
        admin = False
    if article.show_article_before_experation or admin:
        # attachments = article.otherattachment_set
        # image_attachments = article.imageattachment_set
        return render(request, 'model/thesis_article.html', {
            'article': article,
            # 'attachments': attachments,
            # 'image_attachments': image_attachments,
            'can_administer': admin}) 
Example 73
Project: aurora   Author: carnby   File: views.py    MIT License 4 votes vote down vote up
def view_portrait(request, screen_name):
    print(screen_name)
    portrait = get_object_or_404(Portrait, auth_screen_name=screen_name.lower(), active=True)

    if not portrait.public_access_enabled:
        if not request.user.is_authenticated() or request.user.username.lower() != screen_name.lower():
            return render_to_response('portraits/protected.html', {
                'portrait_screen_name': screen_name,
                'portrait_pk': portrait.pk,
                'profile_data': json.dumps(portrait.user_data)
            }, context_instance=RequestContext(request))

    if not portrait.portrait_content:
        return render_to_response('portraits/wait.html', {
            'portrait_screen_name': screen_name,
            'portrait_pk': portrait.pk,
            'profile_data': json.dumps(portrait.user_data),
            'demo_portrait': portrait.demo_portrait
        }, context_instance=RequestContext(request))

    record_interactions = False
    show_recommendations = False

    if request.user.is_authenticated():
        record_interactions = True
        auth_portrait = Portrait.objects.get(auth_screen_name=request.user.username.lower(), active=True)

        if auth_portrait == portrait:
            show_recommendations = True
            portrait.last_access = timezone.now()
            portrait.save()

        if not 'experimental_group' in request.session or not 'portraits' in request.session['experimental_group']:
            print('preparing session')
            prepare_session(request, '{0}_{1}'.format(auth_portrait.condition_ui, auth_portrait.condition_rec), 'portraits')
            print(request.session)

    return render_to_response('portraits/portrait.html', {
        'portrait_screen_name': screen_name,
        'portrait_current_pk': portrait.pk,
        'condition_ui': portrait.condition_ui,
        'condition_rec': portrait.condition_rec,
        'last_update': portrait.last_update_date.isoformat(),
        'demo_portrait': portrait.demo_portrait,
        'show_recommendations': show_recommendations,
        'record_interactions': record_interactions,
        'current_app': 'portraits',
        'client_datetime_var': 'client_datetime'
    }, context_instance=RequestContext(request)) 
Example 74
Project: froide-campaign   Author: okfde   File: views.py    MIT License 4 votes vote down vote up
def campaign_page(request, slug):
    campaign_page = get_object_or_404(CampaignPage, slug=slug)

    if not can_read_object(campaign_page, request):
        raise Http404

    campaigns = campaign_page.campaigns.all()
    qs = InformationObject.objects.filter(campaign__in=campaigns)
    qs = qs.select_related('foirequest')
    stats = get_information_object_stats(qs)
    qs = qs.select_related('campaign', 'publicbody')

    cleaned_query = QueryDict(request.GET.urlencode().encode('utf-8'),
                              mutable=True)
    random_qs = cleaned_query.pop('random', None)

    filterset = InformationObjectFilterSet(
        cleaned_query, queryset=qs, campaigns=campaigns
    )

    if random_qs:
        qs = qs.filter(foirequest__isnull=True).order_by('?')
    else:
        qs = filterset.qs

    page = request.GET.get('page')
    paginator = Paginator(qs, 100)
    try:
        iobjs = paginator.page(page)
    except PageNotAnInteger:
        iobjs = paginator.page(1)
    except EmptyPage:
        iobjs = paginator.page(paginator.num_pages)

    getvars_complete = cleaned_query.urlencode()

    cleaned_query.pop('page', None)
    getvars = cleaned_query.urlencode()

    context = {
        'campaign_page': campaign_page,
        'object_list': iobjs,
        'filtered': filterset,
        'getvars': '&' + getvars,  # pagination
        'getvars_complete': getvars_complete,
    }
    context.update(stats)

    return render(request, 'froide_campaign/campaign.html', context) 
Example 75
Project: i-portalen   Author: I-sektionen   File: views.py    MIT License 4 votes vote down vote up
def create_or_modify_article(request, pk=None):  # TODO: Reduce complexity
    if pk:  # if pk is set we modify an existing article.
        duplicates = Article.objects.filter(replacing_id=pk)
        if duplicates:
            links = ""
            for d in duplicates:
                links += "<a href='{0}'>{1}</a><br>".format(d.get_absolute_url(), d.headline)
            messages.error(
                request,
                "".join([_("Det finns redan en ändrad version av det här arrangemanget!"
                           " Är du säker på att du vill ändra den här?"
                           "<br>Följande ändringar är redan föreslagna:"),
                         " <br> {:}"]).format(links),
                extra_tags='safe')
        article = get_object_or_404(Article, pk=pk)
        if not article.can_administer(request.user):
            raise PermissionDenied
        form = ArticleForm(request.POST or None, request.FILES or None, instance=article)
    else:  # new article.
        form = ArticleForm(request.POST or None, request.FILES or None)
    if request.method == 'POST':
        if form.is_valid():
            article = form.save(commit=False)

            if form.cleaned_data['draft']:
                draft = True
            else:
                draft = False

            status = article.get_new_status(draft)
            article.status = status["status"]
            article.user = request.user

            if status["new"]:
                article.replacing_id = article.id
                article.id = None

            article.save()
            form.save_m2m()
            if article.status == Article.DRAFT:
                messages.success(request, _("Dina ändringar har sparats i ett utkast."))
            elif article.status == Article.BEING_REVIEWED:
                body = "<h1>Hej!</h1><br><br><p>Det finns nya artiklar att godkänna på i-Portalen.<br><a href='https://www.i-portalen.se/article/unapproved/'>Klicka här!</a></p><br><br><p>Med vänliga hälsningar, <br><br>Admins @ webgroup"
                send_mail('Ny artikel att godkänna', '', settings.EMAIL_HOST_USER, ['[email protected]'], fail_silently=False, html_message=body)
                messages.success(request, _("Dina ändringar har skickats för granskning."))
            return redirect('articles:article', pk=article.pk)
        else:
            messages.error(request, _("Det uppstod ett fel, se detaljer nedan."))
            return render(request, 'articles/article_form.html', {
                'form': form,
            })
    return render(request, 'articles/article_form.html', {
        'form': form,
    }) 
Example 76
Project: i-portalen   Author: I-sektionen   File: views.py    MIT License 4 votes vote down vote up
def upload_attachments(request, article_pk):
    article = get_object_or_404(Article, pk=article_pk)
    if not article.can_administer(request.user):
        raise PermissionDenied
    AttachmentFormset = modelformset_factory(OtherAttachment,
                                             form=AttachmentForm,
                                             max_num=30,
                                             extra=3,
                                             can_delete=True,
                                             )
    if request.method == 'POST':
        formset = AttachmentFormset(request.POST, request.FILES, queryset=OtherAttachment.objects.filter(article=article))
        if formset.is_valid():
            for entry in formset.cleaned_data:
                if not entry == {}:
                    if entry['DELETE']:

                        try:
                            entry['id'].delete()  # TODO: Remove the clear option from html-widget (or make it work).
                        except AttributeError:
                            pass
                    else:
                        if entry['id']:
                            attachment = entry['id']
                        else:
                            attachment = OtherAttachment(article=article)
                            attachment.file_name = entry['file'].name
                        attachment.file = entry['file']
                        attachment.display_name = entry['display_name']
                        attachment.modified_by = request.user
                        attachment.save()
            messages.success(request, 'Dina bilagor har sparats.')
            return redirect('articles:manage attachments', article_pk=article.pk)
        else:
            return render(request, "articles/attachments.html", {
                        'article': article,
                        'formset': formset,
                        })
    formset = AttachmentFormset(queryset=OtherAttachment.objects.filter(article=article))
    return render(request, "articles/attachments.html", {
                        'article': article,
                        'formset': formset,
                        }) 
Example 77
Project: i-portalen   Author: I-sektionen   File: views.py    MIT License 4 votes vote down vote up
def upload_attachments_images(request, article_pk):
    article = get_object_or_404(Article, pk=article_pk)
    if not article.can_administer(request.user):
        raise PermissionDenied
    AttachmentFormset = modelformset_factory(ImageAttachment,
                                             form=ImageAttachmentForm,
                                             max_num=30,
                                             extra=3,
                                             can_delete=True,
                                             )
    if request.method == 'POST':
        formset = AttachmentFormset(request.POST,
                                    request.FILES,
                                    queryset=ImageAttachment.objects.filter(article=article)
                                    )
        if formset.is_valid():
            for entry in formset.cleaned_data:
                if not entry == {}:
                    if entry['DELETE']:
                        try:
                            entry['id'].delete()  # TODO: Remove the clear option from html-widget (or make it work).
                        except AttributeError:
                            pass
                    else:
                        if entry['id']:
                            attachment = entry['id']
                        else:
                            attachment = ImageAttachment(article=article)
                        attachment.img = entry['img']
                        attachment.caption = entry['caption']
                        attachment.modified_by = request.user
                        attachment.save()
            messages.success(request, 'Dina bilagor har sparats.')
            return redirect('articles:article', article.pk)
        else:
            return render(request, "articles/attach_images.html", {
                        'article': article,
                        'formset': formset,
                        })
    formset = AttachmentFormset(queryset=ImageAttachment.objects.filter(article=article))
    return render(request, "articles/attach_images.html", {
                        'article': article,
                        'formset': formset,
                        }) 
Example 78
Project: i-portalen   Author: I-sektionen   File: views.py    MIT License 4 votes vote down vote up
def create_or_modify_event(request, pk=None):  # TODO: Reduce complexity
    if pk:  # if pk is set we modify an existing event.
        duplicates = Event.objects.filter(replacing_id=pk)
        if duplicates:
            links = ""
            for d in duplicates:
                links += "<a href='{0}'>{1}</a><br>".format(d.get_absolute_url(), d.headline)
            messages.error(request,
                           "".join([_("Det finns redan en ändrad version av det här arrangemanget! "
                                      "Är du säker på att du vill ändra den här?<br>"
                                      "Följande ändringar är redan föreslagna: <br> "),
                                    "{:}"]).format(links),
                           extra_tags='safe')
        event = get_object_or_404(Event, pk=pk)
        if not event.can_administer(request.user):
            raise PermissionDenied
        form = EventForm(request.POST or None, request.FILES or None, instance=event)
    else:  # new event.
        form = EventForm(request.POST or None, request.FILES or None)
    if request.method == 'POST':
        if form.is_valid():
            event = form.save(commit=False)

            if form.cleaned_data['draft']:
                draft = True
            else:
                draft = False

            status = event.get_new_status(draft)
            event.status = status["status"]
            event.user = request.user

            if status["new"]:
                event.replacing_id = event.id
                event.id = None

            event.save()
            form.save_m2m()
            if event.status == Event.DRAFT:
                messages.success(request, _("Dina ändringar har sparats i ett utkast."))
            elif event.status == Event.BEING_REVIEWED:
                body = "<h1>Hej!</h1><br><br><p>Det finns nya artiklar att godkänna på i-Portalen.<br><a href='https://www.i-portalen.se/article/unapproved/'>Klicka här!</a></p><br><br><p>Med vänliga hälsningar, <br><br>Admins @ webgroup"
                send_mail('Ny artikel att godkänna', '', settings.EMAIL_HOST_USER, ['[email protected]'], fail_silently=False, html_message=body)
                messages.success(request, _("Dina ändringar har skickats för granskning."))
            return redirect('events:by user')
        else:
            messages.error(request, _("Det uppstod ett fel, se detaljer nedan."))
            return render(request, 'events/create_event.html', {
                'form': form,
            })
    return render(request, 'events/create_event.html', {
        'form': form,
    }) 
Example 79
Project: i-portalen   Author: I-sektionen   File: views.py    MIT License 4 votes vote down vote up
def upload_attachments(request, pk):
    event = get_object_or_404(Event, pk=pk)
    if not event.can_administer(request.user):
        raise PermissionDenied
    AttachmentFormset = modelformset_factory(OtherAttachment,
                                             form=AttachmentForm,
                                             max_num=30,
                                             extra=3,
                                             can_delete=True,
                                             )
    if request.method == 'POST':
        formset = AttachmentFormset(request.POST, request.FILES, queryset=OtherAttachment.objects.filter(event=event))
        if formset.is_valid():
            for entry in formset.cleaned_data:
                if not entry == {}:
                    if entry['DELETE']:
                        try:
                            entry['id'].delete()  # TODO: Remove the clear option from html-widget (or make it work).
                        except AttributeError:
                            pass
                    else:
                        if entry['id']:
                            attachment = entry['id']
                        else:
                            attachment = OtherAttachment(event=event)
                            attachment.file_name = entry['file'].name
                        attachment.file = entry['file']
                        attachment.display_name = entry['display_name']
                        attachment.modified_by = request.user
                        attachment.save()
            messages.success(request, 'Dina bilagor har sparats.')
            return redirect('events:manage attachments', pk=event.pk)
        else:
            return render(request, "events/attachments.html", {
                        'event': event,
                        'formset': formset,
                        })
    formset = AttachmentFormset(queryset=OtherAttachment.objects.filter(event=event))
    return render(request, "events/attachments.html", {
                        'event': event,
                        'formset': formset,
                        }) 
Example 80
Project: i-portalen   Author: I-sektionen   File: views.py    MIT License 4 votes vote down vote up
def upload_attachments_images(request, pk):
    event = get_object_or_404(Event, pk=pk)
    if not event.can_administer(request.user):
        raise PermissionDenied
    AttachmentFormset = modelformset_factory(ImageAttachment,
                                             form=ImageAttachmentForm,
                                             max_num=30,
                                             extra=3,
                                             can_delete=True,
                                             )
    if request.method == 'POST':
        formset = AttachmentFormset(request.POST,
                                    request.FILES,
                                    queryset=ImageAttachment.objects.filter(event=event)
                                    )
        if formset.is_valid():
            for entry in formset.cleaned_data:
                if not entry == {}:
                    if entry['DELETE']:
                        try:
                            entry['id'].delete()  # TODO: Remove the clear option from html-widget (or make it work).
                        except AttributeError:
                            pass
                    else:
                        if entry['id']:
                            attachment = entry['id']
                        else:
                            attachment = ImageAttachment(event=event)
                        attachment.img = entry['img']
                        attachment.caption = entry['caption']
                        attachment.modified_by = request.user
                        attachment.save()
            messages.success(request, 'Dina bilagor har sparats.')
            return redirect('events:event', event.pk)
        else:
            return render(request, "events/attach_images.html", {
                        'event': event,
                        'formset': formset,
                        })
    formset = AttachmentFormset(queryset=ImageAttachment.objects.filter(event=event))
    return render(request, "events/attach_images.html", {
                        'event': event,
                        'formset': formset,
                        })