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 [email protected]" 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 <*****@*****.**>', '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)
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())
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
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/')
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 })
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())
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())
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")
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)
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()
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)}))
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
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')
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)
def index(request): if request.user.is_authenticated(): return redirect_to(request, '/projeto/Tarefa/listar/', {}, context_instance=RequestContext(request)) else: return redirect_to(request, '/login/', {}, context_instance=RequestContext(request))
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})
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()))
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'))
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()))
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))
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))
def expensevoucher_add(request, **kwargs): """Adds a new expensevoucher. """ expensevoucher = ExpenseVoucher(date=datetime.now().date()) doc = Document(author=request.user, content_object=expensevoucher) if request.method == 'POST': dform = DocumentForm(request.POST, instance=doc) form = ExpenseVoucherForm(request.POST, instance=expensevoucher) formset = ExpenseEntryFormset(request.POST, instance=expensevoucher) if form.is_valid() and dform.is_valid() and formset.is_valid(): form.save() doc.content_object = expensevoucher dform.save() formset.save() messages.success( request, _("The expense voucher was created successfully.")) return redirect_to(request, url=doc.get_absolute_url()) else: dform = DocumentForm(instance=doc) form = ExpenseVoucherForm(instance=expensevoucher) formset = ExpenseEntryFormset(instance=expensevoucher) return render_to_response( 'hr/expensevoucher_edit.html', RequestContext(request, { 'form': form, 'dform': dform, 'formset': formset, 'object': doc }))
def warehouse_add_outgoing_movement(request, id, **kwargs): """Adds a new movement from the given warehouse. """ movement = Movement(origin_id=id, author=request.user) if request.method == 'POST': form = OutgoingMovementForm(request.POST, instance=movement) pform = ProductEntryForm(request.POST) if pform.is_valid() and form.is_valid(): pe = pform.save() movement.product_entry = pe form.save() messages.success(request, _("The movement was created successfully.")) return redirect_to(request, url=movement.get_absolute_url()) else: form = OutgoingMovementForm(instance=movement) pform = ProductEntryForm() return render_to_response( 'stock/warehouse_edit_movement.html', RequestContext(request, { 'form': form, 'pform': pform, 'object': movement }))
def bookmark_add(request, username, **kwargs): """Adds a new bookmark for the current user. """ user = get_object_or_404(User, username=username) bookmarks = user.get_profile().bookmarks bookmark = Bookmark(menu=bookmarks, sort_order=bookmarks.links.count()) if request.method == 'POST': form = BookmarkForm(request.POST, instance=bookmark) if form.is_valid(): bookmark.slug = slugify("%s_%s" % (bookmark.title, user.pk)) bookmark = form.save() messages.success(request, _("The bookmark was created successfully.")) return redirect_to(request, url=reverse('bookmark_list', args=[user.username])) else: url = clean_referer(request) if url == reverse('bookmark_list', args=[user.username]): url = "" bookmark.url = url form = BookmarkForm(instance=bookmark) return render_to_response( 'menus/bookmark_edit.html', RequestContext(request, { 'form': form, 'object': bookmark, 'object_user': user }))
def search(request, query_string="", page=0, paginate_by=10, **kwargs): """Displays the list of results for the current search query. """ if ('q' in request.GET) and request.GET['q'].strip(): query_string = request.GET['q'] return redirect_to( request, reverse('search_with_query', args=[query_string.replace(' ', '+')])) Result.objects.all().delete() if query_string: autodiscover() for model, fields in MODELS.items(): q = _get_query(query_string, [field.name for field in fields]) objects = model.objects.filter(q) for obj in objects: r = Result(title=obj, content_object=obj) r.save() else: messages.error(request, _("Please, specify a valid search query.")) return list_detail.object_list( request, queryset=Result.objects.all(), paginate_by=paginate_by, page=page, template_name="taxonomy/search.html", extra_context={'query': query_string.replace('+', ' ')}, **kwargs)
def editar_suplemento_dia(request, contrato_id, id=None): """Los suplementos por día""" name = "Suplementos por día" contrato = Contrato.objects.get(pk=contrato_id) form = SuplementoDiaForm( request.POST or None, instance=id and SuplementoDia.objects.get(id=id, contrato__id=contrato_id)) if request.method == 'POST': form.instance.contrato = contrato if form.is_valid(): condicion = form.save(commit=False) condicion.contrato = contrato condicion.save() return redirect_to(request, url=reverse('contrato-hotel', args=[ contrato.hotel.slug, ])) return direct_to_template(request, template='motor/condiciones_contrato.html', extra_context={ 'form': form, 'contrato': contrato, 'name': name })
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))
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))
def employee_add(request, **kwargs): """Adds a new employee. """ job = Job() employee = Employee() if request.method == 'POST': jform = JobForm(request.POST, instance=job) form = EmployeeForm(request.POST, instance=employee) if jform.is_valid(): jform.save() employee = job.employee form = EmployeeForm(request.POST, instance=employee) if form.is_valid(): form.save() messages.success(request, _("The employee was created successfully.")) return redirect_to(request, url=employee.get_absolute_url()) else: job.delete() jform = JobForm(instance=job) form = EmployeeForm(instance=employee) else: jform = JobForm(instance=job) form = EmployeeForm(instance=employee) return render_to_response('hr/employee_edit.html', RequestContext(request, {'form': form, 'jform': jform, 'object': employee}))
def editar_suplemento_regimen(request, hotel_id, id=None): """Los suplementos de regimen van por hotel""" name = "Suplementos de Régimen" hotel = Hotel.objects.get(pk=hotel_id) form = SuplementoRegimenForm( request.POST or None, instance=id and SuplementoRegimen.objects.get(id=id, hotel__id=hotel_id)) if request.method == 'POST': form.instance.hotel = hotel if form.is_valid(): condicion = form.save(commit=False) condicion.hotel = hotel condicion.save() return redirect_to(request, url=reverse('contrato-hotel', args=[ hotel.slug, ])) return direct_to_template(request, template='motor/condiciones_contrato.html', extra_context={ 'form': form, 'name': name })
def editar_descuento_ninyos(request, contrato_id, id=None): """Descuento niños""" name = "Descuento Niños" contrato = Contrato.objects.get(pk=contrato_id) form = DescuentoNinyosForm( request.POST or None, instance=id and DescuentoNin.objects.get(id=id, contrato__id=contrato_id)) if request.method == 'POST': form.instance.contrato = contrato if form.is_valid(): condicion = form.save(commit=False) condicion.contrato = contrato condicion.save() return redirect_to(request, url=reverse('contrato-hotel', args=[ contrato.hotel.slug, ])) return direct_to_template(request, template='motor/condiciones_contrato.html', extra_context={ 'form': form, 'contrato': contrato, 'name': name })
def editar_condiciones(request, contrato_id, id=None): """Modificación y alta de la cabecera de un contrato""" name = "Condiciones del Contrato" contrato = Contrato.objects.get(pk=contrato_id) form = CondicionesContratoForm( request.POST or None, instance=id and CondicionesContrato.objects.get(id=id, contrato__id=contrato_id)) if request.method == 'POST': form.instance.contrato = contrato if form.is_valid(): condicion = form.save(commit=False) condicion.contrato = contrato condicion.save() return redirect_to(request, url=reverse('contrato-hotel', args=[ contrato.hotel.slug, ])) return direct_to_template(request, template='motor/condiciones_contrato.html', extra_context={ 'form': form, 'contrato': contrato, 'name': name })
def editar_restriccion_blackout(request, contrato_id, id=None): """Restriccion de blackout""" name = "Restricción de Blackout" contrato = Contrato.objects.get(pk=contrato_id) form = RestriccionBlackoutForm( request.POST or None, instance=id and RestriccionBlackout.objects.get(id=id, contrato__id=contrato_id)) if request.method == 'POST': form.instance.contrato = contrato if form.is_valid(): condicion = form.save(commit=False) condicion.contrato = contrato condicion.save() return redirect_to(request, url=reverse('contrato-hotel', args=[ contrato.hotel.slug, ])) return direct_to_template(request, template='motor/condiciones_contrato.html', extra_context={ 'form': form, 'contrato': contrato, 'name': name })
def salesinvoice_add(request, **kwargs): """Adds a new sales invoice. """ salesinvoice = SalesInvoice() doc = Document(author=request.user, content_object=salesinvoice) if request.method == 'POST': dform = DocumentForm(request.POST, instance=doc) form = SalesInvoiceForm(request.POST, instance=salesinvoice) formset = ProductEntryFormset(request.POST) if form.is_valid() and dform.is_valid() and formset.is_valid(): form.save() doc.content_object = salesinvoice dform.save() for e in formset.save(): salesinvoice.entries.add(e) messages.success(request, _("The sales invoice was created successfully.")) return redirect_to(request, url=doc.get_absolute_url()) else: dform = DocumentForm(instance=doc) form = SalesInvoiceForm(instance=salesinvoice) formset = ProductEntryFormset() return render_to_response( 'sales/salesinvoice_edit.html', RequestContext(request, { 'form': form, 'dform': dform, 'formset': formset, 'object': doc }))
def event_add(request, year=None, month=None, day=None, **kwargs): """Adds a new event. """ start = datetime.datetime.now() if year and month and day: start = datetime.datetime.combine( datetime.date(int(year), int(month), int(day)), start.time()) event = Event(author=request.user, start=start) if request.method == 'POST': form = EventForm(request.POST, instance=event) if form.is_valid(): form.save() event.calendars.add(request.user.get_profile().calendar) messages.success(request, _("The event was created successfully.")) return redirect_to(request, url=event.get_absolute_url()) else: form = EventForm(instance=event) return render_to_response( 'calendar/event_edit.html', RequestContext(request, { 'form': form, 'object': event }))
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))
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)
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)
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')
def amazon_process(request): try: tid = request.GET.get('transactionId') pid = request.GET.get('referenceId') amt = request.GET.get('transactionAmount') name = request.GET.get('buyerName') purchase = Purchase.objects.get(pk=pid) if amt != "USD %s" % purchase.amount_due: return direct_to_template(request, 'texas/error.html', {'message': "Payment amount does not match!"}) payment = Payment(purchase=purchase, amount=purchase.get_price(), reference=tid) payment.purchaser_name = name payment.save() if payment.amount >= purchase.amount_due: purchase.status = 'P' purchase.save() for ticket in purchase.ticket_set.all(): ticket.assigned_name = payment.purchaser_name ticket.set_code() ticket.set_number() do_send_purchase_confirmation(purchase) return redirect_to(request, "/buy/purchases/receipt/%i/" % purchase.id) return direct_to_template(request, 'texas/error.html', {'message': "Payment error!"}) except: return direct_to_template(request, 'texas/error.html', {'message': "Amazon payment error! Please contact [email protected] and make a payment via PayPal. We will refund your Amazon payment promptly if notified."})
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))
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)
def timesheet_edit(request, id, **kwargs): """Edits a timesheet. """ doc = Document.objects.get_for_content(Timesheet).get(object_id=id) timesheet = doc.content_object if request.method == 'POST': dform = DocumentForm(request.POST, instance=doc) form = TimesheetForm(request.POST, instance=timesheet) formset = TimesheetEntryFormset(request.POST, instance=timesheet) if form.is_valid() and dform.is_valid() and formset.is_valid(): form.save() dform.save() formset.save() messages.success(request, _("The timesheet was updated successfully.")) return redirect_to(request, url=doc.get_absolute_url()) else: dform = DocumentForm(instance=doc) form = TimesheetForm(instance=timesheet) formset = TimesheetEntryFormset(instance=timesheet) return render_to_response( 'hr/timesheet_edit.html', RequestContext(request, { 'form': form, 'dform': dform, 'formset': formset, 'object': doc }))
def render_to_pdf(request, template_name, context, filename="report.pdf", encoding='utf-8', **kwargs): """Renders a pdf response using given *request*, *template_name* and *context*. """ if not isinstance(context, Context): context = RequestContext(request, context) content = render_to_string(template_name, context) src = StringIO(content.encode(encoding)) out = StringIO() result = pisa.CreatePDF(src, out, link_callback=fetch_resources, encoding="UTF-8") if not result.err: response = HttpResponse(out.getvalue(), mimetype='application/pdf') if filename is not None: response[ 'Content-Disposition'] = 'attachment; filename=%s' % filename return response messages.error(request, _("An error has occurred during the PDF conversion")) return redirect_to(request, url=clean_referer(request))
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
def revert_to_revision(request, title, group_slug=None, bridge=None, article_qs=ALL_ARTICLES, extra_context=None, is_member=None, is_private=None, *args, **kw): if request.method == 'POST': revision = int(request.POST['revision']) article_args = {'title': title} group = None if group_slug is not None: try: group = bridge.get_group(group_slug) except ObjectDoesNotExist: raise Http404 # @@@ use bridge instead article_args.update({ 'content_type': get_ct(group), 'object_id': group.id }) allow_read = has_read_perm(request.user, group, is_member, is_private) allow_write = has_write_perm(request.user, group, is_member) else: group = None allow_read = allow_write = True article_args.update({'object_id': None}) if not (allow_read or allow_write): return HttpResponseForbidden() article = get_object_or_404(article_qs, **article_args) if request.user.is_authenticated(): article.revert_to(revision, get_real_ip(request), request.user) else: article.revert_to(revision, get_real_ip(request)) if request.user.is_authenticated(): request.user.message_set.create( message=u"The article was reverted successfully.") url = get_url('wiki_article_history', group, kw={ 'title': title, }, bridge=bridge) return redirect_to(request, url) return HttpResponseNotAllowed(['POST'])
def address_add(request, owner, post_save_redirect, template_name, owner_field='addresses', **kwargs): """Adds a new address to the given owner. """ if request.method == 'POST': form = AddressForm(request.POST) if form.is_valid(): instance = form.save() rel, value = _get_field_and_value(owner, owner_field) if isinstance(rel, models.ForeignKey): setattr(owner, owner_field, instance) elif isinstance(rel, models.ManyToManyField): value.add(instance) owner.save() if owner.pk: messages.success( request, _("Address added to %(owner)s") % {'owner': owner}) return redirect_to(request, url=post_save_redirect) else: form = AddressForm() context = {'owner': owner, 'form': form} if 'extra_context' in kwargs: context.update(kwargs['extra_context']) return render_to_response(template_name, RequestContext(request, context))
def ticket_edit(request, project, code, **kwargs): """Edits a ticket. """ project = get_object_or_404(Project, code=project) ticket = get_object_or_404(Ticket, project=project, code=code) if request.method == 'POST': form = TicketForm(request.POST, instance=ticket) if form.is_valid(): ticket = form.save() messages.success(request, _("The ticket was updated successfully.")) return redirect_to(request, url=ticket.get_absolute_url()) else: form = TicketForm(instance=ticket) if not request.user.has_perm("projects.change_milestone"): del form.fields['milestone'] if not request.user.has_perm("projects.change_assignee"): del form.fields['assignee'] return render_to_response( 'projects/ticket_edit.html', RequestContext(request, { 'form': form, 'object': ticket }))
def bookmark_edit(request, username, slug, **kwargs): """Edits an existing bookmark for the current user. """ user = get_object_or_404(User, username=username) bookmarks = user.get_profile().bookmarks bookmark = get_object_or_404(Bookmark, menu=bookmarks, slug=slug) if request.method == 'POST': form = BookmarkForm(request.POST, instance=bookmark) if form.is_valid(): bookmark = form.save() messages.success(request, _("The bookmark was updated successfully.")) return redirect_to(request, url=reverse('bookmark_list', args=[user.username])) else: form = BookmarkForm(instance=bookmark) return render_to_response( 'menus/bookmark_edit.html', RequestContext(request, { 'form': form, 'object': bookmark, 'object_user': user }))
def ticket_add(request, project, milestone=None, **kwargs): """Adds a new ticket. """ project = get_object_or_404(Project, code=project) ticket = Ticket(project=project, author=request.user) initial = {} if milestone is not None: milestone = get_object_or_404(Milestone, code=milestone, project=project) initial['milestone'] = milestone if request.method == 'POST': form = TicketForm(request.POST, instance=ticket, initial=initial) if form.is_valid(): ticket = form.save() messages.success(request, _("Your ticket has been registered.")) return redirect_to(request, url=ticket.get_absolute_url()) else: form = TicketForm(instance=ticket, initial=initial) if not request.user.has_perm("projects.change_milestone"): del form.fields['milestone'] if not request.user.has_perm("projects.change_assignee"): del form.fields['assignee'] return render_to_response( 'projects/ticket_edit.html', RequestContext(request, { 'form': form, 'object': ticket }))
def salesinvoice_edit(request, id, **kwargs): """Edits a sales invoice. """ doc = get_object_or_404(Document.objects.get_for_content(SalesInvoice), object_id=id) salesinvoice = doc.content_object if request.method == 'POST': dform = DocumentForm(request.POST, instance=doc) form = SalesInvoiceForm(request.POST, instance=salesinvoice) formset = ProductEntryFormset(request.POST, queryset=salesinvoice.entries.all()) if form.is_valid() and dform.is_valid() and formset.is_valid(): form.save() dform.save() for e in formset.save(): salesinvoice.entries.add(e) messages.success(request, _("The sales invoice was updated successfully.")) return redirect_to(request, url=doc.get_absolute_url()) else: dform = DocumentForm(instance=doc) form = SalesInvoiceForm(instance=salesinvoice) formset = ProductEntryFormset(queryset=salesinvoice.entries.all()) return render_to_response( 'sales/salesinvoice_edit.html', RequestContext(request, { 'form': form, 'dform': dform, 'formset': formset, 'object': doc }))
def page_edit(request, slug=None, **kwargs): """Edits or creates a page. """ try: page = WikiPage.objects.get(slug=slug) except WikiPage.DoesNotExist: page = WikiPage(slug=slug, author=request.user, language=request.user.get_profile().language) if request.method == 'POST': form = WikiPageForm(request.POST, instance=page) if form.is_valid(): is_new = (not page.pk) form.save() if is_new: messages.success(request, _("The page was created successfully.")) else: messages.success(request, _("The page was updated successfully.")) return redirect_to(request, url=page.get_absolute_url()) else: form = WikiPageForm(instance=page) return render_to_response( 'knowledge/wikipage_edit.html', RequestContext(request, { 'form': form, 'object': page }))
def expensevoucher_edit(request, id, **kwargs): """Edits a expensevoucher. """ doc = Document.objects.get_for_content(ExpenseVoucher).get(object_id=id) expensevoucher = doc.content_object if request.method == 'POST': dform = DocumentForm(request.POST, instance=doc) form = ExpenseVoucherForm(request.POST, instance=expensevoucher) formset = ExpenseEntryFormset(request.POST, instance=expensevoucher) if form.is_valid() and dform.is_valid() and formset.is_valid(): form.save() dform.save() formset.save() messages.success( request, _("The expense voucher was updated successfully.")) return redirect_to(request, url=doc.get_absolute_url()) else: dform = DocumentForm(instance=doc) form = ExpenseVoucherForm(instance=expensevoucher) formset = ExpenseEntryFormset(instance=expensevoucher) return render_to_response( 'hr/expensevoucher_edit.html', RequestContext(request, { 'form': form, 'dform': dform, 'formset': formset, 'object': doc }))
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')
def user_edit(request, username, **kwargs): """Edits a user's profile. """ user = get_object_or_404(User, username=username) if request.method == 'POST': form = UserEditForm(request.POST, instance=user) _adapt_form(request, form) pform = UserProfileForm(request.POST, instance=user.get_profile()) if form.is_valid() and pform.is_valid(): user = form.save() profile = pform.save() if request.user == user: set_language(request, profile.language) messages.success(request, _("The user was updated successfully.")) return redirect_to(request, url=user.get_absolute_url()) else: form = UserEditForm(instance=user) _adapt_form(request, form) pform = UserProfileForm(instance=user.get_profile()) return render_to_response( 'auth/user_edit.html', RequestContext(request, { 'form': form, 'pform': pform, 'object': user }))
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))
def message_send(request, messageid): message = get_object_or_404(Msg, pk=messageid) # NOW SEND THE REQUEST TO GOOGLE SERVERS # first we need an https connection that ignores the certificate (for now) httpsconnection = httplib.HTTPSConnection("android.apis.google.com", 443) # we need the following params set per http://code.google.com/android/c2dm/index.html#push params = urllib.urlencode({ 'registration_id': message.device.registrationid, 'collapse_key': "message" + str(message.id), 'data.message': str(message.id), 'delay_when_idle': 'TRUE', }) # need the following headers set per http://code.google.com/android/c2dm/index.html#push headers = { "Content-Type": "application/x-www-form-urlencoded", "Content-Length": len(params), "Authorization": "GoogleLogin auth=" + GOOGLE_TOKEN # TOKEN set manually in authentication.py } httpsconnection.request("POST", "/c2dm/send", params, headers) # assuming success, let's return the user to the device list for now return redirect_to(request, "/", False)