Пример #1
0
def location(request):
    """
    Location selection of the user profile
    """
    if (request.user.password == "!"):
        return HttpResponseRedirect('/accounts/social')
    profile, created = Profile.objects.get_or_create(user=request.user)

    if request.method == "POST":
        form = LocationForm(request.POST, instance=profile)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse("profile_edit_location_done"))
    else:
        form = LocationForm(instance=profile)

    template = "userprofile/profile/location.html"
    data = {
        'section': 'location',
        'GOOGLE_MAPS_API_KEY': GOOGLE_MAPS_API_KEY,
        'form': form,
    }
    return render_to_response(template,
                              data,
                              context_instance=RequestContext(request))
Пример #2
0
def edit_location(request, location_id):
    location = get_object_or_404(Location, pk=location_id)
    member_login = get_member_login_object(request)
    if "error" in request.GET:
        return render_to_response(
                "location_template/page/edit_error.html",
                {
                    "member_login": member_login,
                },
                context_instance=RequestContext(request)
            )
    if request.method =='POST':
        form = LocationForm(request.POST)
        if form.is_valid(): 
            try:
                location.name = request.POST['name']
                location.description = request.POST['description']
                location.category = request.POST['category']
                location.address1 = request.POST['address1']
                location.address2 = request.POST['address2']
                location.city = request.POST['city']
                location.state = request.POST['state']
                location.zip_code = request.POST['zip_code']
                if "avatar" in request.FILES:
                    location.avatar = request.FILES['avatar']
                location.save() 
            except:
                return HttpResponseRedirect("/location/" + location_id + "/edit/?error")
            return HttpResponseRedirect("/" + member_login.user.username + "?edit=location")
    else:
        default_data = {
                "name": location.name, 
                "description": location.description,
                "category": location.category,
                "address1": location.address1,
                "address2": location.address2,
                "city": location.city,
                "state": location.state,
                "zip_code": location.zip_code,
                "avatar": location.avatar,
            }
        form = LocationForm(default_data)
    return render_to_response(
                    "location_template/page/edit.html", 
                    {
                        "form": form, 
                        "member_login": member_login,
                        "location":location,
                    }, 
                    context_instance=RequestContext(request))
Пример #3
0
def admin_home():
    locform = LocationForm()
    if locform.validate_on_submit():
        ids = request.form.getlist('id')
        name = request.form.getlist('name')
        longitude = request.form.getlist('longitude')
        latitude = request.form.getlist('latitude')
        type = request.form.getlist('types')
        for (i, id) in enumerate(ids):
            if id.isdigit():
                loc = Location.query.get(id)
                loc.longitude = longitude[i]
                loc.latitude = latitude[i]
                loc.name = name[i]
                loc.type = type[i].lower()
                db.session.commit()
            else:
                if longitude[i] and latitude[i] and name[i]:
                    loc = Location(float(longitude[i]), float(latitude[i]),
                                   name[i], 'N/A', 'N/A')
                    loc.type = type[i].lower()
                    db.session.add(loc)
                    db.session.commit()
    locations = Location.query.all()
    type_list = list()

    for type in location_type._asdict().values():
        type_list.append(type.capitalize())
    return render_template('admin.html',
                           locations=locations,
                           location_types=type_list,
                           form=locform,
                           username=current_user.username)
Пример #4
0
def fuel_price_home(request):
    form = LocationForm(request.POST or None)
    locations = models.AAAData.objects.all()
    # for key,item in form.fields.iteritems():
    #     print key, item

    context = {
        "form": form,
        # "locations":locations,
    }
    # print form.is_valid()
    if form.is_valid():
        pk = form.cleaned_data['location']
        location = models.AAAData.objects.filter(pk=pk)[0]
        variables = location.data.keys()
        fuel_data = sorted(location.data.iteritems())
        variables = sorted([x.replace(' ', '_') for x in variables])
        print variables
        if models.OilPrice.objects.filter(oil_type='brent'):
            brent_data = models.OilPrice.objects.filter(
                oil_type='brent')[0].data
        else:
            brent_data = None

        context = {
            "form": form,
            "fuel_data": fuel_data,
            "variables": variables,
            "fuel_data_json": json.dumps(fuel_data),
            "brent_data_json": json.dumps(brent_data),
        }

    return render(request, 'fuel_price_home.html', context)
Пример #5
0
def location():
	form = LocationForm()
	if form.validate_on_submit():
		cityname = form.cityname.data
		return redirect(url_for('forecast', cityname=cityname))

	return render_template('location.html', form=form)
Пример #6
0
def create_location(request):
    member_login = get_member_login_object(request)
    if "error" in request.GET:
        return render_to_response(
                "location_template/page/create_error.html",
                {
                    "member_login": member_login,
                },
                context_instance=RequestContext(request)
            )
    if request.method=='POST':
        form = LocationForm(request.POST, request.FILES)
        if form.is_valid(): 
            try:
                name = request.POST['name']
                description = request.POST['description']
                category = request.POST['category']
                address1 = request.POST['address1']
                address2 = request.POST['address2']
                city = request.POST['city']
                state = request.POST['state']
                zip_code = request.POST['zip_code']
                new_location = Location.objects.create(
                                create_by=member_login,
                                name=name,
                                description=description,
                                address1=address1,
                                address2=address2,
                                city=city,
                                state=state,
                                zip_code=zip_code
                            )
                if "avatar" in request.FILES:
                    new_location.avatar = request.FILES['avatar']
                new_location.save() 
            except:
                return HttpResponseRedirect("/location/create/?error")
            return HttpResponseRedirect("/" + member_login.user.username + "?create=location")
    else:
        form = LocationForm()
    return render_to_response(
                "location_template/page/create.html", 
                {
                    "form": form,
                    'member_login': member_login,
                }, 
                context_instance=RequestContext(request))
Пример #7
0
 def get(self, request, *args, **kwargs):
     parking_lot = get_object_or_404(ParkingLot, id=kwargs['pk'])
     return render(
         request, 'website/system/parking_lot/location-form.html', {
             'form': LocationForm(instance=parking_lot.location),
             'latitude': parking_lot.location.latitude,
             'longitude': parking_lot.location.longitude,
         })
Пример #8
0
def editlocation(request, location_id):
    location = get_object_or_404(Location, pk=location_id)

    if request.POST:
        form = LocationForm(request.POST, instance=location)
        if form.is_valid():
            form.save()

            return HttpResponseRedirect('/')

    else:
        form = LocationForm(instance=location)

    return render_to_response("editlocation.html", {
        'form': form,
        'location': location,
    },
                              context_instance=RequestContext(request))
Пример #9
0
def get_location():

    location_form = LocationForm(csrf_enabled=False)

    if request.method == 'POST' and location_form.validate():
        location = location_form.zip_code.data

        return redirect(url_for('.show_weather', location=location))

    return render_template('index.html', form=location_form)
Пример #10
0
def index():
    form = LocationForm()
    if form.validate_on_submit():
        town = form.town.data
        plz = str(form.plz.data)
        if not backend.validate_location(town, plz):
            flash("Der eingegebene Ort ist ungültig.", "alert-error")
        else:
            return redirect(url_for("restaurants", town=town, plz=plz))
    return render_template("index.html", form=form)
Пример #11
0
def all_locations(request):
    locations = Location.objects.all().order_by('type')

    for i in locations:
        lat, long = i.latlng.split(",")

    if request.POST:
        form = LocationForm(request.POST)
        if form.is_valid():
            form.save()

            return HttpResponseRedirect('/')
    else:
        form = LocationForm()

    location = Location.objects.all()
    title = "Location"
    url = "location"

    return render(request, "locations.html", locals())
Пример #12
0
def new_location():
    """
    Add a new location
    """
    form = LocationForm(request.form)
    if request.method == 'POST' and form.validate():
        # save the location
        save_changes('location', Location(), form, new=True)
        flash('Location created successfully!')
        return redirect('/')

    return render_template('new_location.html', form=form)
Пример #13
0
 def post(self, request, *args, **kwargs):
     parking_lot_instance = get_object_or_404(ParkingLot, id=kwargs['pk'])
     location = LocationForm(request.POST,
                             instance=parking_lot_instance.location)
     if location.is_valid():
         location.save()
         messages.add_message(request, messages.SUCCESS,
                              'Informações atualizadas com sucesso.')
         return redirect('estacionamento-detalhe', kwargs['pk'])
     messages.add_message(request, messages.ERROR,
                          'Erro ao atualizar informações.')
     return render(request, 'website/system/parking_lot/location-form.html',
                   {'form': location})
Пример #14
0
def edit(id):
    qry = db_session.query(Location).filter(
                Location.id==id)
    location = qry.first()

    if location:
        form = LocationForm(formdata=request.form, obj=location)
        if request.method == 'POST' and form.validate():
            # save edits
            save_changes('location', location, form)
            flash('Location updated successfully!')
            return redirect('/')
        return render_template('edit_location.html', form=form)
    else:
        return 'Error loading #{id}'.format(id=id)
Пример #15
0
def weather():
    form = LocationForm()

    weather = dict()
    if form.validate_on_submit():
        return render_template(
            'weather.html', form=form,
            weather=get_weather(city=form.city.data, key=form.weatherbit_api_key.data),
            banners=get_rtb_banners(),
        )

    return render_template(
        'weather.html', form=form,
        weather=dict(),
        banners=get_rtb_banners(),
    )
Пример #16
0
def addlocation():
    form = LocationForm()
    if form.validate_on_submit() or request.method == 'POST':
        location = Location(locationName=form.locationName.data,
                            locationAddress=form.locationAddress.data)
        try:
            db.session.add(location)
            db.session.commit()
            flash('Location has been added.', 'success')
            return redirect(url_for("locations"))
        except:
            flash('Database Error.', 'danger')
            return redirect(url_for("locations"))
    return render_template('addlocation.html',
                           title="Locations",
                           form=form,
                           legend='Add New location')
Пример #17
0
def add_location():
    form = LocationForm(request.form)
    location = form.location.data.upper()
    form.location.data = ''

    if request.method == 'POST':
        if location:
            res = make_response(redirect(url_for('index')))
            flash('Location updated.')
            res.set_cookie("location",
                           location.upper(),
                           expires=datetime.datetime.now() +
                           datetime.timedelta(days=5000))
            return res
        else:
            flash('Enter a valid location.')

    return render_template('add_location.html', form=form)
Пример #18
0
def editprofile():
    form = UpdateAccountForm()
    form2 = LocationForm()
    if form.validate_on_submit():
        current_user.fname = form.fname.data
        current_user.lname = form.lname.data
        current_user.email = form.email.data
        current_user.phone = form.phone.data
        db.session.commit()
        flash(f'Personal Details Successfully Updated', 'success')
        return redirect(url_for('editprofile'))
    elif request.method == 'GET':
        form.fname.data = current_user.fname
        form.lname.data = current_user.lname
        form.email.data = current_user.email
        form.phone.data = current_user.phone
    image_file = url_for('static', filename='images/users/' + current_user.image_file)
    return render_template('Edit Profile.html', title='Account', image_file=image_file, form=form, form2=form2)
Пример #19
0
Файл: app.py Проект: miku/evreg
def create_location():
	form = LocationForm()
	if form.validate_on_submit():
		location = Location()
		location.name = form.name.data
		location.capacity = form.capacity.data
		location.country = form.country.data
		location.zipcode = form.zipcode.data
		location.city = form.city.data
		location.street = form.street.data
		
		location.address_additions = form.address_additions.data
		location.google_maps_url = form.google_maps_url.data
		
		db_session.add(location)
		db_session.commit()
		return redirect(url_for('list_locations'))
	return render_template("admin/create_location.html", form=form)
Пример #20
0
def updatelocation(locationId):
    location = Location.query.get_or_404(locationId)
    form = LocationForm()
    if form.validate_on_submit() or request.method == 'POST':
        location.locationName = form.locationName.data
        location.locationAddress = form.locationAddress.data
        try:
            db.session.commit()
            flash('Location Name has been updated.', 'success')
            return redirect(url_for("locations"))
        except:
            flash('Database Error.', 'danger')
            return redirect(url_for("locations"))
    form.locationName.data = location.locationName
    form.locationAddress.data = location.locationAddress
    return render_template('addlocation.html',
                           form=form,
                           legend='Update Location')
Пример #21
0
    def post(self, request, *args, **kwargs):
        location = LocationForm(request.POST)
        parking_lot = ParkingLotForm(request.POST)
        if location.is_valid() and parking_lot.is_valid():
            location_instance = location.save()
            parking_lot_instance = parking_lot.save(commit=False)
            parking_lot_instance.location = location_instance
            parking_lot_instance.owner = get_object_or_404(
                Person, user__id=request.user.id)
            parking_lot_instance.save()
            return redirect('estacionamentos')

        forms = {
            u'Localização': location,
            u'Estacionamento': parking_lot,
        }
        messages.add_message(request, messages.ERROR,
                             'Erro ao atualizar informações.')
        return render(request,
                      'website/system/parking_lot/new-parking-lot.html',
                      {'forms': forms})
Пример #22
0
def edit(id=0):
    setExits()
    defaultLoc = {
        'lat': app.config['LOCATION_DEFAULT_LAT'],
        'lng': app.config['LOCATION_DEFAULT_LNG']
    }
    #LOCATION_DEFAULT_LNG
    #LOCATION_DEFAULT_LAT

    id = cleanRecordID(id)
    if id < 0:
        flash("That is not a valid ID")
        return redirect(g.listURL)

    g.tripTotalCount = getLocationTripTotal(id)
    rec = None
    if id > 0:
        rec = Location.query.get(id)
        if not rec:
            flash(
                printException(
                    "Could not edit that " + g.title + " record. ID=" +
                    str(id) + ")", 'error'))
            return redirect(g.listURL)

    form = LocationForm(request.form, rec)

    if request.method == 'POST' and form.validate():
        if not rec:
            rec = Location(form.locationName.data, g.orgID)
            db.session.add(rec)
        form.populate_obj(rec)
        db.session.commit()
        return redirect(g.listURL)

    return render_template('location/location_edit.html',
                           rec=rec,
                           form=form,
                           defaultLoc=defaultLoc)
Пример #23
0
def maps():
    form = LocationForm()
    if form.validate_on_submit():
        coors = [
            re.sub(r' ', '\+', str(form.x_coor.data)),
            re.sub(r' ', '\+', str(form.y_coor.data))
        ]
        # print(form.image)
        file_name = images.save(form.image.data)
        # print('Prepocessing')
        preprocessing(file_name)
        # print('Done')
        # print('Processing')
        # print(form.crs.data)
        coors = list(processing(file_name, int(form.crs.data)))
        # print('Done')
        os.remove(f'./imgtxtenh/{file_name}')
        os.remove(f'./imgtxtenh/pre_{file_name}')
        try:
            response = requests.get(
                f'https://maps.googleapis.com/maps/api/geocode/json?latlng={coors[0]},{coors[1]}&key=AIzaSyCaRkfQYahP3fTIL31Da9Ppv5rnNWcG1F0'
            )
            # access JSOn content
            jsonResponse = response.json()
            coors.append(jsonResponse["results"][0]["formatted_address"])
            print(jsonResponse["results"][0]["formatted_address"])

        except HTTPError as http_err:
            print(f'HTTP error occurred: {http_err}')
        except Exception as err:
            print(f'Other error occurred: {err}')
        return render_template('maps.html',
                               title='Google Maps API',
                               form=form,
                               posts=coors)
    return render_template('maps.html', title='Google Maps API', form=form)