def register(request): if request.user.is_authenticated(): return HttpResponseRedirect('/') form = RegistrationForm(request.POST or None) if request.method == 'POST': if form.is_valid(): user = form.save() perform_login(request, user) send_confirmation_email(request, user) return render(request, 'registration/register-checkemail.html') return render(request, 'registration/register.html', { 'form': form })
def home(request): """Home page""" articles = get_qs_for_user(request.user) events = Event.objects.filter(date__gte=datetime.today()) if request.user.has_perm('website.add_event'): request.user.can_add_event = True return render(request, 'website/home.html', locals())
def login(request, template_name='registration/login.html', redirect_field_name=REDIRECT_FIELD_NAME): redirect_to = request.REQUEST.get(redirect_field_name, '') if not redirect_to: redirect_to = settings.LOGIN_REDIRECT_URL if request.user.is_authenticated(): return HttpResponseRedirect(redirect_to) if request.method == "POST": form = AuthenticationForm(data=request.POST) if form.is_valid(): from django.contrib.auth import login login(request, form.get_user()) if request.session.test_cookie_worked(): request.session.delete_test_cookie() if not redirect_to or '//' in redirect_to or ' ' in redirect_to: redirect_to = settings.LOGIN_REDIRECT_URL return HttpResponseRedirect(redirect_to) else: form = AuthenticationForm(request) request.session.set_test_cookie() return render(request, template_name, { 'form': form, redirect_field_name: redirect_to, })
def directory(request, mbox_id, page=1): mbox_id = int(mbox_id) page = int(page) total = Thread.objects(mailboxes=mbox_id).count() begin = (page - 1) * 50 end = min(total, begin + 50) threads = Thread.objects(mailboxes=mbox_id)[begin:end] # Filter with user profile to be sure you are looking at your mails ! # TODO Replace account's id with something more fashion directory = request.user.get_profile().get_directory(mbox_id) context = { 'directory': directory, 'threads': threads, 'begin': begin + 1, 'end': end, 'total': total, } if total > end: context['next_url'] = reverse('directory', args=[mbox_id, page+1]) if page > 1: context['previous_url'] = reverse('directory', args=[mbox_id, page-1]) return render(request, 'mail.html', context)
def view(request, photo_id): photo_id = base32_to_int(photo_id) photo = get_object_or_404(Photo, id=photo_id) next_photo = Photo.objects.filter(id__gt=photo.id) if next_photo: next_photo = next_photo[0] previous_photo = Photo.objects.filter(id__lt=photo.id).order_by('-id') if previous_photo: previous_photo = previous_photo[0] attached_title = 'Unknown' if isinstance(photo.content_object, Production): attached_title = photo.content_object.play.get_title_display() elif isinstance(photo.content_object, Play): attached_title = photo.content_object.get_title_display() elif isinstance(photo.content_object, Place): attached_title = str(photo.content_object) elif isinstance(photo.content_object, Person): attached_title = str(photo.content_object) return render(request, 'photos/view.html', { 'photo': photo, 'next_photo': next_photo, 'previous_photo': previous_photo, 'attached_title': attached_title, })
def productions_list(request, object, dir, template, context={}): """Given an object, such as a Person, Place, or Play, return a page of productions for it.""" type = '' if not (isinstance(object, Place) or isinstance(object, Person) or isinstance(object, Play) or isinstance(object, ProductionCompany)): type = 'places' # Assume it's around search at the mo if dir == 'future': paginator = Paginator(productions_future(object, type), 10, orphans=2) dir_str = 'Current & Upcoming productions' elif dir == 'past': paginator = Paginator(productions_past(object, type), 10, orphans=2) dir_str = 'Past productions' elif dir == 'parts': paginator = Paginator(Part.objects.search(object), 10, orphans=2) dir_str = u'Parts containing \u201c%s\u201d' % object page = request.GET.get('page', 1) try: page_number = int(page) except ValueError: raise Http404 try: page_obj = paginator.page(page_number) except InvalidPage: raise Http404 context.update({ 'type': dir_str, 'object': object, 'paginator': paginator, 'page_obj': page_obj, }) return render(request, template, context)
def production_add(request, play=None, place=None, company=None): initial = {} if play: initial['play'] = play.id production_form = ProductionForm(data=request.POST or None, initial=initial) # Inline even though empty, because model validation means it can't assign null # to Place.production when calling construct_instance() ProductionPlaceFormSet = inlineformset_factory( Production, ProductionPlace, extra=1, form=PlaceForm ) place_formset = ProductionPlaceFormSet( data = request.POST or None, prefix = 'place', queryset = ProductionPlace.objects.none() ) ProductionCompanyFormSet = inlineformset_factory( Production, Production_Companies, extra=1, form=CompanyInlineForm ) companies_formset = ProductionCompanyFormSet( data = request.POST or None, prefix = 'company', queryset = Production_Companies.objects.none() ) # Yucky, but no way to pass initial to a model formset XXX if place: place_formset.forms[0].initial['place'] = place.id if company: companies_formset.forms[0].initial['productioncompany'] = company.id if request.method == 'POST': if request.POST.get('disregard'): messages.success(request, u"All right, we\u2019ve ignored what you had done.") if play: return HttpResponseRedirect(play.get_absolute_url()) if company: return HttpResponseRedirect(company.get_absolute_url()) if place: return HttpResponseRedirect(place.get_absolute_url()) if production_form.is_valid() and place_formset.is_valid() and companies_formset.is_valid(): # Nasty things to set up the parent/child inline relations as it expects them to be. production = production_form.save() place_formset.instance = production for form in place_formset.forms: form.instance.production = production companies_formset.instance = production for form in companies_formset.forms: form.instance.production = production place_formset.save() companies_formset.save() messages.success(request, "Your addition has been stored; thank you. If you know members of the cast or crew, please feel free to add them now.") url = production.get_edit_cast_url() if request.POST.get('initial_person'): url += '?person=' + request.POST.get('initial_person') return HttpResponseRedirect(url) return render(request, 'productions/add.html', { 'place': place, 'place_formset': place_formset, 'companies_formset': companies_formset, 'play': play, 'company': company, 'form': production_form, })
def inbox(request, account_slug=None, page=1): page = int(page) profile = request.user.get_profile() accounts = profile.accounts.all() if account_slug is not None: accounts = [accounts.get(slug=account_slug)] if not accounts: messages.info(request, _('You don\'t have any account yet, please ' 'fill in the form below')) return redirect(reverse('add_account')) inboxes = Mailbox.objects.filter(imap__account__in=accounts, folder_type=INBOX).values_list('id', flat=True) total = Thread.objects(mailboxes__in=inboxes).count() begin = (page - 1) * 50 end = min(total, begin + 50) threads = Thread.objects(mailboxes__in=inboxes)[begin:end] directory = profile.get_directory(inboxes[0]) context = { 'unified': True, 'directory': directory, 'threads': threads, 'begin': begin + 1, 'end': end, 'total': total, } if total > end: context['next_url'] = reverse('inbox', args=[page+1]) if page > 1: context['previous_url'] = reverse('inbox', args=[page-1]) return render(request, 'mail.html', context)
def part_edit(request, play_id, play, production_id, part_id): production = check_parameters(play_id, play, production_id) part = get_object_or_404(Part, id=part_id) if part.production != production: raise Http404() part_form = PartForm( data = request.POST or None, editing = True, instance = part, initial = { 'person': part.person } # To make form have name rather than ID ) if request.method == 'POST': if request.POST.get('disregard'): messages.success(request, u"All right, we\u2019ve ignored any changes you made.") return HttpResponseRedirect(production.get_edit_cast_url()) if part_form.is_valid(): part_form.save() messages.success(request, "Your changes have been stored; thank you.") return HttpResponseRedirect(production.get_edit_cast_url()) return render(request, 'productions/edit-part.html', { 'id': part_id, 'form': part_form, 'production': production, 'places': production.place_set.order_by('start_date', 'press_date'), })
def weblog_entry_detail(request, blog_slug, year, month, day, slug): date_stamp = time.strptime(year+month+day, "%Y%m%d") published_date = datetime.date(*date_stamp[:3]) entry = get_object_or_404(Entry.live.all(), blog__slug__exact = blog_slug, published_date__year = published_date.year, published_date__month = published_date.month, published_date__day = published_date.day, slug=slug, ) other_blogs = Blog.objects.with_entries( entry_filter={ 'published_date__year' : published_date.year, 'published_date__month' : published_date.month, 'published_date__day' : published_date.day, }, entry_exclude={ 'pk' : entry.pk } ) publications_day = Publication.objects.read_on_day(published_date) return render(request, 'weblog/entry_detail.html', { 'blog': entry.blog, 'entry': entry, 'other_blogs': other_blogs, 'publications_day': publications_day, })
def main(request): if not request.user.is_authenticated(): return redirect(reverse('registration_register')) # if 'version' in request.session: # version = request.session['version'] # print "Taking Version from Session" # else: # print "Taking Version from DB" try: version = Version.objects.filter()[0] except IndexError: version = Version(date=datetime.datetime.now()) version.save() a = [[], [], [], []] if version: products = Product.objects.filter(version=version, selectable=True) for i in range(products.count() / 4): a[0].append(products[4 * i]) a[1].append(products[4 * i + 1]) a[2].append(products[4 * i + 2]) a[3].append(products[4 * i + 3]) products = a # global Big_Matrix # Big_Matrix = eval(BigMatrix.objects.get(version = version).matrix) # Big_Matrix = dpt2Matrix.Big_Matrix # changing to custom page to test- change from main.html to dinestart.html return render(request, 'main.html', {'products': products, 'version': version})
def add_account(request): if request.method == 'POST': account_form = AccountForm(data=request.POST) smtp_form = SMTPForm(data=request.POST, prefix='smtp') imap_form = IMAPForm(data=request.POST, prefix='imap') if all([form.is_valid() for form in (account_form, smtp_form, imap_form)]): # Create an Account, attach it an IMAP and an SMTP instance. account = account_form.save(commit=False) account.profile = request.user.get_profile() account.imap = imap_form.save() account.smtp = smtp_form.save() account.save() messages.success(request, _('Your account has been successfully ' 'created')) return redirect(reverse('edit_account', args=[account.id])) else: account_form = AccountForm() smtp_form = SMTPForm(prefix='smtp') imap_form = IMAPForm(prefix='imap') context = { 'account': account_form, 'imap': imap_form, 'smtp': smtp_form } return render(request, 'users/add_account.html', context)
def take_photo(request): data = request.POST.copy() if not request.user.is_authenticated(): return HttpResponseBadRequest('Only signed in users can upload photographs.') ctype = data.get("content_type") object_id = data.get("object_id") if ctype is None or object_id is None: return HttpResponseBadRequest("Missing content_type or object_id field.") try: model = models.get_model(*ctype.split(".", 1)) target = model._default_manager.get(id=object_id) except TypeError: return HttpResponseBadRequest("Invalid content_type value: %r" % escape(ctype)) except AttributeError: return HttpResponseBadRequest("The given content-type %r does not resolve to a valid model." % escape(ctype)) except ObjectDoesNotExist: return HttpResponseBadRequest("No object matching content-type %r and object PK %r exists." % (escape(ctype), escape(object_id))) form = PhotoForm(target, data=data, files=request.FILES) if not form.is_valid(): template_list = [ "photos/preview.html" #"comments/%s_%s_preview.html" % tuple(str(model._meta).split(".")), #"comments/%s_preview.html" % model._meta.app_label, ] return render(request, template_list, { "form" : form, } ) photo = form.save() #photo = form.get_photo_object() #photo.save() next = data.get("next", '/') return HttpResponseRedirect(next)
def edit_account(request, id): account = get_object_or_404(Account, id=id) if request.method == 'POST': account_form = AccountForm(data=request.POST, instance=account) smtp_form = SMTPForm(data=request.POST, prefix='smtp', instance=account.smtp) imap_form = IMAPForm(data=request.POST, prefix='imap', instance=account.imap) if all([form.is_valid() for form in (account_form, smtp_form, imap_form)]): account_form.save() imap_form.save() smtp_form.save() messages.success(request, _('Your account have been successfully' ' updated.')) return redirect(reverse('accounts')) else: account_form = AccountForm(instance=account) smtp_form = SMTPForm(prefix='smtp', instance=account.smtp) imap_form = IMAPForm(prefix='imap', instance=account.imap) context = { 'account': account, 'account_form': account_form, 'imap': imap_form, 'smtp': smtp_form } return render(request, 'users/edit_account.html', context)
def weblog_blog_index(request, blog_slug): blog = get_object_or_404(Blog, slug=blog_slug) paginator = Paginator(Entry.live.filter(blog__slug__exact = blog_slug), 15, orphans=2) # Make sure page request is an int. If not, deliver first page. try: page = int(request.GET.get('page', '1')) except ValueError: page = 1 # If page request (9999) is out of range, deliver last page of results. try: entries = paginator.page(page) except (EmptyPage, InvalidPage): entries = paginator.page(paginator.num_pages) # Get the most popular tags that are within this Blog, and that are on LIVE Entries. popular_tags = Tag.objects.filter( weblog_taggedentry_items__content_object__blog=blog, weblog_taggedentry_items__content_object__status=Entry.LIVE_STATUS, ).annotate(num_times=Count('weblog_taggedentry_items')).order_by('-num_times', 'name')[:15] featured_entries = Entry.featured_set.all() return render(request, 'weblog/index.html', { 'blog': blog, 'entries': entries, 'popular_tags': popular_tags, 'featured_entries': featured_entries, })
def login(request): user = User() if request.method == 'GET': if 'login-user' in request.session: user = request.session['login-user'] return render(request, 'login.html', {'user':user}) if request.method == "POST": try: user = User.objects.get(email=request.POST['email'], password=hashlib.sha1(request.POST['password']).hexdigest()) except: pass if not user.id: user.email = request.POST['email'] user.errors = ['invalid-login'] request.session['login-user'] = user return redirect('/login') user.last_login = datetime.datetime.now() user.save() request.session["USER_ID"] = user.id if 'login-user' in request.session: del request.session['login-user'] if 'version' in request.session: del request.session['version'] return redirect('/')
def profile(request, username): user = get_object_or_404(User, username=username) profile = user.get_profile() latest = [] content_types = ContentType.objects.filter( Q(app_label='plays', model='play') | Q(app_label='people', model='person') | Q(app_label='productions', model='production') | Q(app_label='places', model='place') ) for l in Revision.objects.filter(user=user, version__content_type__in=content_types).distinct().order_by('-date_created')[:10]: versions = [] for v in l.version_set.filter(content_type__in=content_types): try: obj = v.content_type.get_object_for_this_type(id=v.object_id) url = obj.get_absolute_url() versions.append((obj, url)) except: pass latest.append(versions) seen = user.visit_set.extra(select={'best_date': 'IFNULL(productions_place.press_date, IF(productions_place.end_date!="", productions_place.end_date, productions_place.start_date))'}).order_by('-best_date', 'production__place__press_date').distinct() return render(request, 'profile.html', { 'view': user, 'profile': profile, 'latest': latest, 'observations': Comment.objects.filter(user=user).order_by('-submit_date')[:5], 'seen': seen, })
def people_person(request, person_id): person = get_object_or_404(Person.objects.all(), pk=person_id) publication_list = person.publication_set.all() return render(request, 'people/person_detail.html', { 'person': person, 'publication_list': publication_list, 'reading_years': Reading.objects.years(), })
def aggregator_index(request): blogs = Blog.objects.with_entries(entry_limit=3) publications_inprogress = Publication.objects.in_progress() return render(request, 'aggregator/index.html', { 'blogs': blogs, 'publications_inprogress': publications_inprogress, })
def preferences(request): try: rnd = Round.objects.filter(user=request.user).order_by('-id')[0] except IndexError: return redirect('/') polls = Poll.objects.select_related().filter(round=rnd).order_by('-id') if not polls: return redirect('/start') poll = polls[0] return render(request, 'preferences.html', {'poll':poll})
def books_index(request): """ Front page - listing unread and 'in progress' readings. """ publications_inprogress = Publication.objects.in_progress() publications_unread = Publication.objects.unread() return render(request, 'books/index.html', { 'publications_inprogress': publications_inprogress, 'publications_unread': publications_unread, 'reading_years': Reading.objects.years(), })
def random_meal(request): #reinier # if 'version' in request.session: # version = request.session['version'] # else: try: version = Version.objects.order_by('-id')[0] except IndexError: return redirect('/') products = Product.objects.filter(version=version) output = len(products) random_num = random.randint(1, len(products) - 1) meal = products[random_num] return render(request, 'random_meal.html', {'versions': versions, 'output': output, 'meal': meal})
def weblog_tag(request, blog_slug, tag_slug): blog = get_object_or_404(Blog, slug=blog_slug) tag = get_object_or_404(Tag, slug=tag_slug) entries = list(Entry.live.filter( blog = blog, tags__name__in=[tag.slug] )) return render(request, 'weblog/tag.html', { 'blog': blog, 'tag': tag, 'entries': entries, })
def books_publication(request, publication_id): """ A single Publication, and anything else in the same series. """ publication = get_object_or_404(Publication.objects.all(), pk=publication_id) if publication.series: series_publications = Publication.objects.filter(series=publication.series).exclude(pk=publication.id) else: series_publications = [] return render(request, 'books/publication_detail.html', { 'publication': publication, 'series_publications': series_publications, 'reading_years': Reading.objects.years(), })
def login_screen(self, request): vars = {"form_field_name": self.form_field_name, "path": request.get_full_path(), "error": {}} check = self.rate_limit_manual(request) if check: return check if request.method == "POST": password = request.POST.get(self.form_field_name, "") if password: if password == self.get_password(): response = http.HttpResponseRedirect(request.get_full_path()) self.set_cookie(response, password) return response else: self.cache_incr(self.current_key(request)) vars["error"]["pw"] = "That is not the correct password." email = request.POST.get("ebygum", "") if email: if email_re.match(email): obj = Prelaunch(email=email) obj.save() vars["messages"] = ["Thank you; you will hopefully hear from us in the not too distant future."] else: vars["error"]["em"] = "Please enter a valid email address." statuses = [ "Painting scenery", "Auditioning actors", "Cutting out gobos", "Rehearsing", "Measuring for costumes", "Learning lines", "Stocking the ice-cream cabinet", ] rand_not = int(request.POST.get("not", 0)) if rand_not >= 1 and rand_not <= 7: rand = random.randint(0, len(statuses) - 2) if rand >= rand_not: rand += 1 else: rand = random.randint(0, len(statuses) - 1) vars["rand"] = rand vars["status"] = statuses[rand] return render(request, "alpha_password.html", vars)
def results(request, page=None): if 'version' in request.session: version = request.session['version'] else: try: version = Version.objects.order_by('-id')[0] except IndexError: return redirect('/') rnd = Round.objects.filter(user=request.user).order_by('-id')[0] results = Result.objects.filter(round=rnd) property_ids = [x.id for x in Property.objects.filter(version=version)] function_ids = [r.function_id for r in results] function_properties = FunctionProperty.objects.select_related().filter(function__id__in=function_ids).values_list('function_id', 'property_id', 'value') properties = {} for p in property_ids: properties[p] = 0 for p in function_properties: properties[p[1]] += p[2] for i in properties.keys(): properties[i] /= len(function_ids) products = Product.objects.filter(version=version) product_properties = ProductProperty.objects.select_related().filter(product__in=products).values_list('product_id', 'property_id', 'value') p_coefficients = {} for p in products: p_coefficients[p.id] = {} for c in product_properties: p_coefficients[c[0]][c[1]] = c[2] products = products.values() for product in products: score = 0 for property_id in property_ids: score += properties[property_id] * p_coefficients[product['id']][property_id] product['score'] = score products = sorted(products, key=lambda k: k['score']) products.reverse() pages = [] for i in range(len(products) / 8): pages.append(products[8 * i:8 * i + 8]) products = products[:8] polls = Poll.objects.filter(round=rnd) return render(request, 'results.html', {'results':results, 'products':products, 'polls':polls, 'pages':pages})
def search_around(request, s, type=''): s = s.strip() m = re.match('([-\d.]+)\s*,\s*([-\d.]+)$', s) if m: lat, lon = m.groups() name = request.GET.get('name', '') elif validate_postcode(s): try: r = urllib.urlopen('http://mapit.mysociety.org/postcode/%s' % urllib.quote(s)).read() loc = simplejson.loads(r) pc, lat, lon = loc['postcode'], loc['wgs84_lat'], loc['wgs84_lon'] name = re.sub('(\d[A-Z]{2})', r' \1', s.upper()) except: return search(request, redirect_okay=False) elif validate_partial_postcode(s): try: r = urllib.urlopen('http://mapit.mysociety.org/postcode/partial/' + urllib.quote(s)).read() r = simplejson.loads(r) lat, lon = r['wgs84_lat'], r['wgs84_lon'] except: return search(request, redirect_okay=False) name = s.upper() else: raise Exception, 'Bad request' if not lat or not lon: return places = Place.objects.around(float(lat), float(lon)) if not type: past, future = productions_for(places, 'places') alert = AlertLocal.objects.filter(user=request.user.id, latitude=lat, longitude=lon) return render(request, 'search-around.html', { 'places': places, 'past': past, 'future': future, 'lat': lat, 'lon': lon, 'latlon': '%s,%s' % (lat, lon), 'name': name, 'alert': alert, }) return productions_list(request, places, type, 'search-around-productions.html', { 'lat': lat, 'lon': lon, })
def profile_edit(request): profile = request.user.get_profile() form = ProfileForm(request.POST or None, instance=profile) if request.method == 'POST': if request.POST.get('disregard'): messages.success(request, u"All right, we\u2019ve ignored any changes you made.") return HttpResponseRedirect(profile.get_absolute_url()) if form.is_valid(): form.save() messages.success(request, "Your changes have been stored; thank you.") return HttpResponseRedirect(profile.get_absolute_url()) return render(request, 'profile-edit.html', { 'form': form, 'profile': profile, })
def register_confirm(request, uidb32, token): try: uid_int = base32_to_int(uidb32) except ValueError: raise Http404 user = get_object_or_404(User, id=uid_int) if default_token_generator.check_token(user, token): p = user.get_profile() p.email_validated = True p.save() perform_login(request, user) # Decide what to do with someone confirming registration return render(request, 'registration/validated.html', { 'user': user, }) return HttpResponseRedirect('/')
def settings(request): profile = request.user.get_profile() if request.method == 'POST': form = ProfileForm(request.POST, instance=profile) if form.is_valid(): form.save() messages.success(request, _('Your settings have been updated')) return redirect(reverse('default_inbox')) else: # TODO: handle correctly the error and translate the message err = "Incorrect config..." else: err = '' form = ProfileForm(instance=profile) context = {'user': request.user, 'form': form,} return render(request, 'settings.html', context)
def fa_get(request): return (render(request, '../js学习/js语法/交互/p1.html'))
def handle404(response): """404 views""" return render(response, '404.html')
def index(response): """Index view""" return render(response, 'index.html')
def about(response): """About""" return render(response, 'about.html')