def login(request): # authenticated user does not need to log in if request.user.is_authenticated(): return redirect(reverse("audio:index")) if request.method == "GET": context = {} if "next" in request.GET: context["next"] = "?next=" + request.GET["next"] return render(request, "audio/login.html", context) elif request.method == "POST": user = authenticate( username=request.POST["username"], password=request.POST["password"] ) if user is not None: auth_login(request, user) if "next" in request.GET: return redirect(request.GET["next"]) else: return redirect(reverse("audio:index")) else: return redirect(reverse("login")) else: return HttpResponse("405")
def login(request): if request.method == "POST": form = LoginForm(request.POST) if form.is_valid(): user = authenticate(username=form.cleaned_data["login"], password=form.cleaned_data["password"]) if user is not None: auth_login(request, user) if "next" in request.GET: redir = redirect(request.GET["next"]) else: redir = redirect(reverse("feed")) redir.set_cookie("who", user.username, max_age=24 * 60 * 60) return redir else: return render(request, "profiles/login.html", { "form": form, "errors": ["User is not found."] }) else: return render(request, "profiles/login.html", {"form": form}) else: form = LoginForm() if "who" in request.COOKIES: # form = LoginForm(initial={"username": request.COOKIES["who"]}) # form.fields["login"].initial = request.COOKIES["who"] form.fields["login"].initial = request.COOKIES["who"] return render(request, "profiles/login.html", {"form": form})
def member_signin(request): if request.method == "GET": return my_render( request, 'member/a_signin.html', ) else: user_name = request.POST.get('username') member = member_models.Member.get_member_by_telephone(user_name) password = request.POST.get('password') user = authenticate(user_name=user_name, password=password) if user and user.is_admin: login(request, user) return redirect('/myadmin/index/') elif member: if member.check_password(password): login(request, member) return redirect('/myadmin/index/') else: return my_render(request, 'member/a_signin.html', form_error='用户名或者密码错误', form_data=request.POST) else: return my_render(request, 'member/a_signin.html', form_error='用户名或者密码错误', form_data=request.POST)
def portal_theme(request, portal): if request.method == 'POST': form = CssForm(request.POST) if form.is_valid(): if form.cleaned_data['css']: portal.custom_css = form.cleaned_data['css'] portal.hide_header_title = form.cleaned_data[ 'hide_header_title'] portal.left_sidebar = form.cleaned_data['left_sidebar'] portal.save() save_success_message(request) if request.POST.has_key('save-continue'): return redirect( reverse('portals.backend.views.portal_theme', args=[portal.address])) else: return redirect( reverse('portals.backend.views.portal_main', args=[portal.address])) else: form = CssForm({ 'css': portal.custom_css, 'left_sidebar': portal.left_sidebar, 'hide_header_title': portal.hide_header_title, }) if portal.custom_css else CssForm() return render_to_response( 'b/common_form.html', { 'title': _('Set Custom CSS'), 'form': form, 'disable_tiny_mce': True, 'enable_code_mirror': True, }, portal_request_context(request, portal))
def preview(request, mail): mails = _get_mail_list(request) mail = Mail.objects.get(pk=mail) if not mail.approved: messages.error( request, "You can't preview an email that's not been" " approved. Please check your email for a " "link to approve this email.") return redirect(reverse('mail', kwargs={'mail': mail.id})) if request.method == "POST": if request.POST.has_key('post'): mail.previewed = True mail.save() messages.success(request, ("Your email has been posted!")) if not request.user.has_usable_password(): messages.warning(request, ("Now, please create a " "password so you can log in " "and check your messages in " "the future.")) return redirect( reverse('login_or_register_form', kwargs={'mail': mail.pk})) else: return redirect(reverse('mail', kwargs={'mail': mail.id})) elif request.POST.has_key('delete'): messages.info(request, '"%s" deleted' \ % mail.subject) mail.delete() return redirect(reverse('write')) return locals()
def page_edit(request, subpath): site = request.site if request.method == "POST": if 'file' in request.POST: file = request.FILES['file'] contents = file.read() else: contents = request.POST['contents'] msg = request.POST.get("comment") or None site.write_page(subpath, contents, msg=msg, username=request.user.username) return redirect(site.page_view_url(subpath)) try: contents = site.get_page(subpath) except sven.NoSuchResource: # this is fine, we can edit a new file contents = "" except sven.NotAFile: # this is not fine, we can't edit a directory # @@todo: maybe check for user-supplied index page? return redirect(site.directory_index_url(subpath)) # @@todo: dispatch to different editors based on mimetype raw_edit = ("/%s" % subpath.lstrip('/')).startswith(site.raw_files_path) return dict(site=site, raw_edit=raw_edit, contents=contents, path=subpath, form_url=site.page_edit_url(subpath))
def portal_theme(request, portal): if request.method == 'POST': form = CssForm(request.POST) if form.is_valid(): if form.cleaned_data['css']: portal.custom_css = form.cleaned_data['css'] portal.hide_header_title = form.cleaned_data['hide_header_title'] portal.left_sidebar = form.cleaned_data['left_sidebar'] portal.save() save_success_message(request) if request.POST.has_key('save-continue'): return redirect(reverse('portals.backend.views.portal_theme', args=[portal.address])) else: return redirect(reverse('portals.backend.views.portal_main', args=[portal.address])) else: form = CssForm({ 'css': portal.custom_css, 'left_sidebar': portal.left_sidebar, 'hide_header_title': portal.hide_header_title, }) if portal.custom_css else CssForm() return render_to_response('b/common_form.html', { 'title': _('Set Custom CSS'), 'form': form, 'disable_tiny_mce': True, 'enable_code_mirror': True, }, portal_request_context(request, portal))
def decline_league_invite(request, league="", key=""): league = League.objects.get(slug=league) profile = RegistrationProfile.objects.get_user(key, only_activated=False) if profile: newuser = False if not profile.activated: profile = RegistrationProfile.objects.activate_user(key) newuser = True try: logout(request) user = profile.user joinstate = LeagueJoinStates.objects.filter(league=league, user=user, state=STATE_INVITED)\ .get() joinstate.decline(originator=user) if newuser: return redirect(reverse('home')) else: return redirect(reverse('login_form')) except LeagueJoinStates.DoesNotExist: error = "No invite for user %s to league %s" % (user.email, league.name) else: error = "No profile for key %s" % (key) return locals()
def page_create(request, subpath): site = request.site if request.method == "POST": path = request.POST['path'] # @@todo: don't slugify for raw wikis? dunno from django.template.defaultfilters import slugify path = '/'.join(slugify(i) for i in path.split('/')) path = subpath.rstrip('/') + '/' + path.strip('/') # @@todo: do something else if the page already exists, i guess? return redirect(site.page_edit_url(path.strip('/'))) try: subpaths = site.get_contents(subpath) except sven.NotADirectory: return redirect(site.page_view_url(subpath)) except sven.NoSuchResource: return redirect(site.page_edit_url(subpath)) # @@todo: maybe check for user-supplied index page? return dict(site=site, path=subpath, subpaths=subpaths, form_url=site.page_create_url(subpath))
def logged_in(request): if request.user.is_superuser: logout(request) return redirect(reverse('home')) fb = _get_facebook_cookie(request.COOKIES) if request.user.is_authenticated(): if request.user.has_prediction(): current = getCurrentTable() leagues = request.user.leagues_by_state(STATE_ACCEPTED) my_leagues = leagues.filter(owner=request.user) now = datetime.datetime.now() open_or_entered = Q(start_date__lt=now, close_date__gt=now) | \ Q(start_date__lt=now, competition_date__gt=now, prediction__user=request.user) open_comps = Competition.objects\ .filter(start_date__lt=now, competition_date__gt=now)\ .distinct()\ .order_by('competition_date') open_comps = _decorate_with_predictions(open_comps, request.user) closed_comps = Competition.objects\ .filter(competition_date__lt=now)\ .exclude(pk=settings.FIRST_COMPETITION_ID)\ .all() closed_comps = _decorate_with_predictions(closed_comps, request.user) future_comps = Competition.objects\ .filter(competition_date__gt=now, start_date__gt=now).all() open_and_closed_comps = list(chain(open_comps, closed_comps)) return locals() else: return redirect(reverse('home'))
def social_register(self,request,typesoc,profile): data = request.REQUEST whitespace = ' '; r = None; facebook = twitter = google = '' if 'google' in typesoc: username = profile['name'].lower() google = profile['google_token'] elif 'twitter' in typesoc: username = profile['screen_name'] twitter = '%s;%s' % (profile['key'],profile['secret']) elif 'facebook' in typesoc: username = profile['link'].split('/')[-1:][0] facebook = profile['facebook_token'] # Ja registrado, fazer login social if len(list(User.objects.filter(username=username))) > 0: request.session['user'] = username r = redirect('/') # Nao registrado, gravando chaves sociais e perfil e redirecionando para tutorial else: u = User.objects.create_user(username,password=User.objects.make_random_password()) p = Profile(user=u,facebook_token=facebook,twitter_token=twitter,google_token=google) p.save() r = redirect('tutorial?social=%s'%data['social']) r.set_cookie('username',username) r.set_cookie('permissions','super') return r
def login_via_facebook(request): user = signup_via_facebook(request) if user: return redirect(reverse('logged_in')) else: messages.error(request, "We don't have a record for that account") return redirect(reverse('home'))
def news_create_or_edit(request, portal, news=None): edit = True if news else False if request.method == 'POST': form = NewsForm(portal, request.POST, instance=news) if news else NewsForm(portal, request.POST) if form.is_valid(): news = form.save(commit=False) news.portal = portal news.save() form.save_m2m() news.save_writer(request.user) save_success_message(request) if request.POST.has_key('save-continue'): return redirect(reverse('portals.backend.views.news_edit', args=[portal.address, news.id])) else: if edit: EditLock.unset(request.user, news.id, 'NEWS') return redirect(reverse('portals.backend.views.news_list', args=[portal.address])) else: form = NewsForm(portal, instance=news) if news else NewsForm(portal) if edit: EditLock.set(request.user, news.id, 'NEWS') return render_to_response('b/common_form.html', { 'title': _('Edit News') if edit else _('Create News'), 'form': form, 'edit': edit, 'delete_url': reverse('portals.backend.views.news_delete', args=[portal.address, news.id]) if edit else None, 'view_url': reverse('portals.frontend.views.news_item', args=[portal.address, news.id]) if edit else None, }, portal_request_context(request, portal))
def preview(request, mail): mails = _get_mail_list(request) mail = Mail.objects.get(pk=mail) if not mail.approved: messages.error(request, "You can't preview an email that's not been" " approved. Please check your email for a " "link to approve this email.") return redirect(reverse('mail', kwargs={'mail':mail.id})) if request.method == "POST": if request.POST.has_key('post'): mail.previewed = True mail.save() messages.success(request, ("Your email has been posted!")) if not request.user.has_usable_password(): messages.warning(request, ("Now, please create a " "password so you can log in " "and check your messages in " "the future.")) return redirect(reverse('login_or_register_form', kwargs={'mail': mail.pk})) else: return redirect(reverse('mail', kwargs={'mail':mail.id})) elif request.POST.has_key('delete'): messages.info(request, '"%s" deleted' \ % mail.subject) mail.delete() return redirect(reverse('write')) return locals()
def view_mail_thread(request, mail): mail = Mail.objects.get(pk=mail) mails = _get_mail_list(request) start = mail.start_of_thread() if not request.user.is_anonymous() \ and request.method == "POST": form = MailForm(request, request.POST, request.FILES) if form.is_valid(): mail = form.save(in_reply_to=start.end_of_thread()) return redirect(reverse('preview', kwargs={'mail': mail.pk})) else: if request.user.is_anonymous(): form = MailForm(request) else: form = MailForm(request, initial={'mfrom':request.user.email, 'mto':start.mto.email, 'subject':'Re: %s' % start.subject}) if start == mail: return locals() else: return redirect(reverse('mail', kwargs={'mail':start.id})\ + "#mail-%d" % mail.id)
def event_create_or_edit(request, portal, event=None): edit = True if event else False if request.method == 'POST': form = EventForm(portal, request.POST, instance=event) if event else EventForm(portal, request.POST) if form.is_valid(): event = form.save(commit=False) event.portal = portal if event.begin < event.end: event.save() form.save_m2m() event.save_writer(request.user) save_success_message(request) if request.POST.has_key('save-continue'): return redirect(reverse('portals.backend.views.event_edit', args=[portal.address, event.id])) else: if edit: EditLock.unset(request.user, event.id, 'EVENT') return redirect(reverse('portals.backend.views.event_list', args=[portal.address])) else: form.errors['begin'] = [_('The beginning time must preceed the ending time.')] else: form = EventForm(portal, instance=event) if event else EventForm(portal) if edit: EditLock.set(request.user, event.id, 'EVENT') return render_to_response('b/common_form.html', { 'title': _('Edit Event') if edit else _('Create Event'), 'form': form, 'edit': edit, 'delete_url': reverse('portals.backend.views.event_delete', args=[portal.address, event.id]) if edit and event.id else None, 'view_url': reverse('portals.frontend.views.event_item', args=[portal.address, event.id]) if edit and event.id else None, }, portal_request_context(request, portal))
def podcast_create_or_edit(request, portal, podcast=None): edit = True if podcast else False if request.method == 'POST': form = PodcastForm(portal, request.POST, instance=podcast) if podcast else PodcastForm(portal, request.POST) if form.is_valid(): podcast = form.save(commit=False) podcast.portal = portal podcast.save() form.save_m2m() podcast.save_writer(request.user) save_success_message(request) if request.POST.has_key('save-continue'): return redirect(reverse('portals.backend.views.podcast_edit', args=[portal.address, podcast.id])) else: if edit: EditLock.unset(request.user, podcast.id, 'PODCAST') return redirect(reverse('portals.backend.views.podcast_list', args=[portal.address])) else: form = PodcastForm(portal, instance=podcast) if podcast else PodcastForm(portal) if edit: EditLock.set(request.user, podcast.id, 'PODCAST') return render_to_response('b/common_form.html', { 'title': _('Edit Podcast') if edit else _('Create Podcast'), 'form': form, 'disable_tiny_mce': True, 'edit': edit, 'delete_url': reverse('portals.backend.views.podcast_delete', args=[portal.address, podcast.id]) if edit else None, 'view_url': reverse('portals.frontend.views.podcast_item', args=[portal.address, podcast.id]) if edit else None, }, portal_request_context(request, portal))
def login(request): if request.method == "POST": form = LoginForm(request.POST) if form.is_valid(): user = authenticate( username=form.cleaned_data["login"], password=form.cleaned_data["password"] ) if user is not None: auth_login(request, user) if "next" in request.GET: redir = redirect(request.GET["next"]) else: redir = redirect(reverse("feed")) redir.set_cookie("who", user.username, max_age=24 * 60 * 60) return redir else: return render(request, "profiles/login.html", {"form": form, "errors": ["User is not found."]}) else: return render(request, "profiles/login.html", {"form": form}) else: form = LoginForm() if "who" in request.COOKIES: # form = LoginForm(initial={"username": request.COOKIES["who"]}) # form.fields["login"].initial = request.COOKIES["who"] form.fields["login"].initial = request.COOKIES["who"] return render(request, "profiles/login.html", {"form": form})
def social_register(self, request, typesoc, profile): data = request.REQUEST whitespace = ' ' r = None facebook = twitter = google = '' if 'google' in typesoc: username = profile['name'].lower() google = profile['google_token'] elif 'twitter' in typesoc: username = profile['screen_name'] twitter = '%s;%s' % (profile['key'], profile['secret']) elif 'facebook' in typesoc: username = profile['link'].split('/')[-1:][0] facebook = profile['facebook_token'] # Ja registrado, fazer login social if len(list(User.objects.filter(username=username))) > 0: request.session['user'] = username r = redirect('/') # Nao registrado, gravando chaves sociais e perfil e redirecionando para tutorial else: u = User.objects.create_user( username, password=User.objects.make_random_password()) p = Profile(user=u, facebook_token=facebook, twitter_token=twitter, google_token=google) p.save() r = redirect('tutorial?social=%s' % data['social']) r.set_cookie('username', username) r.set_cookie('permissions', 'super') return r
def view_mail_thread(request, mail): mail = Mail.objects.get(pk=mail) mails = _get_mail_list(request) start = mail.start_of_thread() if not request.user.is_anonymous() \ and request.method == "POST": form = MailForm(request, request.POST, request.FILES) if form.is_valid(): mail = form.save(in_reply_to=start.end_of_thread()) return redirect(reverse('preview', kwargs={'mail': mail.pk})) else: if request.user.is_anonymous(): form = MailForm(request) else: form = MailForm(request, initial={ 'mfrom': request.user.email, 'mto': start.mto.email, 'subject': 'Re: %s' % start.subject }) if start == mail: return locals() else: return redirect(reverse('mail', kwargs={'mail':start.id})\ + "#mail-%d" % mail.id)
def main(request): if request.user.is_authenticated(): if request.COOKIES.has_key("page"): return redirect(reverse(request.COOKIES["page"])) else: return redirect(reverse("audio:index")) else: return redirect(reverse("login"))
def portal_home(request, portal): if portal.homepage_event: return redirect(domain_reverse(portal, 'portals.frontend.views.event_item', args=[portal.address, portal.homepage_event.id])) elif portal.homepage_news: return redirect(domain_reverse(portal, 'portals.frontend.views.news_item', args=[portal.address, portal.homepage_news.id])) elif portal.homepage_page: return redirect(domain_reverse(portal, 'portals.frontend.views.page_item', args=[portal.address, page_sid(portal.homepage_page)])) else: return render_to_response('f/base2.html', { }, portal_request_context(request, portal))
def contributor_create_confirm(request, portal): if request.method == 'POST': form = ContributorConfirmationForm(request.POST) if form.is_valid(): user = get_user(form.cleaned_data['username']) if portal.valid_contributor(user, request.user): portal.contributors.add(user) portal.save() save_success_message(request) return redirect(reverse('portals.backend.views.contributor_list', args=[portal.address])) else: return redirect(reverse('portals.backend.views.contributor_create', args=[portal.address]))
def page_index(request, subpath): site = request.site try: subpaths = site.get_contents(subpath) except sven.NotADirectory: return redirect(site.page_view_url(subpath)) except sven.NoSuchResource: return redirect(site.page_edit_url(subpath)) # @@todo: maybe check for user-supplied index page? return dict(site=site, path=subpath, subpaths=subpaths)
def deploy_to_github_initial(request): site = request.site import subprocess import os import tempfile import shutil curdir = os.getcwd() checkout_path = tempfile.mkdtemp() os.chdir(checkout_path) domain = "github-%s" % request.user.username url = site.github.push_url(domain) subprocess.call(["git", "init"]) subprocess.call(["git", "remote", "add", "github", url]) gitignore = open(".gitignore", 'w') gitignore.write(".bzr") gitignore.close() subprocess.call(["git", "add", ".gitignore"]) subprocess.call(["git", "commit", "-m", "initializing site"]) subprocess.call(["git", "branch", "gh-pages"]) subprocess.call(["git", "checkout", "gh-pages"]) import tempfile with tempfile.TemporaryFile() as capture: ret = subprocess.call(["git", "push", "github", "gh-pages"], stdout=capture, stderr=subprocess.STDOUT) if ret != 0: capture.seek(0) _captured = capture.read() if ("Permission denied" in _captured or "Permission to %s.git denied" % site.github.repo() in _captured or "Could not resolve hostname" in _captured): # @@todo: this last one belongs elsewhere os.chdir(curdir) shutil.rmtree(checkout_path) messages.error(request, "missingsshkey") # @@todo: reverse urlconf return redirect("/.home/account/") os.chdir(curdir) shutil.rmtree(checkout_path) return redirect(site.deploy_dashboard_url())
def latest_change(request, subpath): site = request.site latest_change = site.latest_change(subpath) if latest_change is None: # TODO: dunno where to send them return redirect(site.page_view_url(subpath)) new = latest_change['version'] old = int(new) - 1 return redirect(site.page_diff_url(subpath) + "?versions=%s,%s" % (old, new))
def remove(request, **kwargs): """ Remove a stock item """ try: controller = StockController() controller.remove(f_id=kwargs.get('stock_item_id')) except: return redirect('/stock/index/?msg=No matching stock item found') return redirect('/stock/index/?msg=Successfully Removed')
def remove(request, **kwargs): """ "Remove a facility """ try: controller = infrastructure.facility_cntrl.FacilityController() controller.remove(f_id=kwargs.get('facility_id')) except: return redirect('/infrastructure/index/?msg=No matching facility found') return redirect('/infrastructure/index/?msg=Successfully Removed')
def page_view(request, subpath): site = request.site try: contents = site.get_page(subpath) except sven.NotAFile: return redirect(site.directory_index_url(subpath)) except sven.NoSuchResource: return redirect(site.page_edit_url(subpath)) # @@todo: raw view? binary files? mimetype = mimetypes.guess_type(subpath)[0] return dict(site=site, contents=contents, mimetype=mimetype, path=subpath)
def click_count(request, token): with transaction.atomic(): try: link = Link.objects.select_for_update().filter(token=token).first() except Link.DoesNotExist: pass else: to_url = link.to_url if to_url: link.count = F('count') + 1 link.save() return redirect(to_url) return redirect('/')
def home(request): context = {} if request.user.is_anonymous(): now = datetime.datetime.now() blog_date = blog_title = blog_content = None competition = Competition.objects\ .filter(start_date__lt=now, close_date__gt=now)\ .order_by('start_date') if competition: competition = competition[0] predictions = Prediction.objects\ .filter(competition=competition)\ .all()[:10] else: competition = None predictions = None context['blog_date'] = blog_date context['blog_title'] = blog_title context['blog_content'] = blog_content context['competition'] = competition context['predictions'] = predictions if request.method == "POST": # login attempt if request.POST.get('login', ''): username = request.POST['email'] password = request.POST['password'] user = authenticate(username=username, password=password) if user and not user.is_anonymous(): login(request, user) return redirect(reverse('home')) else: error = "Sorry, your details weren't recognised" context = {'error': error} return redirect(addToQueryString(reverse('home'), context)) else: # signup attempt form = PredictionForm(request.POST, request.FILES) if form.is_valid(): prediction = form.save() request.session['prediction'] = prediction request.session['competition'] = competition return redirect(reverse('signup')) else: context['form'] = form else: # default homepage context['form'] = PredictionForm() return render_with_context(request, 'home.html', context) else: return redirect(reverse('logged_in'))
def approve(request, mail, key): mails = _get_mail_list(request) mail = Mail.objects.get(pk=mail) if key != mail.get_secret_key(): messages.error(request, "That was an invalid key") elif mail.approved: messages.error(request, "You've already approved this message") else: mail.approved = True mail.save() user = authenticate(mail=mail) login(request, user) return redirect(reverse('preview', kwargs={'mail': mail.id})) return redirect(reverse('write'))
def click_count(request, token): with transaction.atomic(): #定义数据库的原子操作。在这个类里开启原子操作为关闭原子操作 try: link = Link.objects.select_for_update().filter(token=token).first( ) #查询结果集中的第一条。select_for_update应该是取出所有数据,然后filter过滤 except Link.DoesNotExist: pass else: to_url = link.to_url if to_url: link.count = F('count') + 1 #count字段值加1。使用F对象来访问字段 link.save() return redirect(to_url) #重定向到指定url。上面的count就是保存着这个url的访问次数 return redirect('/') #否则,重定向到首页
def authenticate_view(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) if user is not None: login(request, user) else: return redirect(reverse('recordstore:login', args=[])) next_url = request.POST.get('next', '') if len(next_url) == 0: return redirect(reverse('recordstore:home', args=[])) else: return redirect(next_url)
def oauth(request): if 'start' in request.GET: return redirect("https://github.com/login/oauth/authorize?scope=public_repo&client_id=%s" % settings.GITHUB_CLIENT_ID) elif request.method == "GET": code = request.GET['code'] params = {'client_id': settings.GITHUB_CLIENT_ID, 'client_secret': settings.GITHUB_SECRET, 'code': code} resp, content = POST("https://github.com/login/oauth/access_token", params, async=False, resp=True) for item in content.split("&"): if item.split("=")[0] == "access_token": token = item.split("=")[1] request.session['github_oauth_token'] = token return redirect("/")
def user_account(request): user = request.user profile = UserProfile.objects.get_or_create(user=user)[0] if request.method == "POST": redirect_to = request.POST.get('redirect_to', '.') if 'ssh_key' in request.POST: if not profile.register_github_key(): messages.error(request, "missingsshkey") return redirect(".") else: username = request.POST['github_username'] token = request.POST['github_api_token'] profile.set_options({'github_username': username, 'github_api_token': token}) profile.save() return redirect(redirect_to) message = None redirect_to = "." msgs = messages.get_messages(request) for msg in msgs: if 'failedauth' in msg.message: message = ("Github authorization failed. " "Please check your account's username " "and api token, and try again.") redirect_to = request.site.deploy_dashboard_url() if 'noprofile' in msg.message: message = ("To create Github Repos, I need your " "Github username and API token. " "Please provide those, and then try again.") redirect_to = request.site.deploy_dashboard_url() if 'missingsshkey' in msg.message: message = ("To work with your Github Repos, I need to " "register my SSH public key with your account. " "Make sure your username and API token are set, " "and then click \"Register SSH Key\". Thanks!") redirect_to = request.site.deploy_dashboard_url() return { 'profile': profile, 'message': message, 'redirect_to': redirect_to, 'path': '/', 'site': request.site, }
def category_create_or_edit(request, portal, form_title, FormClass, success_url, err_msg, category=None, lock_otype=None, help_text=None): edit = True if category else False if request.method == 'POST': form = FormClass(request.POST, instance=category) if edit else FormClass(request.POST) if form.is_valid(): category = form.save(commit=False) category.portal = portal success = False try: category.save() success = True except IntegrityError: pass if success: save_success_message(request) if edit: EditLock.unset(request.user, category.id, lock_otype) return redirect(success_url) else: form.errors['title'] = [err_msg] else: form = FormClass(instance=category) if edit else FormClass() if edit: EditLock.set(request.user, category.id, lock_otype) return render_to_response('b/common_form.html', { 'title': form_title, 'form': form, 'button_label': _('Save'), 'help_text': help_text, 'form_base': 'b/base2r.html', }, portal_request_context(request, portal))
def formdata(request): if request.method == "POST": f = Postform(request.POST) if f.is_valid(): month = request.POST.get("month", "") day = request.POST.get("day", "") tekiyou_kari = request.POST.get("tekiyou_kari", "") tekiyou_kasi = request.POST.get("tekiyou_kasi", "") tekiyou_com = request.POST.get("tekiyou_com", "") amount_kari = request.POST.get("amount_kari", "") amount_kasi = request.POST.get("amount_kasi", "") dd = open('.\\shiwake\\dicdic.py', 'w', encoding='utf-8') dd.write('ddd = {"month":' + month + ',\n"day":' + day + ',\n"tekiyou_kari":"' + tekiyou_kari + '",\n"tekiyou_kasi":"' + tekiyou_kasi + '",\n"tekiyou_com":"' + tekiyou_com + '",\n"amount_kari":' + amount_kari + ',\n"amount_kasi":' + amount_kasi + '}') dd.close() from . import app return redirect('result') else: f = Postform() return render(request, 'shiwake/shiwakeform.html', {'form1': f})
def audio_data_page(request, audio_id): if request.method == "GET": ad = AudioData.objects.filter(audio_id=audio_id) if ad.exists(): s = serializers.serialize("json", ad) data = json.loads(s) data = data[0]["fields"] f = AudioDataForm(initial=data) else: f = AudioDataForm() return render(request, "audio/audio_data_page.html", {"f": f}) elif request.method == "POST": f = AudioDataForm(request.POST) if f.is_valid(): result_ad = AudioData.objects.filter(audio_id=audio_id) if result_ad.exists(): ad = result_ad[0] else: ad = AudioData(audio_id=audio_id) ad.bitrate = f.cleaned_data["bitrate"] ad.year = f.cleaned_data["year"] ad.phone_of_author = f.cleaned_data["phone_of_author"] ad.description = f.cleaned_data["description"] ad.duration = f.cleaned_data["duration"] ad.save() return redirect(reverse("audio:audio_data_page", args=(audio_id,))) else: return render(request, "audio/audio_data_page.html", {"f": f}) else: return HttpResponse("405")
def contact_support(request): if request.method == 'POST': form = SupportForm(request.POST) if form.is_valid(): sys_info = get_sys_info() try: send_mail('[%s] %s' % (sys_info.site_title, form.cleaned_data['subject']), form.cleaned_data['message'], request.user.email, [sys_info.support_email], fail_silently=False) sent = True except: sent = False if sent: request.user.message_set.create(message=ugettext('The email has been sent.')) return redirect(reverse('portals.backend.views.portal_list')) else: request.user.message_set.create(message=ugettext('Cannot send the email. Please check the form balow.')) else: form = SupportForm() return render_to_response('b/common_form.html', { 'title': _('Contact Support Team'), 'form': form, 'disable_tiny_mce': True, 'button_label': _('Send'), }, system_request_context(request))
def competition(request, competition=None, email=None, userid=None): if email: user = CustomUser.objects.get(email=email) elif userid: user = CustomUser.objects.get(id=userid) email = user.email else: user = request.user if user.is_anonymous(): messages.error(request, "You must be logged in to view the competition") return redirect(reverse('home')) competition = Competition.objects.get(pk=competition) current = getCurrentTable() last = getPreviousTable(competition=competition) try: prediction = Prediction.objects\ .filter(competition=competition, user=user).get() predictions = prediction.in_context() entered = True except Prediction.DoesNotExist: prediction = Prediction.objects\ .filter(competition=competition) if prediction.count(): prediction = prediction[0] predictions = prediction.in_context() entered = False final = prediction.last_used_table max_goal_diff = current.max_goal_diff(last) return locals()
def contact_support(request): if request.method == 'POST': form = SupportForm(request.POST) if form.is_valid(): sys_info = get_sys_info() try: send_mail('[%s] %s' % (sys_info.site_title, form.cleaned_data['subject']), form.cleaned_data['message'], request.user.email, [sys_info.support_email], fail_silently=False) sent = True except: sent = False if sent: request.user.message_set.create( message=ugettext('The email has been sent.')) return redirect(reverse('portals.backend.views.portal_list')) else: request.user.message_set.create(message=ugettext( 'Cannot send the email. Please check the form balow.')) else: form = SupportForm() return render_to_response( 'b/common_form.html', { 'title': _('Contact Support Team'), 'form': form, 'disable_tiny_mce': True, 'button_label': _('Send'), }, system_request_context(request))
def email_all(request): if request.method == 'POST': form = SupportForm(request.POST) if form.is_valid(): sys_info = get_sys_info() dt = [] for user in User.objects.all(): dt.append(( form.cleaned_data['subject'], form.cleaned_data['message'], sys_info.support_email, [user.email], )) try: send_mass_mail(dt) set_message(request, ugettext('The email has been sent.')) except: set_message(request, ugettext('ERROR!! The email could not be sent.')) return redirect('/admin/tools/') else: form = SupportForm() return render_to_response( 'at_email_all.html', { 'form': form, 'app_label': _('Tools'), 'opts': { 'verbose_name_plural': _('Email') }, 'original': _('All'), }, RequestContext(request, {}))
def editor_brand(request): brand_id = request.GET.get('brand_id') if request.method == 'GET': item_obj = item_models.Brands.get_brand_by_id(brand_id) form_data = model_to_dict(item_obj) return my_render( request, 'item/a_add_brand.html', form_data=form_data, ) else: form = EditorBrandForm(request.POST) item_obj = item_models.Brands.get_brand_by_id(brand_id) if not form.is_valid(): return my_render( request, 'item/a_add_brand.html', form_errors=form.errors, ) form.update(brand_id) files = request.FILES if files: file_obj = files.get('brand_image') if not os.path.exists(settings.MEDIA_ROOT, ): os.makedirs(settings.MEDIA_ROOT, ) data = photo.save_upload_photo( file_obj, settings.MEDIA_ROOT, ) if data: item_obj.photo_id = data['photo_id'] item_obj.save() back_url = request.GET.get('back_url') return redirect(back_url)
def add_brand(request): if request.method == 'GET': return my_render( request, 'item/a_add_brand.html', ) else: form = AddBrandForm(request.POST) if not form.is_valid(): return my_render( request, 'item/a_add_brand.html', form_errors=form.errors, ) brand = form.save() files = request.FILES if files: file_obj = files.get('brand_image') if not os.path.exists(settings.MEDIA_ROOT, ): os.makedirs(settings.MEDIA_ROOT, ) data = photo.save_upload_photo( file_obj, settings.MEDIA_ROOT, ) if data: brand.photo = data['photo_id'] brand.save() return redirect('/myadmin/brand_manage/')
def add_item(request): specifications_type_dict = dict( item_models.Items.specifications_type_choices) brands_dict = item_models.Brands.get_brands_dict_for_all() categories_dict = item_models.Categories.get_categoreis_select_for_all() campaigns_dict = ad_models.Campaigns.get_campaigns_selecet_all() if request.method == 'GET': return my_render( request, 'item/a_add_item.html', specifications_type_dict=specifications_type_dict, brands_dict=brands_dict, categories_dict=categories_dict, campaigns_dict=campaigns_dict, ) else: form = AddItemForm(request.POST) if not form.is_valid(): return my_render( request, 'item/a_add_item.html', specifications_type_dict=specifications_type_dict, brands_dict=brands_dict, categories_dict=categories_dict, form_errors=form.errors, form_data=request.POST, campaigns_dict=campaigns_dict, ) form.save(request=request) return redirect('/myadmin/item_manage/')
def edit(request, **kwargs): """ Edit a facility """ controller = infrastructure.facility_cntrl.FacilityController() facility = controller.getFacility(kwargs.get('facility_id')) existing = True save_error_name = None if request.method == "POST": form = FacilityForm(request.POST, existing_flag=existing) if form.is_valid(): try: form.save(facility) return redirect('/infrastructure/index/?msg=Successfully updated') except: save_error_name = "The name selected is an existing facility, please try again." else: if facility: form = FacilityForm(instance=facility) else: form = FacilityForm() return render_to_response( 'infrastructure/add.html', { 'existing':True, 'form':form, 'message':save_error_name, }, context_instance=RequestContext(request) )
def file_edit(request, portal, f): x = EditLock.get(f.id, 'MEDIAFILE') if x and x.valid_lock(request.user): return locked_error(request, portal, x, reverse('portals.backend.views.file_list', args=[portal.address])) else: if request.method == 'POST': form = FileForm(portal, request.POST, request.FILES, instance=f) if form.is_valid(): file_name = request.FILES['file'].name if 'file' in request.FILES else f.name file_name_err = validate_file_name(file_name) if file_name_err: form.errors['file'] = [file_name_err] else: if f.name == file_name: if 'file' in request.FILES: f.remove_file() f = form.save() f.save_writer(request.user) save_success_message(request) EditLock.unset(request.user, f.id, 'MEDIAFILE') return redirect('%s?f=%s' % (reverse('portals.backend.views.file_list', args=[portal.address]), f.name)) else: form.errors['file'] = [ _('The uploaded file does not have the same name as the original file.'), _('Please rename it to the following name') + ': %s' % f.name,] else: form = FileForm(portal, instance=f) EditLock.set(request.user, f.id, 'MEDIAFILE') return render_to_response('b/common_form.html', { 'title': _('Update File') + ': %s' % f.name, 'form': form, 'button_label': _('Update'), 'delete_url': reverse('portals.backend.views.file_delete', args=[portal.address, f.id]), }, portal_request_context(request, portal))
def singup(request): if request.user.is_authenticated(): return redirect(reverse("home")) data = {} username = request.POST["user"] password = request.POST["pass"] email = request.POST["email"] user = User.objects.filter(username=username) if not user: # user was created # set the password here u = User.objects.create(username=username, password=password, email=email) u.save() u.backend = "django.contrib.auth.backends.ModelBackend" login_auth(request, u) data["user"] = u.username else: # user was retrieved data["duplicated_user"] = True return HttpResponse(simplejson.dumps(data))
def add_categorie(request): # categorie_choices = dict(item_models.Categories.type_choices) if request.method == 'GET': return my_render( request, 'item/a_add_categorie.html', # categorie_choices = categorie_choices, ) else: form = AddCategorieForm(request.POST) if not form.is_valid(): return my_render( request, 'item/a_add_categorie.html', form_errors=form.errors, # categorie_choices = categorie_choices, ) categorie = form.save() files = request.FILES if files: file_obj = files.get('categorie_image') if not os.path.exists(settings.MEDIA_ROOT, ): os.makedirs(settings.MEDIA_ROOT, ) data = photo.save_upload_photo( file_obj, settings.MEDIA_ROOT, ) if data: categorie.photo_id = data['photo_id'] categorie.save() return redirect('/myadmin/categorie_manage/')
def hero_view(request, hero_id=0): try: hero = Player.objects.get(id=hero_id) except Player.DoesNotExist: return redirect('/') hero.faction = hero.get_faction_display() hero.kit = hero.get_kit_display() # 20 Latest games try: games = RoundPlayer.objects.filter(player=hero)[:20] # Loop and stuff for game in games: game.map = game.round.get_map_display() latest = games except RoundPlayer.DoesNotExist: latest = False return render_to_response('hero.html', { 'site_title' : '%s - ' % hero.name, 'hero' : hero, 'latest': latest })
def page_delete(request, portal, page): children_count = page.page_set.filter(deleted=False).count() if children_count > 0: return render_to_response( 'b/msg_box.html', { 'title': _('Unable to Delete'), 'message': _('This book page (%(title)s) cannot be deleted. It has %(count)s children. You may delete them first.' ) % { 'title': page.title, 'count': children_count }, 'return_url': '%s?p=%s' % (reverse('portals.backend.views.page_list', args=[portal.address]), page.id), }, portal_request_context(request, portal)) else: if request.method == 'POST': if request.POST.has_key('yes'): page.mark_deleted() return redirect( reverse('portals.backend.views.page_list', args=[portal.address])) return render_to_response( 'b/confirm_form.html', { 'title': _('Are you sure you want to delete this book page?'), 'message_title': page.title, 'message': mark_safe(page.content), }, portal_request_context(request, portal))
def participate(self, request): whitespace = ' ' username = password = first_name = last_name = '' for k, v in request.POST.items(): if 'username' in k: u = User.objects.filter(username=v) if len(u) > 0: return response('Username already exists') else: username = v elif 'password' in k: if v not in request.POST['repeatpassword']: return response('Password mismatch') else: password = v elif 'name' in k: first_name, last_name = whitespace.join( v.split()[:1]), whitespace.join(v.split()[1:]) user = User(username=username, first_name=first_name, last_name=last_name) user.set_password(password) user.save() r = redirect('/Socialize/tutorial') r.set_cookie('username', username) r.set_cookie('permissions', 'super') return r
def posted(request, mail): mails = _get_mail_list(request) mail = Mail.objects.get(pk=mail) messages.info(request, ("Your email has been saved. Please" " check your inbox to confirm.\n\n\n" " Meanwhile, why not write another one?")) return redirect(reverse('write'))
def server_view(request, server_id=0): try: server = Server.objects.get(id=server_id) except Server.DoesNotExist: return redirect('/') # Latest 20 games games_total = Round.objects.filter(server=server) roundsplayed = len(games_total) games = games_total[:20] for game in games: game.map = game.get_map_display() if game.running: game.time = 'In Progress' else: game.time_title = '%s - %s' % (game.start.isoformat(' '), game.end.isoformat(' ')) game.time = '%s' % (game.end - game.start) game.player_count = game.t1_count + game.t2_count return render_to_response('server_view.html', { 'server': server, 'games': games, 'roundsplayed': roundsplayed, })