def bigmap_filter(request, slug): s = get_object_or_404(get_schema_manager(request), slug=slug, is_special_report=False) if not s.allow_charting: return HttpResponse(status=404) filter_sf_dict = _get_filter_schemafields(s) # Determine what filters to apply, based on path and/or query string. filterchain = FilterChain(request=request, schema=s) try: filterchain.update_from_request(filter_sf_dict) filters_need_more = filterchain.validate() except: logger.exception("Unhandled error") return HttpResponse(status=404) config = _decode_map_permalink(request, show_default_layers=False, filters=filterchain) new_url = filterchain.make_url(base_url=reverse("bigmap_filter", args=(slug,))) if new_url != request.get_full_path(): return HttpResponseRedirect(new_url) # add in the filter layer base_url = reverse("ebpub-schema-filter-geojson", args=(slug,)) layer_url = filterchain.make_url(base_url=base_url) custom_layer = {"url": layer_url, "params": {}, "title": "Custom Filter", "visible": True} config["layers"].append(custom_layer) if config["is_widget"]: return eb_render(request, "richmaps/embed_bigmap.html", {"map_config": simplejson.dumps(config, indent=2)}) else: return eb_render(request, "richmaps/bigmap.html", {"map_config": simplejson.dumps(config, indent=2)})
def bigmap(request): config = _decode_map_permalink(request) if config["is_widget"]: return eb_render(request, "richmaps/embed_bigmap.html", {"map_config": simplejson.dumps(config, indent=2)}) else: return eb_render(request, "richmaps/bigmap.html", {"map_config": simplejson.dumps(config, indent=2)})
def newsitem_flag(request, newsitem_id): ni = get_object_or_404(NewsItem.objects.by_request(request), id=newsitem_id) flags = NewsItemFlag.objects.filter(news_item=ni).exclude(state='approved') flag_counts = flags.values('reason').annotate(count=Count('id')).order_by() context = { 'flag_counts': flag_counts, 'news_item_id': newsitem_id, } if request.method == 'POST': form = NewsItemFlagForm(request.POST) context['form'] = form if form.is_valid(): form.save() return eb_render(request, 'moderation/flagged.html', context) else: form = NewsItemFlagForm() context['form'] = form # Initial values are easier to set here since we have access to the request, # and the Form doesn't. form.fields['news_item'].initial = str(newsitem_id) if not request.user.is_anonymous(): form.fields['user'].initial = request.user.email context['form'] = form return eb_render(request, 'moderation/flag_form.html', context)
def bigmap(request): config = _decode_map_permalink(request) if config['is_widget']: return eb_render(request, 'richmaps/embed_bigmap.html', {'map_config': simplejson.dumps(config, indent=2)}) else: return eb_render(request, 'richmaps/bigmap.html', {'map_config': simplejson.dumps(config, indent=2)})
def bigmap(request): config = _decode_map_permalink(request) if config['is_widget']: return eb_render(request, 'richmaps/embed_bigmap.html', { 'map_config': simplejson.dumps(config, indent=2) }) else: return eb_render(request, 'richmaps/bigmap.html', { 'map_config': simplejson.dumps(config, indent=2) })
def bigmap_filter(request, slug, args_from_url): s = get_object_or_404(get_schema_manager(request), slug=slug, is_special_report=False) if not s.allow_charting: return HttpResponse(status=404) filter_sf_list = list( SchemaField.objects.filter(schema__id=s.id, is_filter=True).order_by('display_order')) textsearch_sf_list = list( SchemaField.objects.filter( schema__id=s.id, is_searchable=True).order_by('display_order')) # Use SortedDict to preserve the display_order. filter_sf_dict = SortedDict([(sf.name, sf) for sf in filter_sf_list] + [(sf.name, sf) for sf in textsearch_sf_list]) # Determine what filters to apply, based on path and/or query string. filterchain = FilterChain(request=request, schema=s) try: filterchain.update_from_request(args_from_url, filter_sf_dict) filters_need_more = filterchain.validate() except: return HttpResponse(status=404) config = _decode_map_permalink(request, show_default_layers=False, filters=filterchain) new_url = filterchain.make_url( base_url=reverse('bigmap_filter', args=(slug, ))) if new_url != request.get_full_path(): return HttpResponseRedirect(new_url) # add in the filter layer base_url = reverse('ebpub-schema-filter-geojson', args=(slug, )) layer_url = filterchain.make_url(base_url=base_url) custom_layer = { 'url': layer_url, 'params': {}, 'title': "Custom Filter", 'visible': True } config['layers'].append(custom_layer) if config['is_widget']: return eb_render(request, 'richmaps/embed_bigmap.html', {'map_config': simplejson.dumps(config, indent=2)}) else: return eb_render(request, 'richmaps/bigmap.html', {'map_config': simplejson.dumps(config, indent=2)})
def bigmap(request): ''' Big map with all Schemas enabled by default. ''' filterchain = FilterChain(request=request) config = _decode_map_permalink(request, filters=filterchain) if config['is_widget']: return eb_render(request, 'richmaps/embed_bigmap.html', {'map_config': simplejson.dumps(config, indent=2)}) else: return eb_render(request, 'richmaps/bigmap.html', {'map_config': simplejson.dumps(config, indent=2)})
def bigmap(request): ''' Big map with all Schemas enabled by default. ''' filterchain = FilterChain(request=request) config = _decode_map_permalink(request, filters=filterchain) if config['is_widget']: return eb_render(request, 'richmaps/embed_bigmap.html', { 'map_config': simplejson.dumps(config, indent=2) }) else: return eb_render(request, 'richmaps/bigmap.html', { 'map_config': simplejson.dumps(config, indent=2) })
def bigmap_filter(request, slug, args_from_url): s = get_object_or_404(get_schema_manager(request), slug=slug, is_special_report=False) if not s.allow_charting: return HttpResponse(status=404) filter_sf_list = list(SchemaField.objects.filter(schema__id=s.id, is_filter=True).order_by('display_order')) textsearch_sf_list = list(SchemaField.objects.filter(schema__id=s.id, is_searchable=True).order_by('display_order')) # Use SortedDict to preserve the display_order. filter_sf_dict = SortedDict([(sf.name, sf) for sf in filter_sf_list] + [(sf.name, sf) for sf in textsearch_sf_list]) # Determine what filters to apply, based on path and/or query string. filterchain = FilterChain(request=request, schema=s) try: filterchain.update_from_request(args_from_url, filter_sf_dict) filters_need_more = filterchain.validate() except: return HttpResponse(status=404) config = _decode_map_permalink(request, show_default_layers=False, filters=filterchain) new_url = filterchain.make_url(base_url=reverse('bigmap_filter', args=(slug,))) if new_url != request.get_full_path(): return HttpResponseRedirect(new_url) # add in the filter layer base_url = reverse('ebpub-schema-filter-geojson', args=(slug,)) layer_url = filterchain.make_url(base_url=base_url) custom_layer = { 'url': layer_url, 'params': {}, 'title': "Custom Filter", 'visible': True } config['layers'].append(custom_layer) if config['is_widget']: return eb_render(request, 'richmaps/embed_bigmap.html', { 'map_config': simplejson.dumps(config, indent=2) }) else: return eb_render(request, 'richmaps/bigmap.html', { 'map_config': simplejson.dumps(config, indent=2) })
def dashboard(request): custom_message = request.session.get('login_message') if 'login_message' in request.session: del request.session['login_message'] alert_list = EmailAlert.active_objects.filter(user_id=request.user.id) saved_place_list = SavedPlace.objects.filter(user_id=request.user.id) hidden_schema_ids = HiddenSchema.objects.filter( user_id=request.user.id).values('schema_id') hidden_schema_ids = set([x['schema_id'] for x in hidden_schema_ids]) schema_list = [] for schema in Schema.public_objects.filter( is_special_report=False).order_by('plural_name'): schema_list.append({ 'schema': schema, 'is_hidden': schema.id in hidden_schema_ids }) return eb_render( request, 'accounts/dashboard.html', { 'custom_message': custom_message, 'user': request.user, 'alert_list': alert_list, 'saved_place_list': saved_place_list, 'schema_list': schema_list, })
def logout(request): if request.method == 'POST': request.session.flush() request.user = AnonymousUser() # The `next_url` can be specified either as POST data or in the # session. If it's in the session, it can be trusted. If it's in # POST data, it can't be trusted, so we do a simple check that it # starts with a slash (so that people can't hack redirects to other # sites). if REDIRECT_FIELD_NAME in request.POST and request.POST[ REDIRECT_FIELD_NAME].startswith('/'): next_url = request.POST[REDIRECT_FIELD_NAME] elif REDIRECT_FIELD_NAME in request.session: next_url = request.session.pop(REDIRECT_FIELD_NAME) else: # See if the referrer is on our site, and is not this page, # and if so, go there. referrer = request.META['HTTP_REFERER'] host = request.get_host() protocol = 'https://' if request.is_secure() else 'http://' root_url = '%s%s' % (protocol, host) if referrer != request.build_absolute_uri( ) and referrer.startswith(root_url): next_url = referrer else: # Final fallback is the login page. request.session[ 'login_message'] = "You're logged out. You can log in again below." next_url = reverse('accounts-login') return http.HttpResponseRedirect(next_url) return eb_render(request, 'accounts/logout_form.html')
def dashboard(request): """ The user's account settings, saved places, alerts, and other personalized stuff. """ custom_message = request.session.get('login_message') if 'login_message' in request.session: del request.session['login_message'] alert_list = EmailAlert.active_objects.filter(user_id=request.user.id) saved_place_list = SavedPlace.objects.filter(user_id=request.user.id) hidden_schema_ids = HiddenSchema.objects.filter( user_id=request.user.id).values('schema_id') hidden_schema_ids = set([x['schema_id'] for x in hidden_schema_ids]) schema_list = [] manager = get_schema_manager(request) for schema in manager.filter( is_special_report=False).order_by('plural_name'): schema_list.append({ 'schema': schema, 'is_hidden': schema.id in hidden_schema_ids }) from ebpub.neighbornews.utils import is_neighbornews_enabled return eb_render( request, 'accounts/dashboard.html', { 'custom_message': custom_message, 'user': request.user, 'alert_list': alert_list, 'saved_place_list': saved_place_list, 'schema_list': schema_list, 'is_neighbornews_enabled': is_neighbornews_enabled, })
def signup(request, *args, **kwargs): place = url_to_place(*args, **kwargs) schema_list = Schema.public_objects.filter(is_special_report=False).order_by("plural_name") if isinstance(place, Block): FormClass, type_code = BlockAlertForm, "b" else: FormClass, type_code = LocationAlertForm, "l" email_required = request.user.is_anonymous() if request.method == "POST": form = FormClass(request.POST, email_required=email_required) if form.is_valid(): return finish_signup(request, place, form.cleaned_data) else: schema_ids = [s.id for s in schema_list] form = FormClass( initial={ "email": "Enter your e-mail address", "radius": block_radius_value(request)[1], "frequency": "1", "include_new_schemas": True, "selected_schemas": schema_ids, "displayed_schemas": schema_ids, }, email_required=email_required, ) context = get_place_info_for_request(request, *args, **kwargs) context["form"] = form context["schema_list"] = schema_list return eb_render(request, "alerts/signup_form.html", context)
def signup(request, *args, **kwargs): place = url_to_place(*args, **kwargs) schema_list = Schema.public_objects.filter(is_special_report=False).order_by('plural_name') if isinstance(place, Block): FormClass, type_code = BlockAlertForm, 'b' else: FormClass, type_code = LocationAlertForm, 'l' email_required = request.user.is_anonymous() if request.method == 'POST': form = FormClass(request.POST, email_required=email_required) if form.is_valid(): return finish_signup(request, place, form.cleaned_data) else: schema_ids = [s.id for s in schema_list] form = FormClass(initial={ 'email': 'Enter your e-mail address', 'radius': block_radius_value(request)[1], 'frequency': '1', 'include_new_schemas': True, 'selected_schemas': schema_ids, 'displayed_schemas': schema_ids, }, email_required=email_required) context = get_place_info_for_request(request, *args, **kwargs) context['form'] = form context['schema_list'] = schema_list return eb_render(request, 'alerts/signup_form.html', context)
def form_view(request, slug, is_schema): if is_schema: p = get_object_or_404(Petition, schema__slug=slug) else: p = get_object_or_404(Petition, slug=slug) if request.method == 'POST': form = PetitionForm(request.POST) if form.is_valid(): cd = form.cleaned_data ip_address = request.META.get( 'HTTP_X_FORWARDED_FOR', '').split(',')[0] or request.META.get( 'REMOTE_ADDR', '') Petitioner.objects.create( petition=p, name=cd['name'].strip(), location=cd['location'].strip(), city=cd['city'].strip(), state=cd['state'].strip(), email=cd['email'].strip().lower(), notes=cd['notes'].strip(), date_signed=datetime.datetime.now(), ip_address=ip_address, ) return HttpResponseRedirect('thanks/') else: form = PetitionForm() return eb_render(request, 'petitions/form.html', { 'form': form, 'is_schema': is_schema, 'petition': p })
def form_view(request, slug, is_schema): if is_schema: p = get_object_or_404(Petition, schema__slug=slug) else: p = get_object_or_404(Petition, slug=slug) if request.method == 'POST': form = PetitionForm(request.POST) if form.is_valid(): cd = form.cleaned_data ip_address = request.META.get('HTTP_X_FORWARDED_FOR', '').split(',')[0] or request.META.get('REMOTE_ADDR', '') Petitioner.objects.create( petition=p, name=cd['name'].strip(), location=cd['location'].strip(), city=cd['city'].strip(), state=cd['state'].strip(), email=cd['email'].strip().lower(), notes=cd['notes'].strip(), date_signed=datetime.datetime.now(), ip_address=ip_address, ) return HttpResponseRedirect('thanks/') else: form = PetitionForm() return eb_render(request, 'petitions/form.html', {'form': form, 'is_schema': is_schema, 'petition': p})
def unsubscribe(request, alert_id): a = get_object_or_404(EmailAlert.active_objects.all(), id=alert_id, user_id=request.user.id) if request.method == 'POST': EmailAlert.objects.filter(id=alert_id).update(cancel_date=datetime.datetime.now(), is_active=False) request.session['login_message'] = "We've unsubscribed you from the alert for %s" % a.name() return http.HttpResponseRedirect('/accounts/dashboard/') return eb_render(request, 'alerts/confirm_unsubscription.html', {'alert': a})
def _new_usertype(request, schema, FormType, create_item): if request.method == 'POST': form = FormType(request.POST) if form.is_valid(): item = create_item(request, schema, form) detail_url = reverse('ebpub-newsitem-detail', args=(schema.slug, '%d' % item.id)) return HttpResponseRedirect(detail_url) else: form = FormType() mapconfig = { 'locations': [], 'layers': [], 'baselayer_type': settings.MAP_BASELAYER_TYPE, } ctx = { 'form': form, 'map_configuration': mapconfig, 'default_lon': settings.DEFAULT_MAP_CENTER_LON, 'default_lat': settings.DEFAULT_MAP_CENTER_LAT, 'default_zoom': settings.DEFAULT_MAP_ZOOM, 'schema': schema } return eb_render(request, "neighbornews/new_message.html", ctx)
def logout(request): if request.method == 'POST': request.session.flush() request.user = AnonymousUser() # The `next_url` can be specified either as POST data or in the # session. If it's in the session, it can be trusted. If it's in # POST data, it can't be trusted, so we do a simple check that it # starts with a slash (so that people can't hack redirects to other # sites). if REDIRECT_FIELD_NAME in request.POST and request.POST[REDIRECT_FIELD_NAME].startswith('/'): next_url = request.POST[REDIRECT_FIELD_NAME] elif REDIRECT_FIELD_NAME in request.session: next_url = request.session.pop(REDIRECT_FIELD_NAME) else: # See if the referrer is on our site, and is not this page, # and if so, go there. referrer = request.META['HTTP_REFERER'] host = request.get_host() protocol = 'https://' if request.is_secure() else 'http://' root_url = '%s%s' % (protocol, host) if referrer != request.build_absolute_uri() and referrer.startswith(root_url): next_url = referrer else: # Final fallback is the login page. request.session['login_message'] = "You're logged out. You can log in again below." next_url = reverse('accounts-login') return http.HttpResponseRedirect(next_url) return eb_render(request, 'accounts/logout_form.html')
def dashboard(request): """ The user's account settings, saved places, alerts, and other personalized stuff. """ custom_message = request.session.get('login_message') if 'login_message' in request.session: del request.session['login_message'] alert_list = EmailAlert.active_objects.filter(user_id=request.user.id) saved_place_list = SavedPlace.objects.filter(user_id=request.user.id) hidden_schema_ids = HiddenSchema.objects.filter(user_id=request.user.id).values('schema_id') hidden_schema_ids = set([x['schema_id'] for x in hidden_schema_ids]) schema_list = [] manager = get_schema_manager(request) for schema in manager.filter(is_special_report=False).order_by('plural_name'): schema_list.append({'schema': schema, 'is_hidden': schema.id in hidden_schema_ids}) from ebpub.neighbornews.utils import is_neighbornews_enabled return eb_render(request, 'accounts/dashboard.html', { 'custom_message': custom_message, 'user': request.user, 'alert_list': alert_list, 'saved_place_list': saved_place_list, 'schema_list': schema_list, 'is_neighbornews_enabled': is_neighbornews_enabled, })
def request_password_change(request): if request.method == 'POST': form = forms.PasswordResetRequestForm(request.POST) if form.is_valid(): return send_confirmation_and_redirect(request, form.cleaned_data['email'], utils.RESET_TASK) else: form = forms.PasswordResetRequestForm() return eb_render(request, 'accounts/request_password_change_form.html', {'form': form})
def form_thanks(request, slug, is_schema): if is_schema: p = get_object_or_404(Petition.objects.select_related(), schema__slug=slug) else: p = get_object_or_404(Petition, slug=slug) return eb_render(request, 'petitions/thanks.html', { 'is_schema': is_schema, 'petition': p })
def _delete(request, newsitem): item = get_object_or_404(NewsItem, id=newsitem) if request.method == 'POST': item.delete() messages.add_message(request, messages.INFO, 'Deleted.') return HttpResponseRedirect(reverse('neighbornews_by_user', args=(request.user.id,))) else: return eb_render(request, 'neighbornews/delete_form.html', {'newsitem': item})
def login(request, custom_message=None, force_form=False, initial_email=None): """ View for logging in. custom_message is a string to display at the top of the login form. force_form is used when you want to force display of the original form (regardless of whether it's a POST request). """ # If the user is already logged in, redirect to the dashboard. if not request.user.is_anonymous(): return http.HttpResponseRedirect('/accounts/dashboard/') if request.method == 'POST' and not force_form: form = forms.LoginForm(request, request.POST) if form.is_valid(): utils.login(request, form.user) if request.session.test_cookie_worked(): request.session.delete_test_cookie() # If the session contains a 'pending_login' variable, it will be a # tuple of (callback_name, data), where data is an unserialized # Python object and callback_name corresponds to a callback in # ebpub/accounts/callbacks.py. if 'pending_login' in request.session: try: callback, data = request.session['pending_login'] message = callbacks.do_callback(callback, form.user, data) except (TypeError, ValueError): message = None # We're done with the callbacks and don't want to risk them # happening again, so we delete the session value. del request.session['pending_login'] # Save the login message in the session so we can display it # for the user. if message: request.session['login_message'] = message next_url = request.session.pop('next_url', '/accounts/dashboard/') return http.HttpResponseRedirect(next_url) else: form = forms.LoginForm(request, initial={'email': initial_email}) request.session.set_test_cookie() if request.GET.get('next'): request.session['next_url'] = request.GET['next'] custom_message = request.session.pop('login_message', custom_message) context = { 'form': form, 'custom_message': custom_message, } return eb_render(request, 'accounts/login_form.html', context)
def register(request): # If the user is already logged in, redirect to the dashboard. if not request.user.is_anonymous(): return http.HttpResponseRedirect(reverse(dashboard)) if request.method == 'POST': form = forms.EmailRegistrationForm(request.POST) if form.is_valid(): return send_confirmation_and_redirect(request, form.cleaned_data['email'], utils.CREATE_TASK) else: form = forms.EmailRegistrationForm() return eb_render(request, 'accounts/register_form_1.html', {'form': form})
def bigmap_filter(request, slug): """ Big map with just one Schema (identified by ``slug``) enabled by default. """ s = get_object_or_404(get_schema_manager(request), slug=slug, is_special_report=False) if not s.allow_charting: return HttpResponse(status=404) filter_sf_dict = _get_filter_schemafields(s) # Determine what filters to apply, based on path and/or query string. filterchain = FilterChain(request=request, schema=s) try: filterchain.update_from_request(filter_sf_dict) filters_need_more = filterchain.validate() except: logger.exception("Unhandled error") return HttpResponse(status=404) config = _decode_map_permalink(request, show_default_layers=False, filters=filterchain) # TODO: This can leave in permalink params eg. 'i', even if there # is also 'ids', because it doesn't recognize those as being the # same. new_url = filterchain.make_url( base_url=reverse('bigmap_filter', args=(slug, ))) if new_url != request.get_full_path(): return HttpResponseRedirect(new_url) if config['is_widget']: return eb_render(request, 'richmaps/embed_bigmap.html', {'map_config': simplejson.dumps(config, indent=2)}) else: return eb_render(request, 'richmaps/bigmap.html', {'map_config': simplejson.dumps(config, indent=2)})
def city_list(request): city_type_slug = get_metro()['city_location_type'] cities_with_streets = set([City.from_norm_name(c['city']).slug for c in Street.objects.order_by().distinct().values('city')]) all_cities = [City.from_norm_name(v['slug']) for v in Location.objects.filter(location_type__slug=city_type_slug).values('slug', 'name').order_by('name')] all_cities = [city for city in all_cities if city.slug.strip()] return eb_render(request, 'db/city_list.html', {'all_cities': all_cities, 'cities_with_streets': cities_with_streets, 'bodyclass': 'city-list', })
def bigmap_filter(request, slug): """ Big map with just one Schema (identified by ``slug``) enabled by default. """ s = get_object_or_404(get_schema_manager(request), slug=slug, is_special_report=False) if not s.allow_charting: return HttpResponse(status=404) filter_sf_dict = _get_filter_schemafields(s) # Determine what filters to apply, based on path and/or query string. filterchain = FilterChain(request=request, schema=s) try: filterchain.update_from_request(filter_sf_dict) filters_need_more = filterchain.validate() except: logger.exception("Unhandled error") return HttpResponse(status=404) config = _decode_map_permalink(request, show_default_layers=False, filters=filterchain) # TODO: This can leave in permalink params eg. 'i', even if there # is also 'ids', because it doesn't recognize those as being the # same. new_url = filterchain.make_url(base_url=reverse('bigmap_filter', args=(slug,))) if new_url != request.get_full_path(): return HttpResponseRedirect(new_url) if config['is_widget']: return eb_render(request, 'richmaps/embed_bigmap.html', { 'map_config': simplejson.dumps(config, indent=2) }) else: return eb_render(request, 'richmaps/bigmap.html', { 'map_config': simplejson.dumps(config, indent=2) })
def location_type_detail(request, slug): lt = get_object_or_404(LocationType, slug=slug) order_by = get_metro()['multiple_cities'] and ('city', 'display_order') or ('display_order',) loc_list = Location.objects.filter(location_type__id=lt.id, is_public=True).order_by(*order_by) lt_list = [{'location_type': i, 'is_current': i == lt} for i in LocationType.objects.filter(is_significant=True).order_by('plural_name')] context = { 'location_type': lt, 'location_list': loc_list, 'location_type_list': lt_list, 'bodyclass': 'location-type-detail', 'bodyid': slug, } context['breadcrumbs'] = breadcrumbs.location_type_detail(context) return eb_render(request, 'db/location_type_detail.html', context)
def street_list(request, city_slug): city = city_slug and City.from_slug(city_slug) or None kwargs = city_slug and {'city': city.norm_name} or {} streets = list(Street.objects.filter(**kwargs).order_by('street', 'suffix')) if not streets: raise Http404('This city has no streets') context = { 'street_list': streets, 'city': city, 'bodyclass': 'street-list', 'example_loctype': LocationType.objects.get(slug=settings.DEFAULT_LOCTYPE_SLUG).plural_name, } context['breadcrumbs'] = breadcrumbs.street_list(context) return eb_render(request, 'db/street_list.html', context)
def register(request): # If the user is already logged in, redirect to the dashboard. if request.user: return http.HttpResponseRedirect('/accounts/dashboard/') if request.method == 'POST': form = forms.EmailRegistrationForm(request.POST) if form.is_valid(): return send_confirmation_and_redirect(request, form.cleaned_data['email'], utils.CREATE_TASK) else: form = forms.EmailRegistrationForm() return eb_render(request, 'accounts/register_form_1.html', {'form': form})
def login(request, custom_message=None, force_form=False, initial_email=None): # custom_message is a string to display at the top of the login form. # force_form is used when you want to force display of the original # form (regardless of whether it's a POST request). # If the user is already logged in, redirect to the dashboard. if request.user: return http.HttpResponseRedirect('/accounts/dashboard/') if request.method == 'POST' and not force_form: form = forms.LoginForm(request, request.POST) if form.is_valid(): utils.login(request, form.user) if request.session.test_cookie_worked(): request.session.delete_test_cookie() # If the session contains a 'pending_login' variable, it will be a # tuple of (callback_name, data), where data is an unserialized # Python object and callback_name corresponds to a callback in # ebpub/accounts/callbacks.py. if 'pending_login' in request.session: try: callback, data = request.session['pending_login'] message = callbacks.do_callback(callback, form.user, data) except (TypeError, ValueError): message = None # We're done with the callbacks and don't want to risk them # happening again, so we delete the session value. del request.session['pending_login'] # Save the login message in the session so we can display it # for the user. if message: request.session['login_message'] = message next_url = request.session.pop('next_url', '/accounts/dashboard/') return http.HttpResponseRedirect(next_url) else: form = forms.LoginForm(request, initial={'email': initial_email}) request.session.set_test_cookie() custom_message = request.session.pop('login_message', custom_message) return eb_render(request, 'accounts/login_form.html', { 'form': form, 'custom_message': custom_message })
def schema_list(request): schema_list = Schema.objects.select_related().filter(is_public=True, is_special_report=False).order_by('plural_name') schemafield_list = list(SchemaField.objects.filter(is_filter=True).order_by('display_order')) browsable_locationtype_list = LocationType.objects.filter(is_significant=True) # Populate s_list, which contains a schema and schemafield list for each schema. s_list = [] for s in schema_list: s_list.append({ 'schema': s, 'schemafield_list': [sf for sf in schemafield_list if sf.schema_id == s.id], }) return eb_render(request, 'db/schema_list.html', { 'schema_list': s_list, 'browsable_locationtype_list': browsable_locationtype_list, 'bodyclass': 'schema-list', })
def block_list(request, city_slug, street_slug): city = city_slug and City.from_slug(city_slug) or None kwargs = {'street_slug': street_slug} if city_slug: city_filter = Q(left_city=city.norm_name) | Q(right_city=city.norm_name) else: city_filter = Q() blocks = Block.objects.filter(city_filter, **kwargs).order_by('postdir', 'predir', 'from_num', 'to_num') if not blocks: raise Http404('This street has no blocks') context = { 'block_list': blocks, 'first_block': blocks[0], 'city': city, 'bodyclass': 'block-list', } context['breadcrumbs'] = breadcrumbs.block_list(context) return eb_render(request, 'db/block_list.html', context)
def news_by_user(request, userid): user = User.objects.get(id=userid) is_viewing_self = False if not request.user.is_anonymous(): if user.id == request.user.id: is_viewing_self = True items_by_schema = [] for slug in ('neighbor-messages', 'neighbor-events'): try: schema = Schema.objects.get(slug=slug) except Schema.DoesNotExist: continue items = NewsItemCreator.objects.filter(user__id=userid, news_item__schema=schema) items = items.select_related().order_by('-news_item__item_date') items = [item.news_item for item in items] items_by_schema.append({'schema': schema, 'items': items}) context = {'items_by_schema': items_by_schema, 'user': user, 'is_viewing_self': is_viewing_self} return eb_render(request, "neighbornews/news_by_user.html", context)
def logout(request): if request.method == 'POST': request.session.flush() request.user = AnonymousUser() # The `next_url` can be specified either as POST data or in the # session. If it's in the session, it can be trusted. If it's in # POST data, it can't be trusted, so we do a simple check that it # starts with a slash (so that people can't hack redirects to other # sites). if 'next_url' in request.POST and request.POST['next_url'].startswith('/'): next_url = request.POST['next_url'] elif 'next_url' in request.session: next_url = request.session.pop('next_url') else: request.session['login_message'] = "You're logged out. You can log in again below." next_url = '/accounts/login/' return http.HttpResponseRedirect(next_url) return eb_render(request, 'accounts/logout_form.html')
def homepage(request): """Front page of the default OpenBlock theme. """ end_date = today() start_date = end_date - datetime.timedelta(days=settings.DEFAULT_DAYS) end_date += datetime.timedelta(days=1) manager = get_schema_manager(request) sparkline_schemas = list(manager.filter(allow_charting=True, is_special_report=False)) # Order by slug to ensure case-insensitive ordering. (Kind of hackish.) lt_list = LocationType.objects.filter(is_significant=True).order_by('slug').extra(select={'count': 'select count(*) from db_location where is_public=True and location_type_id=db_locationtype.id'}) street_count = Street.objects.count() more_schemas = manager.filter(allow_charting=False).order_by('name') # Get the public records. date_charts = get_date_chart_agg_model(sparkline_schemas, start_date, end_date, AggregateDay) empty_date_charts, non_empty_date_charts = [], [] for chart in date_charts: if chart['total_count']: non_empty_date_charts.append(chart) else: empty_date_charts.append(chart) non_empty_date_charts.sort(lambda a, b: cmp(b['total_count'], a['total_count'])) empty_date_charts.sort(lambda a, b: cmp(a['schema'].plural_name, b['schema'].plural_name)) return eb_render(request, 'homepage.html', { 'location_type_list': lt_list, 'street_count': street_count, 'more_schemas': more_schemas, 'non_empty_date_charts': non_empty_date_charts, 'empty_date_charts': empty_date_charts, 'num_days': settings.DEFAULT_DAYS, 'default_lon': settings.DEFAULT_MAP_CENTER_LON, 'default_lat': settings.DEFAULT_MAP_CENTER_LAT, 'default_zoom': settings.DEFAULT_MAP_ZOOM, 'bodyclass': 'homepage', 'breadcrumbs': breadcrumbs.home({}), 'map_configuration': _preconfigured_map({}) })
def dashboard(request): custom_message = request.session.get('login_message') if 'login_message' in request.session: del request.session['login_message'] alert_list = EmailAlert.active_objects.filter(user_id=request.user.id) saved_place_list = SavedPlace.objects.filter(user_id=request.user.id) hidden_schema_ids = HiddenSchema.objects.filter(user_id=request.user.id).values('schema_id') hidden_schema_ids = set([x['schema_id'] for x in hidden_schema_ids]) schema_list = [] for schema in Schema.public_objects.filter(is_special_report=False).order_by('plural_name'): schema_list.append({'schema': schema, 'is_hidden': schema.id in hidden_schema_ids}) return eb_render(request, 'accounts/dashboard.html', { 'custom_message': custom_message, 'user': request.user, 'alert_list': alert_list, 'saved_place_list': saved_place_list, 'schema_list': schema_list, })
def logout(request): if request.method == 'POST': request.session.flush() request.user = None # The `next_url` can be specified either as POST data or in the # session. If it's in the session, it can be trusted. If it's in # POST data, it can't be trusted, so we do a simple check that it # starts with a slash (so that people can't hack redirects to other # sites). if 'next_url' in request.POST and request.POST['next_url'].startswith( '/'): next_url = request.POST['next_url'] elif 'next_url' in request.session: next_url = request.session.pop('next_url') else: request.session[ 'login_message'] = "You're logged out. You can log in again below." next_url = '/accounts/login/' return http.HttpResponseRedirect(next_url) return eb_render(request, 'accounts/logout_form.html')
def news_by_user(request, userid): """ List of all messages / events posted by the given user. """ user = User.objects.get(id=userid) is_viewing_self = False if not request.user.is_anonymous(): if user.id == request.user.id: is_viewing_self = True items_by_schema = [] for slug in ('neighbor-messages', 'neighbor-events'): try: schema = Schema.objects.get(slug=slug) except Schema.DoesNotExist: continue items = NewsItemCreator.objects.filter(user__id=userid, news_item__schema=schema) items = items.select_related().order_by('-news_item__item_date') items = [item.news_item for item in items] items_by_schema.append({'schema': schema, 'items': items}) context = {'items_by_schema': items_by_schema, 'user': user, 'is_viewing_self': is_viewing_self} return eb_render(request, "neighbornews/news_by_user.html", context)
def schema_detail_special_report(request, schema): """ For display of schemas where is_special_report=True. """ ni_list = NewsItem.objects.filter(schema__id=schema.id) populate_schema(ni_list, schema) populate_attributes_if_needed(ni_list, [schema]) if schema.allow_charting: browsable_locationtype_list = LocationType.objects.filter(is_significant=True) schemafield_list = list(schema.schemafield_set.filter(is_filter=True).order_by('display_order')) else: browsable_locationtype_list = [] schemafield_list = [] templates_to_try = ('db/schema_detail/%s.html' % schema.slug, 'db/schema_detail_special_report.html') return eb_render(request, templates_to_try, { 'schema': schema, 'newsitem_list': ni_list, 'browsable_locationtype_list': browsable_locationtype_list, 'schemafield_list': schemafield_list, 'bodyclass': 'schema-detail-special-report', 'bodyid': schema.slug, })
def login(request, custom_message=None, force_form=False, initial_email=None, override_target=None): """ View for logging in. custom_message is a string to display at the top of the login form. force_form is used when you want to force display of the original form (regardless of whether it's a POST request). override_target can be used to set the form's target URL; otherwise it's self-POSTing. """ if not request.user.is_anonymous(): # If the user is already logged in, redirect to the dashboard. next_url = reverse(dashboard) return http.HttpResponseRedirect(next_url) if request.method == 'POST' and not force_form: next_url = (request.session.pop(REDIRECT_FIELD_NAME, None) or request.POST.get(REDIRECT_FIELD_NAME) or reverse(dashboard)) form = forms.LoginForm(request, request.POST) if form.is_valid(): utils.login(request, form.user_cache) if request.session.test_cookie_worked(): request.session.delete_test_cookie() # If the session contains a 'pending_login' variable, it will be a # tuple of (callback_name, data), where data is an unserialized # Python object and callback_name corresponds to a callback in # ebpub/accounts/callbacks.py. if 'pending_login' in request.session: try: callback, data = request.session['pending_login'] message = callbacks.do_callback(callback, form.user_cache, data) except (TypeError, ValueError): message = None # We're done with the callbacks and don't want to risk them # happening again, so we delete the session value. del request.session['pending_login'] # Save the login message in the session so we can display it # for the user. if message: request.session['login_message'] = message return http.HttpResponseRedirect(next_url) else: form = forms.LoginForm(request, initial={'email': initial_email}) # Rendering the form. request.session.set_test_cookie() if request.REQUEST.get(REDIRECT_FIELD_NAME): request.session[REDIRECT_FIELD_NAME] = request.REQUEST[ REDIRECT_FIELD_NAME] custom_message = request.session.pop('login_message', custom_message) context = RequestContext( request, { 'form': form, 'custom_message': custom_message, 'target': override_target or reverse(login), }) return eb_render(request, 'accounts/login_form.html', context)
def _update_item(request, form, schema, action): # Do we need to use need captcha? # This might depend on the request, so you can set it to a callable, # or rather a path to a callable. need_captcha = getattr(settings, 'NEIGHBORNEWS_USE_CAPTCHA', False) if isinstance(need_captcha, basestring): module, func = need_captcha.split(':') import importlib module = importlib.import_module(module) need_captcha = getattr(module, func) if callable(need_captcha): need_captcha = need_captcha(request) if need_captcha: form.need_captcha = True form.recaptcha_ip = request.META['REMOTE_ADDR'] cat_field = SchemaField.objects.get(schema=schema, name='categories') if form.is_bound and form.is_valid(): # Creating or updating a NewsItem. form.instance.schema = schema item = form.save() # Add a NewsItemCreator association; un-lazy the User. user = User.objects.get(id=request.user.id) NewsItemCreator.objects.get_or_create(news_item=item, user=user) # Image url. if form.cleaned_data['image_url'] is not None: item.attributes['image_url'] = form.cleaned_data['image_url'] # Image. uploaded = form.cleaned_data['image'] if uploaded is False: # This is apparently how File fields announce deletion. Is # that in the docs?? item.newsitemimage_set.all().delete() elif uploaded: from ebpub.db.models import NewsItemImage # TODO: allow more than one? For now, we just delete and recreate. item.newsitemimage_set.all().delete() ni_image, created = NewsItemImage.objects.get_or_create(news_item=item, image=uploaded.name) ni_image.image.save(uploaded.name, uploaded) # Times. for key in ('start_time', 'end_time'): if key in form.fields and form.cleaned_data.get(key): item.attributes[key] = form.cleaned_data[key] # 'categories' cats = [cat for cat in form.cleaned_data['categories'].split(',') if cat.strip()] if len(cats): lookups = set() for cat in cats: code = _category_code(cat) nice_name = _category_nice_name(cat) lu = Lookup.objects.get_or_create_lookup(cat_field, nice_name, code, "", False) lookups.add(lu.id) item.attributes['categories'] = ','.join(['%d' % luid for luid in lookups]) detail_url = reverse('ebpub-newsitem-detail', args=(schema.slug, '%d' % item.id)) if action == 'create': messages.add_message(request, messages.INFO, '%s created.' % schema.name) else: messages.add_message(request, messages.INFO, '%s edited.' % schema.name) return HttpResponseRedirect(detail_url) elif form.instance: # Update form. if form.instance.attributes.get('categories'): cat_ids = form.instance.attributes['categories'].split(',') cat_lookups = Lookup.objects.filter(schema_field=cat_field, id__in=cat_ids) form.fields['categories'].initial = ', '.join( sorted([look.name for look in cat_lookups])) if form.instance.location: form.fields['location'].initial = form.instance.location.wkt existing_images = list(form.instance.newsitemimage_set.all()) if existing_images: img = existing_images[0].image # TODO: allow uploading more than one? form.fields['image'].initial = img else: img = None for key in ('start_time', 'end_time', 'image_url'): if key in form.fields and form.instance.attributes.get(key): value = form.instance.attributes[key] if key.endswith('time'): value = value.strftime('%H:%M%p') form.fields[key].initial = value mapconfig = { 'locations': [], 'layers': [], 'baselayer_type': settings.MAP_BASELAYER_TYPE, } ctx = { 'form': form, 'map_configuration': mapconfig, 'default_lon': settings.DEFAULT_MAP_CENTER_LON, 'default_lat': settings.DEFAULT_MAP_CENTER_LAT, 'default_zoom': settings.DEFAULT_MAP_ZOOM, 'schema': schema, 'action': action, 'need_captcha': need_captcha, 'image': img, } return eb_render(request, "neighbornews/new_message.html", ctx)
def _update_item(request, form, schema, action): # Do we need to use need captcha? # This might depend on the request, so you can set it to a callable, # or rather a path to a callable. need_captcha = getattr(settings, 'NEIGHBORNEWS_USE_CAPTCHA', False) if isinstance(need_captcha, basestring): module, func = need_captcha.split(':') import importlib module = importlib.import_module(module) need_captcha = getattr(module, func) if callable(need_captcha): need_captcha = need_captcha(request) if need_captcha: form.need_captcha = True form.recaptcha_ip = request.META['REMOTE_ADDR'] cat_field = SchemaField.objects.get(schema=schema, name='categories') if form.is_bound and form.is_valid(): # Creating or updating a NewsItem. form.instance.schema = schema item = form.save() # Add a NewsItemCreator association; un-lazy the User. user = User.objects.get(id=request.user.id) NewsItemCreator.objects.get_or_create(news_item=item, user=user) # Image url. if form.cleaned_data['image_url'] is not None: item.attributes['image_url'] = form.cleaned_data['image_url'] # Image. uploaded = form.cleaned_data['image'] if uploaded is False: # This is apparently how File fields announce deletion. Is # that in the docs?? item.newsitemimage_set.all().delete() elif uploaded: from ebpub.db.models import NewsItemImage # TODO: allow more than one? For now, we just delete and recreate. item.newsitemimage_set.all().delete() ni_image, created = NewsItemImage.objects.get_or_create(news_item=item, image=uploaded.name) ni_image.image.save(uploaded.name, uploaded) # Times. for key in ('start_time', 'end_time'): if key in form.fields and form.cleaned_data.get(key): item.attributes[key] = form.cleaned_data[key] # 'categories' cats = [cat.strip() for cat in form.cleaned_data['categories'].split(',') if cat.strip()] if len(cats): lookups = set() for cat in cats: code = _category_code(cat) nice_name = _category_nice_name(cat) try: # We don't call get_or_create() yet because we # only want to look up by the normalized code, to # avoid dupes with slightly different names. from django.db.models import Q lu = Lookup.objects.filter( Q(schema_field=cat_field), Q(code=code) | Q(name=nice_name) )[0] except (IndexError, Lookup.DoesNotExist): # We know it doesn't exist, but use get_or_create_lookup() # here b/c that takes care of the slug. lu = Lookup.objects.get_or_create_lookup(cat_field, nice_name, code=code) lookups.add(lu.id) item.attributes['categories'] = ','.join(['%d' % luid for luid in lookups]) detail_url = reverse('ebpub-newsitem-detail', args=(schema.slug, '%d' % item.id)) if action == 'create': messages.add_message(request, messages.INFO, '%s created.' % schema.name) else: messages.add_message(request, messages.INFO, '%s edited.' % schema.name) return HttpResponseRedirect(detail_url) elif form.instance: # Update form. if form.instance.attributes.get('categories'): cat_ids = form.instance.attributes['categories'].split(',') cat_lookups = Lookup.objects.filter(schema_field=cat_field, id__in=cat_ids) form.fields['categories'].initial = ', '.join( sorted([look.name for look in cat_lookups])) if form.instance.location: form.fields['location'].initial = form.instance.location.wkt existing_images = list(form.instance.newsitemimage_set.all()) if existing_images: img = existing_images[0].image # TODO: allow uploading more than one? form.fields['image'].initial = img else: img = None for key in ('start_time', 'end_time', 'image_url'): if key in form.fields and form.instance.attributes.get(key): value = form.instance.attributes[key] if key.endswith('time'): value = value.strftime('%H:%M%p') form.fields[key].initial = value mapconfig = { 'locations': [], 'layers': [], 'baselayer_type': settings.MAP_BASELAYER_TYPE, } ctx = { 'form': form, 'map_configuration': mapconfig, 'default_lon': settings.DEFAULT_MAP_CENTER_LON, 'default_lat': settings.DEFAULT_MAP_CENTER_LAT, 'default_zoom': settings.DEFAULT_MAP_ZOOM, 'schema': schema, 'action': action, 'need_captcha': need_captcha, 'image': img, } return eb_render(request, "neighbornews/new_message.html", ctx)
def form_thanks(request, slug, is_schema): if is_schema: p = get_object_or_404(Petition.objects.select_related(), schema__slug=slug) else: p = get_object_or_404(Petition, slug=slug) return eb_render(request, 'petitions/thanks.html', {'is_schema': is_schema, 'petition': p})
# Look for any PendingUserActions for this e-mail address and # execute the callbacks. for action in PendingUserAction.objects.filter(email=u.email): data = callbacks.unserialize(action.data) callbacks.do_callback(action.callback, u, data) action.delete() request.session[ 'login_message'] = 'Your account was created! Thanks for signing up.' return http.HttpResponseRedirect('../dashboard/') else: form = forms.PasswordRegistrationForm(initial={ 'e': email, 'h': email_hash }) return eb_render(request, 'accounts/register_form_2.html', {'form': form}) ################### # PASSWORD CHANGE # ################### def request_password_change(request): if request.method == 'POST': form = forms.PasswordResetRequestForm(request.POST) if form.is_valid(): return send_confirmation_and_redirect(request, form.cleaned_data['email'], utils.RESET_TASK) else: