Exemple #1
0
def register(request):
    if request.method == 'POST':
        userForm = UserForm(data=request.POST)
        profileForm = UserProfileForm(data=request.POST)
        locationForm = LocationForm(data=request.POST)

        if userForm.is_valid() and profileForm.is_valid() and \
           locationForm.is_valid():
            userObj = userForm.save()
            userObj.set_password(userObj.password)
            userObj.save()

            location = locationForm.save(commit=False)
            location.name = 'Home'
            location.save()

            profileObj = profileForm.save(commit=False)
            profileObj.user = userObj
            profileObj.address = location
            profileObj.save()
            profileObj.locations.add(location)
            profileObj.save()

            userObj = authenticate(username=userObj.username,
                                   password=userObj.password)
            login(request, userObj)

            return render(request, 'socketbox/index.html', {})
        else:
            if not locationForm.is_valid():
                print("Location is bad!")
                print locationForm.errors
            if not userForm.is_valid():
                print("user is bad!")
                print userForm.errors
                print request.POST
            if not profileForm.is_valid():
                print("profile is bad!")
                print profileForm.errors
            return index(request)
    else:
        profileForm = UserProfile()
        locationForm = Location()
        userForm = User()

    contextDict = {'profileForm': profileForm, 'locationForm': locationForm,
                   'userForm': userForm}

    return render(request, "registration/registration_form.html", contextDict)
Exemple #2
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))
Exemple #3
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)
Exemple #4
0
def register_user(request):

    context = setup_view(request, 'Register')

    if request.method == 'POST': # If the form has been submitted...
        citizen_form = CitizenForm(request.POST, request.FILES) # A form bound to the POST data
        location_form = LocationForm(request.POST)

        if citizen_form.is_valid() and location_form.is_valid(): # All validation rules pass

            #Save the valid data
            home_location = location_form.save(commit=True)
            user = citizen_form.save(commit=False)

            email = citizen_form.cleaned_data.get('email')
            avatar = citizen_form.cleaned_data.get('avatar')
            first_name = citizen_form.cleaned_data.get('first_name')
            last_name = citizen_form.cleaned_data.get('last_name')

            citizen = Citizen.objects.create(email=email, first_name=first_name, last_name=last_name, avatar=avatar,
                                             user=user, home_location=home_location)
            citizen.save()

            context['citizen'] = citizen

            return redirect(home)

    else:
        citizen_form = CitizenForm() # An unbound form
        location_form = LocationForm()

    context['citizen_form'] = citizen_form
    context['location_form'] = location_form
    return render_to_response('registration/create_user.html', context, context_instance=RequestContext(request))
Exemple #5
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)
Exemple #6
0
def edit_location(request, username):
    person = get_object_or_404(DjangoPerson, user__username = username)
    if request.method == 'POST':
        form = LocationForm(request.POST)
        if form.is_valid():
            region = None
            if form.cleaned_data['region']:
                region = Region.objects.get(
                    country__iso_code = form.cleaned_data['country'],
                    code = form.cleaned_data['region']
                )
            person.country = Country.objects.get(
                iso_code = form.cleaned_data['country']
            )
            person.region = region
            person.latitude = form.cleaned_data['latitude']
            person.longitude = form.cleaned_data['longitude']
            person.location_description = \
                form.cleaned_data['location_description']
            person.save()
            return HttpResponseRedirect('/%s/' % username)
    else:
        form = LocationForm()
    return render(request, 'edit_location.html', {
        'form': form,
        'api_key': settings.GOOGLE_MAPS_API_KEY,
    })
def home(request):
    status = {
        'comma': "Learn how to type! City COMMA State.",
	'error': "I don't know what you did wrong. I can't find it.",
	'sports': "Things are gonna suck because of a game in town.",
	'maybe': "Probably, but not due to a sports game."
    }
    if request.method == 'POST':
	form = LocationForm(request.POST, request.FILES)
	if form.is_valid():
            cd = form.cleaned_data
	    if ',' in cd['location']:
                # Split the location in two, separated with a comma
		location = cd['location'].split(',')
		city = location[0].upper()
		state = location[1].upper()
		# Call the sports function with a request
		if sports(city, state):
		    return render_to_response('index.html', {'status':status['sports']})
		return render_to_response('index.html', {'status':status['maybe']})
	    else:
	        form = LocationForm()
	        return render(request, 'index.html', {'status':status['comma'], 'form':form})
        else:
	    form = LocationForm()
	    return render(request, 'index.html', {'status':status['error'], 'form':form})
    form = LocationForm()
    return render(request, 'index.html', {'form':form})
def add_location(req, parent_id=None):
    nodes = Area.tree.all()

    if req.method == 'POST':
        form = LocationForm(req.POST)
        if form.is_valid():
            name = form.cleaned_data['name']
            code = form.cleaned_data['code']
            lat = form.cleaned_data['lat']
            lon = form.cleaned_data['lon']
            target = form.cleaned_data['target']
            position = form.cleaned_data['position']
            kind=form.cleaned_data['kind']

            area=Area.objects.create(name=name,code=code,parent=target)
            if lat and lon:
                location=Point(latitude=lat,longitude=lon)
                location.save()
                area.location=location
            try:
                kind=get_object_or_404(AreaType,pk=int(kind))
                area.kind=kind
            except ValueError:
                pass
            area.save()
            form = LocationForm()

            return render_to_response(
                    'simple_locations/location_edit.html'
                    ,{'form': form, 'nodes': nodes},
                    context_instance=RequestContext(req))
        else:
            form = LocationForm(req.POST)
            return render_to_response(
                    'simple_locations/location_edit.html'
                    ,{'form': form, 'nodes': nodes},
                    context_instance=RequestContext(req))

    else:
        if (parent_id):
            default_data = {}
            parent = get_object_or_404(Area, pk=parent_id)
            default_data['move_choice'] = True
            default_data['target'] = parent.pk
            default_data['position'] = 'last-child'
            form = LocationForm(default_data)
            form._errors=''


        else:
            form = LocationForm()

    return render_to_response(
            'simple_locations/location_edit.html'
            ,{'form': form, 'nodes': nodes},
            context_instance=RequestContext(req))
Exemple #9
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})
Exemple #10
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))
Exemple #11
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))
def location_new(request):
    from forms import LocationForm
    initial = {}
    if request.method == 'POST':
        form = LocationForm(request.POST, initial=initial)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/systems/locations/')
    else:
        form = LocationForm(initial=initial)

    return render_to_response(
        'generic_form.html',
        {
            'form': form,
        },
        RequestContext(request))
Exemple #13
0
def location(request):
    """
    Location selection of the user profile
    """
    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))
Exemple #14
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))
def location_edit(request, object_id):
    location = get_object_or_404(models.Location, pk=object_id)
    from forms import LocationForm
    initial = {}
    if request.method == 'POST':
        form = LocationForm(request.POST, instance=location)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/systems/locations/')
    else:
        form = LocationForm(instance=location)

    return render_to_response(
        'generic_form.html',
        {
            'form': form,
        },
        RequestContext(request))
Exemple #16
0
def location_add(request):
	"""
	FIXME
	@param request:
	@type request:
	"""
	if request.method == "POST":
		form = LocationForm(request.POST)
		if form.is_valid():
			larp=form.save()
			return HttpResponseRedirect(location.get_absolute_url())
	else:
		form = LocationForm()
	
	return render_to_response('eventCRUD/location_add.html', {
		'form':form, 
		},
		context_instance=RequestContext(request)
	)
Exemple #17
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())
Exemple #18
0
def loc_create(request):
    '''Model form for creating a new location.'''
    if request.POST:
        form = LocationForm(request.POST, auto_id=True)
        if form.is_valid():
            form.save()
            # The problem w/ duplicate POST submissions is only a problem with traditional requests. With AJAX request can simply render the success page instead of redirecting to it.
            if request.is_ajax():
                return render(request, 'loc_list.html')
            else:
                return redirect('/loc_list/')
    else:
        form = LocationForm(auto_id=True)

    context = {}
    context.update(csrf(request))
    
    context['form'] = form

    return render_to_response('loc_create.html', context)
Exemple #19
0
def loc_edit(request, pk):
    '''Model form for editing a location. This location is acquired with a pk.'''
    location= Location.objects.get(pk = pk)
    if request.POST:
        form = LocationForm(request.POST, instance = location)
        if form.is_valid():
            form.save()
            if request.is_ajax():
                return render(request, 'loc_list.html')
            else:
                return redirect('/loc_list/')
    else:
        form = LocationForm(instance = location)

    context = {}
    context.update(csrf(request))
    context['form'] = form
    context['location'] = location
    context['pk'] = pk
    
    return render_to_response('loc_edit.html', context)
Exemple #20
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})
Exemple #21
0
def edit_location(req, area_id):
    location = get_object_or_404(Area, pk=area_id)
    if req.method == "POST":
        form = LocationForm(req.POST)
        if form.is_valid():
            saved = True

            area = Area.objects.get(pk=area_id)
            area.name = form.cleaned_data["name"]
            area.code = form.cleaned_data["code"]
            lat = form.cleaned_data["lat"]
            lon = form.cleaned_data["lon"]
            kind = form.cleaned_data["kind"]
            try:
                kind = get_object_or_404(AreaType, pk=int(kind))
                area.kind = kind
            except ValueError:
                pass
            if lat and lon:
                point = Point(latitude=lat, longitude=lon)
                point.save()
                area.location = point
            try:
                area.save()
            except IntegrityError:
                form.errors["code"] = "This code already exists"
                saved = False

            if form.cleaned_data["move_choice"]:
                target = form.cleaned_data["target"]
                position = form.cleaned_data["position"]

                try:
                    Area.tree.move_node(area, target, position)
                except InvalidMove:
                    form.errors["position"] = "This move is invalid"
                    saved = False

            if saved:
                form = LocationForm()
                return render_to_response(
                    "simple_locations/location_edit.html",
                    {"form": form, "nodes": Area.tree.all()},
                    context_instance=RequestContext(req),
                )
            else:
                return render_to_response(
                    "simple_locations/location_edit.html",
                    {"form": form, "item": location, "nodes": Area.tree.all()},
                    context_instance=RequestContext(req),
                )

        else:
            return render_to_response(
                "simple_locations/location_edit.html",
                {"form": form, "item": location},
                context_instance=RequestContext(req),
            )
    else:
        default_data = {}
        default_data["pk"] = location.pk
        default_data["name"] = location.name
        default_data["code"] = location.code
        default_data["move_choice"] = False
        if location.kind:
            default_data["kind"] = location.kind.pk
        if location.parent:
            default_data["target"] = location.parent
            default_data["position"] = "last-child"
        if location.location:
            default_data["lat"] = location.location.latitude
            default_data["lon"] = location.location.longitude
        form = LocationForm(default_data)
        return render_to_response(
            "simple_locations/location_edit.html",
            {"form": form, "nodes": Area.tree.all(), "item": location},
            context_instance=RequestContext(req),
        )
Exemple #22
0
def add_location(req, parent_id=None):
    nodes = Area.tree.all()

    if req.method == "POST":
        form = LocationForm(req.POST)
        if form.is_valid():
            name = form.cleaned_data["name"]
            code = form.cleaned_data["code"]
            lat = form.cleaned_data["lat"]
            lon = form.cleaned_data["lon"]
            target = form.cleaned_data["target"]
            position = form.cleaned_data["position"]
            kind = form.cleaned_data["kind"]

            area = Area(name=name, code=code)
            if lat and lon:
                location = Point(latitude=lat, longitude=lon)
                location.save()
                area.location = location
            try:
                kind = get_object_or_404(AreaType, pk=int(kind))
                area.kind = kind
            except ValueError:
                pass
            area.save()
            if form.cleaned_data["move_choice"]:
                try:
                    Area.tree.move_node(area, target, position)
                except InvalidMove:
                    pass
            form = LocationForm()

            return render_to_response(
                "simple_locations/location_edit.html",
                {"form": form, "nodes": nodes},
                context_instance=RequestContext(req),
            )
        else:
            form = LocationForm(req.POST)
            return render_to_response(
                "simple_locations/location_edit.html",
                {"form": form, "nodes": nodes},
                context_instance=RequestContext(req),
            )

    else:
        if parent_id:
            default_data = {}
            parent = get_object_or_404(Area, pk=parent_id)
            default_data["move_choice"] = True
            default_data["target"] = parent.pk
            default_data["position"] = "last-child"
            form = LocationForm(default_data)
            form._errors = ""

        else:
            form = LocationForm()

    return render_to_response(
        "simple_locations/location_edit.html", {"form": form, "nodes": nodes}, context_instance=RequestContext(req)
    )
Exemple #23
0
def add_edit_item(request, model_name, add_edit, edit_id):
    """Add/Edit page for the inventory"""
    if add_edit == "add":
        edit_id = None
    if _checkModel(model_name):
        directory = "asset_inventory/add_edit_Pages/"
        # Adding or Editing a Job
        if model_name == "Job":
            templateFile = directory + "Job.html"
            post_data = request.POST or None

            try:
                Job_Instance = Job.objects.get(pk=edit_id)
            except Job.DoesNotExist:
                Job_Instance = None
                if add_edit == "edit":
                    return HttpResponseRedirect(reverse("asset_inventory_add_edit_item", args=["Job", "add", "new"]))

            Job_Form = JobForm(post_data, instance=Job_Instance)

            if Job_Form.is_valid():
                Job_Occurance = Job_Form.save()
                return HttpResponseRedirect(reverse("asset_inventory_list_model", args=["Job"]))
            return render_to_response(templateFile, {"form": Job_Form}, context_instance=RequestContext(request))
        # Adding or Editing a Location
        elif model_name == "Location":
            templateFile = directory + "Location.html"
            post_data = request.POST or None

            try:
                Location_Instance = Location.objects.get(pk=edit_id)
            except Location.DoesNotExist:
                Location_Instance = None
                if add_edit == "edit":
                    return HttpResponseRedirect(
                        reverse("asset_inventory_add_edit_item", args=["Location", "add", "new"])
                    )

            Location_Form = LocationForm(post_data, instance=Location_Instance)

            if Location_Form.is_valid():
                Location_Occurance = Location_Form.save()
                return HttpResponseRedirect(reverse("asset_inventory_list_model", args=["Location"]))

            return render_to_response(templateFile, {"form": Location_Form}, context_instance=RequestContext(request))

        # Adding or Editing a Person
        elif model_name == "Person":
            templateFile = directory + "Person.html"
            post_data = request.POST or None

            try:
                Person_Instance = Person.objects.get(pk=edit_id)
            except Person.DoesNotExist:
                Person_Instance = None
                if add_edit == "edit":
                    return HttpResponseRedirect(reverse("asset_inventory_add_edit_item", args=["Person", "add", "new"]))

            Person_Form = PersonForm(post_data, instance=Person_Instance)

            if Person_Form.is_valid():
                Person_Occurance = Person_Form.save()
                return HttpResponseRedirect(reverse("asset_inventory_list_model", args=["Person"]))

            return render_to_response(templateFile, {"form": Person_Form}, context_instance=RequestContext(request))

        # Adding or Editing a Purchase
        elif model_name == "Purchase":
            templateFile = directory + "Purchase.html"
            post_data = request.POST or None

            try:
                Purchase_Instance = Purchase.objects.get(pk=edit_id)
            except Purchase.DoesNotExist:
                Purchase_Instance = None
                if add_edit == "edit":
                    return HttpResponseRedirect(
                        reverse("asset_inventory_add_edit_item", args=["Purchase", "add", "new"])
                    )

            Purchase_Form = PurchaseForm(post_data, instance=Purchase_Instance)

            if Purchase_Form.is_valid():
                Purchase_Occurance = Purchase_Form.save()
                return HttpResponseRedirect(reverse("asset_inventory_list_model", args=["Purchase"]))

            return render_to_response(templateFile, {"form": Purchase_Form}, context_instance=RequestContext(request))
        # Adding or Editing a Status
        elif model_name == "Status":
            templateFile = directory + "Status.html"
            post_data = request.POST or None

            try:
                Status_Instance = Status.objects.get(pk=edit_id)
            except Status.DoesNotExist:
                Status_Instance = None
                if add_edit == "edit":
                    return HttpResponseRedirect(reverse("asset_inventory_add_edit_item", args=["Status", "add", "new"]))

            Status_Form = StatusForm(post_data, instance=Status_Instance)

            if Status_Form.is_valid():
                Status_Occurance = Status_Form.save()
                return HttpResponseRedirect(reverse("asset_inventory_list_model", args=["Status"]))

            return render_to_response(templateFile, {"form": Status_Form}, context_instance=RequestContext(request))
        # Adding or Editing a Esign
        elif model_name == "Esign":
            templateFile = directory + "Esign.html"
            post_data = request.POST or None

            try:
                Esign_Instance = Esign.objects.get(pk=edit_id)
            except Esign.DoesNotExist:
                Esign_Instance = None
                if add_edit == "edit":
                    return HttpResponseRedirect(reverse("asset_inventory_add_edit_item", args=["Esign", "add", "new"]))

            Esign_Form = EsignForm(post_data, instance=Esign_Instance)

            if Esign_Form.is_valid():
                Esign_Occurance = Esign_Form.save()
                return HttpResponseRedirect(reverse("asset_inventory_list_model", args=["Esign"]))

            return render_to_response(templateFile, {"form": Esign_Form}, context_instance=RequestContext(request))
        # Adding or Editing a Device
        elif model_name == "Device":
            templateFile = directory + "Device.html"
            post_data = request.POST or None

            try:
                Device_Instance = Device.objects.get(pk=edit_id)
            except Device.DoesNotExist:
                Device_Instance = None
                if add_edit == "edit":
                    return HttpResponseRedirect(reverse("asset_inventory_add_edit_item", args=["Device", "add", "new"]))

            Device_Form = DeviceForm(post_data, instance=Device_Instance)

            if Device_Form.is_valid():
                Device_Occurance = Device_Form.save()
                return HttpResponseRedirect(reverse("asset_inventory_list_model", args=["Device"]))

            return render_to_response(templateFile, {"form": Device_Form}, context_instance=RequestContext(request))
    # This is a catch all response, if some unforseen error manages
    # to occur with the calling of add/edit pages
    else:
        render_to_response(reverse("homepage"))
Exemple #24
0
def create_Activity(request):
	if request.is_ajax():
		search_term = request.POST['yelp_term']
		# lat = request.session['cur_lat']
		# lng = request.session['cur_lng']
		lat = '42.056459'
		lng = '-87.675267'
		search_result = yelp_api.search_location(lat,lng,search_term)
		request.session['search_result'] = search_result
		return HttpResponse(json.dumps(search_result), content_type="application/json")

	elif request.method == 'POST':
		actForm = ActivityForm(request.POST)
		locForm = LocationForm(request.POST)

		# check for valid location
		if locForm.is_valid():
			street = request.POST.get('address')
			city = request.POST.get('city')
			state = request.POST.get('state')

			# get lat and long
			addr_str = street + ", " + city + ", " + state
			r = geocode(addr_str)
			lat = r['lat']
			lng = r['lng']

			m = locForm.save(commit=False)
			m.longitude = lng
			m.latitude = lat
			loc_name = m.location_name
			
			# get yelp rating and image
			rating,img_url = yelp_api.get_yelp_data(loc_name,lng,lat)
			print rating
			if rating == -1:
				m.location_rate = 0.0
			else:
				m.location_rate = rating
			if img_url == -1:
				m.location_img_url = "http://www.mountainmansocialmedia.com/_site/wp-content/themes/juiced/img/thumbnail-default.jpg"
			else:
				m.location_img_url = img_url
			
			location_obj = locForm.save()
			
			date = request.POST.get('date')
			start_time = request.POST.get('start_time')
			end_time = request.POST.get('end_time')
			name = request.POST.get('activity_name')
			max_num = request.POST.get('max_num_attendees')
			min_num = request.POST.get('min_num_attendees')
			skill = request.POST.get('skill_level')

			dt = datetime.strptime(date, "%m/%d/%Y")
			st = datetime.strptime(convert_Time(start_time), "%H:%M:%S")
			et = datetime.strptime(convert_Time(end_time), "%H:%M:%S")
			owner = request.user.onthemoveuser

			request.GET = request.GET.copy()
			request.GET['date'] = dt
			request.GET['start_time'] = st 
			request.GET['end_time'] = et 
			request.GET['activity_name'] = name
			request.GET['max_num_attendees'] = max_num
			request.GET['min_num_attendees'] = min_num
			request.GET['skill_level'] = skill
			request.GET['location_id'] = location_obj
			request.GET['owner_id'] = owner

			actForm1 = ActivityForm(request.GET)

			if actForm1.is_valid():
				x=actForm1.save(commit=False)
				x.location_id = location_obj
				x.owner_id = owner
				y = actForm1.save()
				print "here"
				return HttpResponseRedirect(reverse("Activities:details",args=(y.pk,)))
	else:
		actForm = ActivityForm()
		locForm = LocationForm()
	context = {}
	context.update(csrf(request))
	context['act_form'] = actForm
	context['loc_form'] = locForm
	context['path'] = request.path

	return render(request,"Activities/createActivity.html", context)
def edit_location(req, area_id):
    location = get_object_or_404(Area, pk=area_id)
    if req.method == 'POST':
        form = LocationForm(req.POST)
        if form.is_valid():
            saved = True

            area = Area.objects.get(pk=area_id)
            area.name = form.cleaned_data['name']
            area.code = form.cleaned_data['code']
            lat=form.cleaned_data['lat']
            lon=form.cleaned_data['lon']
            kind=form.cleaned_data['kind']
            try:
                kind = get_object_or_404(AreaType,pk=int(kind))
                area.kind = kind
            except ValueError:
                pass
            if lat and lon:
                point = Point(latitude=lat,longitude=lon)
                point.save()
                area.location = point
            try:
                area.save()
            except IntegrityError:
                form.errors['code'] = 'This code already exists'
                saved = False

            if form.cleaned_data['move_choice']:
                target = form.cleaned_data['target']
                position = form.cleaned_data['position']

                try:
                    area.parent=target
                    area.save()
                except InvalidMove:
                    form.errors['position'] = 'This move is invalid'
                    saved = False

            if saved:
                form = LocationForm()
                return render_to_response("simple_locations/location_edit.html", {"form":form, 'nodes':Area.tree.all()},
                                          context_instance=RequestContext(req))
            else:
                return render_to_response("simple_locations/location_edit.html",
                                          {"form":form, 'item': location, 'nodes':Area.tree.all()},
                                          context_instance=RequestContext(req))

        else:
            return render_to_response("simple_locations/location_edit.html",
                                      { 'form': form, 'item': location },
                                      context_instance=RequestContext(req))
    else:
        default_data = {}
        default_data['pk'] = location.pk
        default_data['name'] = location.name
        default_data['code'] = location.code
        default_data['move_choice'] = False
        if location.kind:
            default_data['kind'] = location.kind.pk
        if location.parent:
            default_data['target'] = location.parent
            default_data['position'] = 'last-child'
        if location.location:
            default_data['lat'] = location.location.latitude
            default_data['lon'] = location.location.longitude
        form = LocationForm(default_data)
        return render_to_response("simple_locations/location_edit.html",
                                  {'form':form, 'nodes':Area.tree.all(),'item':location},
                                  context_instance=RequestContext(req))