Example #1
0
def world_detail_master_users(request, world_id):
    '''Process the user changes and redirect to world master.'''
    world = get_object_or_404(World, pk=world_id)
    
    user_membership = world.user_is_member(request.user)
    if not user_membership:
        request.user.message_set.create(message = "Access denied. Either you are not a member of the world requested, or your membership has not yet been approved.")
        return redirect_to(request, url ='/thegame/userprofile/')
    
    if not user_membership.is_master:
        request.user.message_set.create(message = 'You are not authorized to edit this world.')
        return HttpResponseRedirect(world.get_absolute_url())
        
    if request.method == 'POST':
        formset = MembershipFormSet(request.POST, 
                queryset = Membership.objects.filter(world = world).order_by('user__user__username'))
        if formset.is_valid():
            instances = formset.save()
            for membership in instances:
                if membership.approved == True and membership.user.user.is_active == False:
                    user = membership.user.user
                    user.is_active = True
                    user.save()
            
            request.user.message_set.create(message = "Users edited successfully.")
            return HttpResponseRedirect(world.get_absolute_url() + 'master/')
    else:
        return redirect_to(request, url=world.get_absolute_url + 'master/')
Example #2
0
def rename_tag(request):
    from django.utils.http import urlquote
    
    key = request.POST['key']
    value = request.POST.get('value', None)
    
    if value:
        tags = Tag.objects.filter(key=key, value=value)
    else:
        tags = Tag.objects.filter(key=key)

    for tag in tags:
        if value and 'new_value' in request.POST:
            tag.value = request.POST['new_value']
        if 'new_key' in request.POST:
            tag.key = request.POST['new_key']
        tag.save()
    
    if 'new_key' in request.POST:
        if 'new_value' in request.POST:    
            return redirect_to(request, reverse('openresources_tag', kwargs={'key':urlquote(request.POST['new_key']), 'value': urlquote(request.POST['new_value'])}))
        return redirect_to(request, reverse('openresources_tag_key', kwargs={'key':urlquote(request.POST['new_key'])}))

    if value:
        return redirect_to(request, reverse('openresources_tag', kwargs={'key':urlquote(key), 'value': urlquote(value)}))
    
    return redirect_to(request, reverse('openresources_tag_key', kwargs={'key':urlquote(key)}))
Example #3
0
def complete_profile(request):

    p = request.user.get_profile()
    if p.is_profile_complete(): return redirect_to(request, reverse('dashboard'))

    form = CompleteProfileForm(instance = p)
    if request.method == 'POST':
    
        form = CompleteProfileForm(request.POST, instance=p)
        if form.is_valid():
            
            request.user.userdata_set.create(
                                             weight=form.cleaned_data['current_weight'], 
                                             waist=form.cleaned_data['current_waist'])
            form.save()
            request.user.save()
            
            request.user.message_set.create(message="Uzupełniono profil")
            
            try:
                FlatPage.objects.get(url='/wprowadzenie/')
                return redirect_to(request, '/wprowadzenie/')
            except FlatPage.DoesNotExist: #@UndefinedVariable
                return redirect_to(reverse('dashboard'), '/wprowadzenie/')
            

    
    return direct_to_template(request, "home/complete_profile.html", extra_context= {'form':form })
Example #4
0
def double_digit_checker(request,year,month,day=None):
    if len(month) == 1:
        try:
            url = reverse(
                "blog:archive_month",
                args=[year,"0%s" % month]
            )
        except:
            raise Http404
        return redirect_to(
            request,
            url
        )
    if day and len(day) == 1:
        try:
            url = reverse(
                "blog:archive_month",
                args=[year,month,"0%s" % day]
            )
        except:
            raise Http404
        return redirect_to(
            request,
            url
        )
    return None
Example #5
0
def feedback(request):

    page_title = u"Feedback"
    breadcrumbs = [{"url": reverse("feedback"), "title": page_title}]

    user = None
    if request.user.is_authenticated():
        user = request.user

    form = FeedbackForm(user=user)

    if request.method == "POST":
        if "send" in request.POST:
            form = FeedbackForm(request.POST, user=user)
            if form.is_valid():
                message = form.save(commit=False)
                if user is not None:
                    message.name = ("%s %s" % (user.first_name, user.last_name)).strip()
                    message.email = user.email
                message.save()
                messages.success(request, u"Thank you, your feedback message was sent to site administrators.")
                return redirect_to(request, reverse("frontpage"), permanent=False)
            else:
                messages.error(request, u"Please correct the indicated errors.")
        elif "cancel" in request.POST:
            return redirect_to(request, reverse("frontpage"), permanent=False)

    disable_getsatisfaction_tab = True
    return direct_to_template(request, "feedback/feedback.html", locals())
Example #6
0
def poll_vote(request, id, choice, **kwargs):
    """Votes the selected choice.
    """
    from datetime import datetime

    poll = get_object_or_404(Poll, id=id)

    if poll.due_date is not None and poll.due_date < datetime.now():
        messages.warning(request, _("Sorry, this poll is already closed."))
        return redirect_to(request, permanent=False, url=poll.get_absolute_url())

    try:
        owner = request.user
        choices = poll.choices.all()
        choice_obj = choices[int(choice)]
        previous_vote = Vote.objects.get_for_models(choices).filter(owner=owner)
        if previous_vote.count() == 0:
            messages.success(request, _("Thank you for your vote."))
        else:
            previous_vote.delete()
            messages.success(request, _("Thank you. Your vote was updated successfully."))
        new_vote = Vote.objects.create(owner=owner, content_object=choice_obj)

    except IndexError:
        messages.error(request, _("Sorry, you selected an invalid choice."))

    return redirect_to(request, permanent=False, url=poll.get_absolute_url())
Example #7
0
def dissociate(
    request,
    template_name="authopenid/dissociate.html",
    dissociate_form=OpenidDissociateForm,
    redirect_field_name=REDIRECT_FIELD_NAME,
    default_redirect=settings.LOGIN_REDIRECT_URL,
    extra_context=None,
):
    """ view used to dissociate an openid from an account """
    nb_associated_openids, associated_openids = get_associate_openid(request.user)
    if nb_associated_openids == 1 and not request.user.has_usable_password() and request.method != "GET":
        msg = ["You can't remove this openid, you should set a password first."]
        return render_to_response(
            "authopenid/associate.html",
            {"associated_openids": associated_openids, "nb_associated_openids": nb_associated_openids, "msg": msg},
            context_instance=RequestContext(request),
        )

    if request.POST:
        if request.POST.get("bdissociate_cancel", "") == "Cancel":
            msg = ["Operation Cancel."]
            return redirect_to(request, "/accounts/openid/associate/")

        openid_urls = request.POST.getlist("a_openids_remove")
        if len(openid_urls) >= 1:
            for openid_url in openid_urls:
                UserAssociation.objects.get(openid_url__exact=openid_url).delete()
                if openid_url == request.session.get("openid_url"):
                    del request.session["openid_url"]
                msg = "Openid removed."

            request.user.message_set.create(message=msg)
            return redirect_to(request, "/accounts/openid/associate")
    else:
        return redirect_to(request, "/accounts/openid/associate")
Example #8
0
def cluster_accounts_new(request, cluster_id):
    """"""
    try:
        cluster = Cluster.objects.get(id = cluster_id)
    except Exception:
        return HttpResponse('this cluster doesn\'t exist')

    if request.method == 'POST':

        ClusterAccountFilledFormSet = modelformset_factory(ClusterAccount,
            form = ClusterAccountForm,
            can_delete = True,
            extra = 0)

        ClusterAccountFormSet = modelformset_factory(ClusterAccount,
            form = ClusterAccountForm,
            extra = 3)

        formset = ClusterAccountFormSet(request.POST)
        formset_filled = ClusterAccountFilledFormSet(request.POST, prefix = 'filled')

        if formset_filled.is_valid():
            formset_filled.save()

        if formset.is_valid():
            for form in formset.save(commit = False):
                form.cluster = cluster
                form.save()

        if 'more' in request.POST:
            return redirect_to(request, '/cluster/%s/provision/accounts/' % cluster_id)
        else:
            return redirect_to(request, '/cluster/%s/provision/' % cluster_id)
Example #9
0
def change_plan(request):
    if request.method == 'POST':
        user_plan = get_user_plan(request)
        new_plan = request.POST.get('plan')
        new_price_plan = PricePlan.objects.filter(active=True, slug=new_plan)
        if new_plan != user_plan.price_plan.slug and new_price_plan:
            recurly = Recurly(**settings.RECURLY)
            
            update_data = {
              'timeframe': 'renewal',
              'plan_code': new_plan,
            }
            update_result = recurly.accounts.subscription.update(account_code=user_plan.recurly_account_code, data=update_data)
            logging.debug(update_result)
            
            new_user_plan = UserPlan(price_plan=new_price_plan[0], account=user_plan.account, 
                                 recurly_account_code=update_result['account_code'],
                                 recurly_login_token=user_plan.recurly_login_token,
                                 card_set_up=user_plan.card_set_up)
            user_plan.end_date = datetime.datetime.now()
            user_plan.save()
            new_user_plan.save()
            
            set_message(request, 'plan_changed', context={'old_user_plan': user_plan, 'new_user_plan': new_user_plan})
            return redirect_to(request, reverse('administer_site',args=[request.user.get_profile().last_website_id]))
        else:
            set_message(request, 'plan_not_changed', level='attention', context={'user_plan': user_plan})
            return redirect_to(request, reverse('choose_plan'))  
    else:
        return HttpResponseBadRequest()
Example #10
0
def pvt_message(request, receiver):
    """This function will store pvt msgs in db
        and send a notification mail to receiver"""    
    if request.method == "POST":
        referer = request.META.get('HTTP_REFERER', '')
        sender = request.user
        receiver_username =  request.POST.get('receiver_username', False) 
        receiver = get_object_or_404(User, username=receiver_username)
        msg = request.POST.get('pvt_msg', False) 
        account = get_object_or_404(Account, user=sender, provider=0)
        if isfollowing(receiver, sender) or is_in_group(sender,'team'):
            if sender.is_active == 4:
                request.session['flash'] = "You are temporarily not allowed to message someone. Please contact support@kwippy.com"
                return redirect_to(request, referer)
            message = Private_Message(sender=sender, receiver=receiver,
                                  message=msg, account=account)
            message.save()
            list_filter = List_Filter(receiver_user = receiver, pm = message,status=0)
            list_filter.save()
            sent_filter = Sent_Filter(sender_user = sender, pm = message)
            sent_filter.save()
            request.session['flash'] = "Your private message was sent"
            params_for_mail = {'#_1':receiver.username,'#_2':sender.username, '#_3':msg, '#_4':str(message.id)}
            send_mail(str(receiver.email), 'kwippy <support@kwippy.com>', 'private_message', params_for_mail)
            send_im(receiver,'private_message', params_for_mail)
            return redirect_to(request, referer)
        else:
            request.session['flash'] = "You cannot send this message"
            return redirect_to(request, referer)
Example #11
0
def submit(request, recipients=None, debug=False, redirect_url=None):
    """
    Submit the contact form request.
    
    recipients: 
        the recipients to which the rendered form will be sent
    debug:
        if True, do everything but actually send the message
    redirect_url:
        if supplied, redirect a non-POST request to this url rather than raise a 404 error
    """
    if request.method == "POST":
        args = { 'success' : False }
        form = ContactForm(request.POST)
        if form.is_valid():
            sender = render_sender(form.cleaned_data)
            subject = render_subject(form.cleaned_data) 
            message = render_message(form.cleaned_data)
            
            if not debug:
                send_mail(subject, message, sender, recipients, fail_silently=False) #,auth_user=None, auth_password=None, connection=None)
            
            args = form.cleaned_data
            args['message'] = render_to_string('success.html', args)
            args['success'] = True
            return args
        else:
            args['message'] = render_to_string('fail.html')
            return args
    elif redirect_url:
         from django.views.generic.simple import redirect_to
         redirect_to(request, redirect_url)
    else:  
        raise Http404
Example #12
0
def FusionFlickrNew(request, flickrid):
    try:
        now = imagefromflickrid(flickrid, request.user)
    except ValidationError:
        return redirect_to(request, reverse('incorrect_license'))
    
    #return redirect_to(request, '/fusion/new/%d?init=true' % now.id)
    return redirect_to(request, reverse('fusion_new', args=[now.id]) + '?init=true')
Example #13
0
def logout(request):
    auth_logout(request)
    if 'next' in request.GET and request.GET['next']:
        return redirect_to(request, request.GET['next'], permanent=False)
    elif 'next' in request.POST and request.POST['next']:
        return redirect_to(request, request.POST['next'], permanent=False)
    else:
        return redirect_to(request, '/', permanent=False)
Example #14
0
def edit_view(request, name=None):
    view = None
    if name:
        view = get_object_or_404(View, shortname=name)
    
    if request.method == "POST":
        form = ViewForm(request.user, request.POST, instance=view, prefix='view')
        if form.is_valid():
            
            if not view:
                # new view
                view = form.save(commit=False)
                view.creator = request.user
                view.save()
                form.save_m2m()
            else:
                form.save()
            
            queryformset = QueryFormSet(request.POST, instance=view, prefix='queries')
            queries_valid = queryformset.is_valid()
            if queries_valid:
                queryformset.saved_forms = []
                queryformset.save_existing_objects()
                queries = queryformset.save_new_objects(commit=False)
                for query in queries:
                    query.creator = request.user
                    query.save()
                    
            mappingformset = TagMappingFormSet(request.POST, instance=view, prefix='mappings')
            mappings_valid = mappingformset.is_valid()
            if mappings_valid:
                mappingformset.saved_forms = []
                mappingformset.save_existing_objects()
                mappings = mappingformset.save_new_objects(commit=False)
                for mapping in mappings:
                    mapping.creator = request.user
                    mapping.save()
            
            if queries_valid and mappings_valid:       
                if 'action' in request.POST and request.POST['action'] == 'add_row':
                    return redirect_to(request, reverse('openresources_edit_view', kwargs={'name':view.shortname}))               
                else:
                    return redirect_to(request, reverse('openresources_view', kwargs={'name':view.shortname}))               
        else:
            queryformset = QueryFormSet(instance=view, prefix='queries')
            mappingformset = TagMappingFormSet(instance=view, prefix='mappings')
    else:
        form = ViewForm(request.user, instance=view, prefix='view')
        queryformset = QueryFormSet(instance=view, prefix='queries')
        mappingformset = TagMappingFormSet(instance=view, prefix='mappings')
    
    popular_tags = Tag.objects.values('key').annotate(key_count=Count('key')).filter(key_count__gt=2).order_by('key')
    tag_help = settings.TAG_HELP_LINKS

    return render_to_response('openresources/view_edit.html', RequestContext(request, locals()))
Example #15
0
def tickets(request):
    if not request.user.is_authenticated():
        form = LoginForm()
        message = "Please log in to continue."
        return direct_to_template(request,
                'registration/login.html', {'form': form,
                'message': message})
    if request.method == 'POST':
        if request.POST.get('action', '') == 'transfer':
            email = request.POST.get('email', '')
            ticket_id = request.POST.get('ticket_id', '')
            ticket = Ticket.objects.get(pk=ticket_id)
            if ticket.purchase.user != request.user:
                return direct_to_template(request, 'texas/error.html',
                        {'message': "Access denied"})
            else:
                try:
                    assigned_user = User.objects.get(email__iexact=email)
                except:
                    assigned_user = None

                if not assigned_user:
                    assigned_user = User.objects.create_user(username=email,
                            email=email, password='')
                    assigned_user.first_name = ''.join(Random().sample(
                            string.letters+string.digits, 5))
                    assigned_user.is_active = False
                    assigned_user.save()

                ticket.assigned_user = assigned_user
                ticket.waiver = None
                #ticket.set_code()
                ticket.save()
                do_send_transfer_notification(ticket)
                return redirect_to(request, '/tickets/')

    paid_purchases = Purchase.objects.filter(
            user=request.user, status='P'
    ).exclude(
            occurrence__end_date__lte=datetime.now()
    )
    assigned_tickets = Ticket.objects.filter(
            assigned_user=request.user, purchase__status='P'
    ).exclude(
            purchase__occurrence__end_date__lte=datetime.now()
    )

    for ticket in assigned_tickets:
        if ticket.purchase.occurrence.event.waiver and not ticket.waiver:
            # break on the first one found
            return redirect_to(request, '/tickets/waiver/%s/' % ticket.id)

    return direct_to_template(request, 'texas/tickets.html',
            {'paid_purchases': paid_purchases,
                    'assigned_tickets': assigned_tickets})
Example #16
0
def logged_in(request):
    
    if request.user.is_staff:
        return redirect_to(request, reverse('patients_list'))
    
    if request.user.is_authenticated():
        p = request.user.get_profile()
        if p.is_profile_complete():
            return redirect_to(request, reverse('dashboard'))
        else:
            return redirect_to(request, reverse('complete_profile'))
Example #17
0
def edit_with_template(request, resource=None, template=None):

    if resource and not isinstance(resource, Resource):
        resource = get_object_or_404(Resource, shortname=resource)

    if template and not isinstance(template, ResourceTemplate):
        template = get_object_or_404(ResourceTemplate, shortname=template)

    key_choices = Tag.objects.values('key').annotate(key_count=Count('key')).filter(key_count__gt=2).order_by('key')
    key_choices = [(val['key'], val['key']) for val in key_choices]

    if request.method == "POST":
        form = ResourceForm(request.user, request.POST, request.FILES, instance=resource)
        if form.is_valid():
            
            if not resource:
                # new resource
                resource = form.save(commit=False)
                resource.creator = request.user
                resource.save()
                form.save_m2m()
            else:
                form.save()

            # we have to wait until here to create the formset to be able to assign the instance
            formset = TemplateFormSet(template, request.POST, request.FILES, instance=resource,
                                        can_delete=request.user.has_perm('openresources.delete_tag'),
                                        key_choices=key_choices)

            if formset.is_valid():     
         
                formset.saved_forms = []
                formset.save_existing_objects()
                tags = formset.save_new_objects(commit=False)
                for tag in tags:
                    tag.creator = request.user
                    tag.save()

            if 'action' in request.POST and request.POST['action'] == 'add_tag':
                return redirect_to(request, reverse('openresources_edit_with_template', kwargs={'resource':resource.shortname, 'template':template.shortname}))               
            else:

                return redirect_to(request, reverse('openresources_resource', kwargs={'key':resource.shortname}))               
    else:
        if template and not resource:
            # pre-initialize template field for new resources
            form = ResourceForm(request.user, initial={'template':template})
        else:
            form = ResourceForm(request.user, instance=resource)
        formset = TemplateFormSet(template, instance=resource, can_delete=request.user.has_perm('openresources.delete_tag'), key_choices=key_choices)
    
    return render_to_response('openresources/edit_with_template.html', RequestContext(request, locals()))
Example #18
0
def bid_history(request, auction_id):
    auction = get_object_or_404(Auction, pk=auction_id)
    
    user_membership = auction.asset.period.world.user_is_member(request.user)
    if not user_membership:
        request.user.message_set.create(message = "Access denied. Either you are not a member of the world requested, or your membership has not yet been approved.")
        return redirect_to(request, url ='/thegame/userprofile/')
    
    # if our period hasn't started yet, don't show the info.
    if not auction.asset.period.is_started() and not user_membership.is_master:
        request.user.message_set.create(message = "Period " + unicode(auction.asset.period.number) + " of World " + auction.asset.period.world.name + " has not yet started.")
        return redirect_to(request, url ='/thegame/userprofile/')
    else:
        return render_to_response('bid_history.html', {'auction':auction, 'user_membership':user_membership}, context_instance=RequestContext(request))
Example #19
0
def period_detail(request, world_id, period_id):
    period = get_object_or_404(Period, pk=period_id)
    world = get_object_or_404(World, pk=world_id)
    
    user_membership = world.user_is_member(request.user)
    if not user_membership:
        request.user.message_set.create(message = "Access denied. Either you are not a member of the world requested, or your membership has not yet been approved.")
        return redirect_to(request, url ='/thegame/userprofile/')

    # if our period hasn't started yet, don't show the info.
    if not period.is_started() and not user_membership.is_master:
        request.user.message_set.create(message = "Period " + unicode(period.number) + " of World " + world.name + " has not yet started.")
        return redirect_to(request, url ='/thegame/userprofile/')

    return render_to_response('period_detail.html', {'period':period, 'world':world, 'user_membership':user_membership}, context_instance=RequestContext(request))
Example #20
0
def ajaxGenerateDendogram(request):
    if not request.user.is_authenticated():
        return redirect_to(request, '/auth/login/')
    if request.POST.has_key('gridUSID'):
        grid1= Grid.objects.filter(user= request.user, usid= request.POST['gridUSID'])
        if len(grid1) >= 1:
            try:
                grid1= grid1[0]
                if grid1.dendogram != None and grid1.dendogram != '':
                    return HttpResponse(grid1.dendogram, content_type='application/xml')
                else:
                    try:     
                        imgData= createDendogram(grid1)
                        return HttpResponse(imgData, content_type='application/xml')
                    except:
                        print "Exception in user code:"
                        print '-'*60
                        traceback.print_exc(file=sys.stdout)
                        print '-'*60
                        return HttpResponse(createXmlErrorResponse('Unknown dendrogram error'), content_type='application/xml')
            except:
                print "Exception in user code:"
                print '-'*60
                traceback.print_exc(file=sys.stdout)
                print '-'*60
                return HttpResponse(createXmlErrorResponse('Unknown error'), content_type='application/xml')
        else:
            return HttpResponse(createXmlErrorResponse('Could not find the grid to generate the dendrogram'), content_type='application/xml')
    else:
        return HttpResponse(createXmlErrorResponse('Invalid request, request is missing argument(s)'), content_type='application/xml')
Example #21
0
def signin(request):
    try:
        next = request.POST['next']
    except KeyError:
        try:
            next = request.GET['next']
        except KeyError:
            next = SNAP_PREFIX

    if request.POST:
        form_data = request.POST.copy()
        form = LoginForm(form_data)

        if form.is_valid():
            user = form.user
            login(request, user)
            form = LoginForm()
            return redirect_to(request, next)
    else:
        form = LoginForm()

    return render_to_response('snapboard/signin.html',
        {
        'login_form': form,
        'login_next': next,
        },
        context_instance=RequestContext(request))
Example #22
0
def world_detail_master(request, world_id):
    # world attributes/settings edit form, prefilled
    # list periods, with edit/delete links, create new button
    # list users, with approve/delete/edit links, create new button
    world = get_object_or_404(World, pk=world_id)
    user_membership = world.user_is_member(request.user)
    if not user_membership:
        request.user.message_set.create(message = "Access denied. Either you are not a member of the world requested, or your membership has not yet been approved.")
        return redirect_to(request, url ='/thegame/userprofile/')
    
    if not user_membership.is_master:
        request.user.message_set.create(message = 'You are not authorized to edit this world.')
        return HttpResponseRedirect(world.get_absolute_url())
    
    world_form = WorldForm(instance = world)
    
    # could this ever error if a user is created in the middle, thus creating
    # an unequal number of items in formset and queryset?
    membership_queryset = Membership.objects.filter(world = world).order_by('user__user__username')
    user_formset = MembershipFormSet(queryset = membership_queryset)
    user_formset_dict = dict(zip(membership_queryset, user_formset.forms))
    
        
    return render_to_response('world_detail_master.html', 
            {'world_form':world_form, 
            'user_formset':user_formset, 
            'user_formset_dict': user_formset_dict, 
            'world':world,
            'user_membership':user_membership,}, 
            context_instance=RequestContext(request))
Example #23
0
def getCreateMyGridPage(request):
    if not request.user.is_authenticated():
        return redirect_to(request, '/auth/login/')
    try:
        tableOnly= False
        if request.REQUEST.has_key('tableOnly'):
            if request.REQUEST['tableOnly'] == 'true':
                tableOnly= True
    
        gridTableTemplate= GridTableData(generateGridTable(None))
        gridTableTemplate.changeRatingsWeights= True
        gridTableTemplate.changeCornAlt= True
        gridTableTemplate.tableId= randomStringGenerator()
             
        context= None 
        #RequestContext(request, {'data': gridTableTemplate })
        if tableOnly:
            template= loader.get_template('gridMng/createMyGridBase.html')
            templateData= CreateMyGridBaseData(gridTableTemplate)
            context= RequestContext(request, {'data': templateData })
            htmlData= template.render(context)
            return HttpResponse(createXmlSuccessResponse(htmlData), content_type='application/xml')
        else:
            templateData= CreateMyGridData(CreateMyGridBaseData(gridTableTemplate))
            context= RequestContext(request, {'data': templateData })
            return render(request, 'gridMng/createMyGrid.html', context_instance=context)

    except:
        #do nothing
        print "Exception in user code:"
        print '-'*60
        traceback.print_exc(file=sys.stdout)
        print '-'*60
        return HttpResponse(createXmlErrorResponse('unknown error'), content_type='application/xml')
Example #24
0
    def add_view(self, request, form_url='', extra_context=None):
        model = self.model
        opts = model._meta

        if request.method == "POST":
            if "cancel" in request.POST:
                return redirect_to(request, reverse("admin:materials_course_changelist"))
            form = CourseAddForm(request.POST, initial=dict(creator=request.user))
            authors_formset = AuthorsFormSet(request.POST, prefix="authors", queryset=Author.objects.none())
            if form.is_valid() and authors_formset.is_valid():
                obj = form.save()
                saved_authors = authors_formset.save()
                # TODO: reindex all related objects if author info were changed
                for author in saved_authors:
                    obj.authors.add(author)
                obj.save()
                return self.response_add(request, obj)
        else:
            form = CourseAddForm(initial=dict(creator=request.user))
            authors_formset = AuthorsFormSet(prefix="authors", queryset=Author.objects.none())

        context = {
            'title': _('Add %s') % force_unicode(opts.verbose_name),
            'form': form,
            'authors_formset': authors_formset,
            'main_fields': MAIN_FIELDS_CHANGE,
            'is_popup': request.REQUEST.has_key('_popup'),
            'show_delete': False,
            'app_label': opts.app_label,
            'media': mark_safe(self.media + forms.Media(js=['%s%s' % (settings.ADMIN_MEDIA_PREFIX, 'js/collapse.min.js')])),
        }
        context.update(extra_context or {})
        return self.render_change_form(request, context, form_url=form_url, add=True)
Example #25
0
def edit_tap(request, tap_id):
  context = RequestContext(request)
  tap = get_object_or_404(models.KegTap, site=request.kbsite, seqn=tap_id)
  form = forms.ChangeKegForm()

  form = forms.ChangeKegForm(request.POST)
  if form.is_valid():
    current = tap.current_keg
    if current and current.status != 'offline':
      current.status = 'offline'
      current.save()
    new_keg = models.Keg()
    new_keg.site = request.kbsite
    new_keg.type = form.cleaned_data['beer_type']
    new_keg.size = form.cleaned_data['keg_size']
    new_keg.status = 'online'
    if form.cleaned_data['description']:
      new_keg.description = form.cleaned_data['description']
    new_keg.save()
    tap.current_keg = new_keg
    tap.save()
    messages.success(request, 'The new keg was activated. Bottoms up!')
    form = forms.ChangeKegForm()

  result_url = reverse('kegadmin-taps', args=[request.kbsite.url()])
  return redirect_to(request, result_url)
Example #26
0
def static_serve(request, path, client):
    """
    Given a request for a media asset, this view does the necessary wrangling
    to get the correct thing delivered to the user. This can also emulate the
    combo behavior seen when SERVE_REMOTE == False and EMULATE_COMBO == True.
    """
    if msettings["SERVE_REMOTE"]:
        # We're serving from S3, redirect there.
        url = client.remote_media_url().strip("/") + "/%(path)s"
        return redirect_to(request, url, path=path)

    if not msettings["SERVE_REMOTE"] and msettings["EMULATE_COMBO"]:
        # Combo emulation is on and we're serving media locally. Try to see if
        # the given path matches a combo file defined in the JOINED dict in
        # the MEDIASYNC settings dict.
        combo_match = _find_combo_match(path)
        if combo_match:
            # We found a combo file match. Combine it and serve the result.
            return combo_serve(request, combo_match, client)

    # No combo file, but we're serving locally. Use the standard (inefficient)
    # Django static serve view.
    resp = serve(request, path, document_root=client.media_root)
    resp.content = client.process(resp.content, resp["Content-Type"], path)
    return resp
Example #27
0
    def add_view(self, request, form_url="", extra_context=None):
        model = self.model
        opts = model._meta

        if request.method == "POST":
            if "cancel" in request.POST:
                return redirect_to(request, reverse("admin:materials_library_changelist"))
            form = LibraryAddForm(request.POST, initial=dict(creator=request.user))
            authors_formset = AuthorsFormSet(request.POST, prefix="authors", queryset=Author.objects.none())
            if form.is_valid() and authors_formset.is_valid():
                obj = form.save()
                saved_authors = authors_formset.save()
                # TODO: reindex all related objects if author info were changed
                for author in saved_authors:
                    obj.authors.add(author)
                obj.save()
                return self.response_add(request, obj)
        else:
            form = LibraryAddForm(initial=dict(creator=request.user))
            authors_formset = AuthorsFormSet(prefix="authors", queryset=Author.objects.none())

        context = {
            "title": _("Add %s") % force_unicode(opts.verbose_name),
            "form": form,
            "authors_formset": authors_formset,
            "main_fields": MAIN_FIELDS_CHANGE,
            "is_popup": request.REQUEST.has_key("_popup"),
            "show_delete": False,
            "app_label": opts.app_label,
            "media": mark_safe(
                self.media + forms.Media(js=["%s%s" % (settings.ADMIN_MEDIA_PREFIX, "js/collapse.min.js")])
            ),
        }
        context.update(extra_context or {})
        return self.render_change_form(request, context, form_url=form_url, add=True)
Example #28
0
def period_results_master(request, world_id, period_id):
    # button to regenerate period results
    
    period = get_object_or_404(Period, pk=period_id)
    world = get_object_or_404(World, pk=world_id)
    
    user_membership = world.user_is_member(request.user)
    if not user_membership:
        request.user.message_set.create(message = "Access denied. Either you are not a member of the world requested, or your membership has not yet been approved.")
        return redirect_to(request, url ='/thegame/userprofile/')
    
    if not user_membership.is_master:
        request.user.message_set.create(message = 'You are not authorized to edit this world.')
        return HttpResponseRedirect(period.get_absolute_url())
    
    # if our period hasn't completed yet, don't show the info.
    if not period.is_ended():
        request.user.message_set.create(message = "Period " + unicode(period.number) + " of World " + world.name + " is not yet complete.")
        return HttpResponseRedirect(request.user.get_profile().get_absolute_url())
    
    if request.method == 'POST': # If the form has been submitted...
        form = RecalculatePeriodResultsForm(request.POST)
        if form.is_valid():
            #period.recalc_period_summary(form.cleaned_data['update_wealth'])
            period.calc_period_summary(force=True, 
                    recalc_auctions = form.cleaned_data['recalc_auctions'])
            request.user.message_set.create(message = "Results recalculated.")
            return HttpResponseRedirect('.')
        else: 
            request.user.message_set.create(message = "Form errors.")
    else:
        form = RecalculatePeriodResultsForm()
    
    period_result_list = period.periodsummary_set.all().order_by('-correct_count')
    return render_to_response('period_results_master.html', {'period':period, 'world':world, 'user_membership':user_membership, 'period_result_list':period_result_list, 'form':form}, context_instance=RequestContext(request))
Example #29
0
def auction_detail_master(request, auction_id):
    # auction edit form, prefilled
    # list bids, with delete links? or do that in bid history
    
    auction = get_object_or_404(Auction, pk=auction_id)
    
    user_membership = auction.asset.period.world.user_is_member(request.user)
    if not user_membership:
        request.user.message_set.create(message = "Access denied. Either you are not a member of the world requested, or your membership has not yet been approved.")
        return redirect_to(request, url ='/thegame/userprofile/')
    
    if not user_membership.is_master:
        request.user.message_set.create(message = 'You are not authorized to edit this world.')
        return HttpResponseRedirect(auction.get_absolute_url())
    
    if request.method == 'POST': # If the form has been submitted...
        asset_form = AssetForm(request.POST, instance=auction.asset, queryset = auction.asset.period.world.period_set.all()) # A form bound to the POST data for asset
        auction_form = AuctionForm(request.POST, instance=auction) # A form bound to the POST data for auction
        if asset_form.is_valid() and auction_form.is_valid():
            new_asset = asset_form.save()
            new_auction = auction_form.save()
            
            request.user.message_set.create(message = "Auction edited successfully.")
            return HttpResponseRedirect('.')
        else:
            request.user.message_set.create(message = "Errors in form.")
    else:
        asset_form = AssetForm(instance = auction.asset, queryset = auction.asset.period.world.period_set.all())
        auction_form = AuctionForm(instance = auction)

    return render_to_response('auction_detail_master.html', {'auction':auction, 'user_membership':user_membership, 'asset_form':asset_form, 'auction_form':auction_form}, context_instance=RequestContext(request))
Example #30
0
def period_detail_master(request, world_id, period_id):
    # period attributes edit form, prefilled
    # list asset-auctions, with edit/delete links, create new button
    period = get_object_or_404(Period, pk=period_id)
    world = get_object_or_404(World, pk=world_id)
    
    user_membership = world.user_is_member(request.user)
    if not user_membership:
        request.user.message_set.create(message = "Access denied. Either you are not a member of the world requested, or your membership has not yet been approved.")
        return redirect_to(request, url ='/thegame/userprofile/')
    
    if not user_membership.is_master:
        request.user.message_set.create(message = 'You are not authorized to edit this world.')
        return HttpResponseRedirect(period.get_absolute_url())
    
    q = World.objects.filter(membership__user__user = request.user)
    
    if request.method == 'POST': # If the form has been submitted...
        period_form = PeriodForm(request.POST, instance=period, queryset = q) # A form bound to the POST data for asset
        if period_form.is_valid():
            new_period = period_form.save()
            
            request.user.message_set.create(message = "Period edited successfully.")
            return HttpResponseRedirect('.')
    else:
        period_form = PeriodForm(instance = period, queryset = q)
    
    membership_queryset = Membership.objects.filter(world = world).order_by('user__user__username')
    period_bids = Bid.objects.filter(auction__asset__period=period)
    
    return render_to_response('period_detail_master.html', {'period':period, 'world':world, 'user_membership':user_membership, 'period_form':period_form, 'world_members':membership_queryset, 'period_bids':period_bids}, context_instance=RequestContext(request))