Exemple #1
0
 def post(self, request):
     form = self.form_class(request.POST)
     if form.is_valid():
         animal = Animal(
             name=form.cleaned_data.get("name"),
             age=form.cleaned_data.get("age"),
             weight=form.cleaned_data.get("weight"),
             height=form.cleaned_data.get("height"),
             spec_features=form.cleaned_data.get("spec_features"))
         arrival_date = form.cleaned_data.get("arrival_date")
         if arrival_date:
             animal.arrival_date = arrival_date
         animal.save()
         return HttpResponseRedirect(reverse('animals:animal'))
     else:
         return HttpResponse(status=400)
Exemple #2
0
def create_animal(request):
    name = request.GET.get('name')
    age = request.GET.get('age')
    breed = request.GET.get('breed')
    kind = request.GET.get('kind')
    description = request.GET.get('description')
    image_url = request.GET.get('image_url')
    try:
        animal = Animal(name=name,
                        age=age,
                        kind=kind,
                        breed=breed,
                        description=description,
                        image_url=image_url)
        animal.save()
        return HttpResponse('Created successfully')
    except:
        return HttpResponse('Not created')
Exemple #3
0
def refresh_from_csv(request):
    df = pd.read_csv('animal_data_set.csv', sep=';')

    for row in df.iloc:
        animal = Animal.from_dict(row)
        animal_inspection = AnimalInspection.from_dict(row)
        animal_capture = AnimalCapture.from_dict(row)
        AnimalDrug.from_dict(row)
        AnimalVacine.from_dict(row)
        shelter = Shelter.from_dict(row)
        shelter_staff = ShelterStaff.from_dict(row)

        AnimalInShelter.from_dict(row, animal_capture, shelter, shelter_staff)

    return JsonResponse({'error': 0})
Exemple #4
0
def process_data(request):
    if request.method == 'POST':
        sender = request.POST.get('sender')
        recipient = request.POST.get('recipient')
        subject = request.POST.get('subject')

        for key in request.FILES:
            data_file = request.FILES[key]
            contents = unicode_csv_reader(data_file, dialect='excel',
                delimiter=',')
            header = contents.next()
            g = geocoders.Google('AIzaSyAZoNPSlRTETltbmJvgYYqol0SLAVBgKs')
            for row in contents:
                animal_id = row[3]
                if not Animal.objects.filter(animal_id=animal_id).exists():
                    location = row[1]
                    location_found = True
                    try:
                        (place, point) = g.geocode(location)
                    except:
                        location_found = False
                    if location_found:
                        a = Animal()
                        a.animal_id = animal_id
                        intake_date = row[0]
                        dt = datetime.strptime(intake_date.strip(), "%m/%d/%y")
                        a.intake_date = date(year=dt.year, month=dt.month,
                            day=dt.day)
                        a.location = location
                        a.intake_condition = row[2]
                        a.animal_type = row[4]
                        sex = {'UNKNOWN': 'U',
                                'MALE': 'M',
                                'FEMALE': 'F'}
                        a.sex = sex[row[5]]
                        a.spayed = True if row[6] == 'YES' else False
                        a.name = row[7]
                        a.age = int(float(row[8].replace(',', '')))
                        a.description = row[9]
                        a.intake_total = 1
                        a.geometry = "POINT (%s %s)" % (point[1], point[0])
                        a.photo = ''
                        a.save()
    return HttpResponse('cool')
Exemple #5
0
def populate(row):
    animal_id = row[3]
    image_updated = True if row[13] == 'New Image Available' else False
    print "starting to process  %s" % animal_id
    if not Animal.objects.filter(animal_id=animal_id).exists():
        location = row[1]
        location_found = True
        try:
            (place, point) = g.geocode(location)
        except:
            location_found = False
            print 'location not found'
        if location_found:
            a = Animal()
            a.animal_id = animal_id
            intake_date = row[0]
            dt = datetime.strptime(intake_date.strip(), "%m/%d/%Y")
            a.intake_date = date(year=dt.year, month=dt.month, day=dt.day)
            a.location = location
            a.intake_condition = row[2]
            a.animal_type = row[4]
            sex = {'UNKNOWN': 'U', 'MALE': 'M', 'FEMALE': 'F'}
            a.sex = sex[row[5]]
            a.spayed = True if row[6] == 'YES' else False
            a.name = row[7]
            a.age = int(float(row[8].replace(',', '')))
            a.description = row[9]
            a.intake_total = 1
            a.outcome_type = row[10]
            outcome_date = row[11]
            if outcome_date:
                odt = datetime.strptime(intake_date.strip(), "%m/%d/%Y")
                a.outcome_date = date(year=odt.year,
                                      month=odt.month,
                                      day=odt.day)
            a.transferred_to = row[12]
            a.geometry = "POINT (%s %s)" % (point[1], point[0])
            a.photo = ''
            a.save()
            print a
    elif image_updated:
        print 'marking %s as having photo updated' % animal_id
        a = Animal.objects.get(animal_id=animal_id)
        a.photo_updated = image_updated
        a.save()
    return 'finished processing %s' % (animal_id)
Exemple #6
0
    def handle(self, *args, **options):
        data = []
        with open('TF.csv', 'r') as csvfile:
            reader = csv.DictReader(csvfile, delimiter=',')
            for row in reader:
                data.append(row)

        for i in data:
            pet_id = i['id']
            nickname = i['Кличка']
            url = i['Ссылка на профиль']
            shelter = i['Приют']
            breed = i['Порода']
            kind = i['Вид']
            date_of_birth = i['Дата рождения']
            sex = i['Пол']
            favorite = i['В избранном']
            home = i['Уже дома']
            take_home = i['Забрать домой']
            walk = i['Погулять']
            city = i['Город']

            if not City.objects.filter(city=city).exists():
                print(f'Добавляю {city}')
                city_animals = City(city=city)
                city_animals.save()
            city = City.objects.get(city=city)

            if not Shelter.objects.filter(title=shelter).exists():
                print(f'Добавляю приют {shelter}')
                shelter_animal = Shelter(title=shelter)
                shelter_animal.save()
            shelter = Shelter.objects.get(title=shelter, )

            if not Breed.objects.filter(title=breed).exists():
                print(f'Добавляю породу {breed}')
                breed_animal = Breed(title=breed)
                breed_animal.save()
            breed = Breed.objects.get(title=breed)

            if not Kind.objects.filter(title=kind).exists():
                print(f'Добавляю вид животного {kind}')
                kind_animal = Kind(title=kind)
                kind_animal.save()
            kind = Kind.objects.get(title=kind)

            if not Animal.objects.filter(pet_id=pet_id).exists():
                print(f'Добавляю животное {nickname} вида {kind}')
                animal = Animal(
                    pet_id=pet_id,
                    nickname=nickname,
                    url=url,
                    shelter=shelter,
                    breed=breed,
                    kind=kind,
                    date_of_birth=date_of_birth,
                    sex=sex,
                    favorite=favorite,
                    home=home,
                    take_home=take_home,
                    walk=walk,
                    city=city,
                )
                animal.save()

        return '--Все животные добавленны--'
Exemple #7
0
def populate(row):
    animal_id = row[3]
    image_updated = True if row[13] == 'New Image Available' else False
    print "starting to process  %s" % animal_id
    if not Animal.objects.filter(animal_id=animal_id).exists():
        location = row[1]
        location_found = True
        try:
            address, (latitude, longitude) = g.geocode(location)
        except:
            location_found = False
            print 'location not found'
        if location_found:
            a = Animal()
            a.animal_id = animal_id
            intake_date = row[0]
            dt = datetime.strptime(intake_date.strip(), "%m/%d/%Y")
            a.intake_date = date(year=dt.year, month=dt.month, day=dt.day)
            a.location = location
            a.intake_condition = row[2]
            a.animal_type = row[4]
            sex = {'UNKNOWN': 'U', 'MALE': 'M', 'FEMALE': 'F'}
            a.sex = sex[row[5]]
            a.spayed = True if row[6] == 'YES' else False
            a.name = row[7]
            a.age = int(float(row[8].replace(',', '')))
            a.description = row[9]
            a.intake_total = 1
            a.outcome_type = row[10]
            outcome_date = row[11]
            if outcome_date:
                odt = datetime.strptime(intake_date.strip(), "%m/%d/%Y")
                a.outcome_date = date(year=odt.year, month=odt.month,
                                      day=odt.day)
            a.transferred_to = row[12]
            a.geometry = "POINT (%s %s)" % (longitude, latitude)
            a.photo = ''
            a.save()
            print a
    elif image_updated:
        print 'marking %s as having photo updated' % animal_id
        a = Animal.objects.get(animal_id=animal_id)
        a.photo_updated = image_updated
        a.save()
    return 'finished processing %s' % (animal_id)
Exemple #8
0
def run():
    csv_file = open("%s/../fixtures/DataSet1.csv" % os.path.dirname(__file__))
    contents = csv.reader(csv_file, dialect='excel', delimiter=',')
    header = contents.next()
    g = geocoders.Google('AIzaSyAZoNPSlRTETltbmJvgYYqol0SLAVBgKs')
    for row in contents:
        animal_id = row[3]
        if not Animal.objects.filter(animal_id=animal_id).exists():
            location = row[1]
            location_found = True
            try:
                (place, point) = g.geocode(location)
            except:
                location_found = False
            if location_found:
                a = Animal()
                a.animal_id = animal_id
                intake_date = row[0]
                dt = datetime.strptime(intake_date.strip(), "%m/%d/%y")
                a.intake_date = date(year=dt.year, month=dt.month, day=dt.day)
                a.location = location
                a.intake_condition = row[2]
                a.animal_type = row[4]
                sex = {'UNKNOWN': 'U',
                        'MALE': 'M',
                        'FEMALE': 'F'}
                a.sex = sex[row[5]]
                a.spayed = True if row[6] == 'YES' else False
                a.name = row[7]
                a.age = int(float(row[8].replace(',', '')))
                a.description = row[9]
                a.intake_total = 1
                a.geometry = "POINT (%s %s)" % (point[1], point[0])
                a.photo = ''
                a.save()
                print a
Exemple #9
0
    def handle(self, *args, **options):
        lines_count = 0
        fname = options['filename'][0]
        xl = xlrd.open_workbook(fname) # Open the workbook
#        for sheet in (2,0):
        for sheet in (0,):
            print('Sheet #' + str(sheet))
            xl_sheet = xl.sheet_by_index(sheet) # grab sheet

            num_cols = xl_sheet.ncols   # Number of columns
            for row_idx in range(10, xl_sheet.nrows):    # Iterate through rows
                print('.', end ="", flush=True)
#                print ('-'*40)
#                print ('Row: %s' % row_idx)   # Print row number
#                for col_idx in range(0, num_cols):  # Iterate through columns
#                    cell_obj = xl_sheet.cell(row_idx, col_idx)  # Get cell object by row, col
#                    print ('Column: [%s] cell_obj: [%s]' % (col_idx, cell_obj))

                a = Animal()

#                a.pk = int(xl_sheet.cell(row_idx, 0).value)
                a.entry_date = xldate_as_datetime(xl_sheet.cell(row_idx, 1).value, xl.datemode)
                a.database_id = str(xl_sheet.cell(row_idx, 2).value).strip()
                a.lab_id = str(xl_sheet.cell(row_idx, 3).value).strip()
                a.day_of_birth = xldate_as_datetime(xl_sheet.cell(row_idx, 4).value, xl.datemode)
                try:
                    age = int(xl_sheet.cell(row_idx, 5).value)
                except ValueError:
                    age = 0
                a.line = str(xl_sheet.cell(row_idx, 6).value).strip()
                mutation_1 = str(xl_sheet.cell(row_idx, 7).value).strip()
                grade_1 = str(xl_sheet.cell(row_idx, 8).value).strip()
                mutation_2 = str(xl_sheet.cell(row_idx, 9).value).strip()
                grade_2 = str(xl_sheet.cell(row_idx, 10).value).strip()
                mutation_3 = str(xl_sheet.cell(row_idx, 11).value).strip()
                grade_3 = str(xl_sheet.cell(row_idx, 12).value).strip()
                mutation_4 = str(xl_sheet.cell(row_idx, 13).value).strip()
                grade_4 = str(xl_sheet.cell(row_idx, 14).value).strip()
                a.sex = str(xl_sheet.cell(row_idx, 15).value).strip().lower() or 'u'
                a.licence_number = str(xl_sheet.cell(row_idx, 17).value).strip()
                responsible_person = str(xl_sheet.cell(row_idx, 18).value).strip().strip()
                a.available_from = xldate_as_datetime(xl_sheet.cell(row_idx, 19).value, xl.datemode)
                a.available_to = xldate_as_datetime(xl_sheet.cell(row_idx, 20).value, xl.datemode)
                a.new_owner = str(xl_sheet.cell(row_idx, 21).value).strip()
                a.animal_type = 'mouse'
#                a.organ_type = 'whole animal'

                a.mutations =  mutation_1 + ' ' + grade_1 + '\n' + \
                            mutation_2 + ' ' + grade_2 + '\n' + \
                            mutation_3 + ' ' + grade_3 + '\n' + \
                            mutation_4 + ' ' + grade_4 + '\n'

                location_name = str(xl_sheet.cell(row_idx, 16).value).strip()
                try:
                    a.location = Location.objects.get(name=location_name)
                except Location.DoesNotExist:
                    loc = Location(name=location_name)
                    loc.save()
                    a.location = loc

                a.responsible_person = Person.objects.get(Q(email=responsible_person.lower()) | Q(name__iexact=responsible_person.lower()))
                try:
                    Animal.objects.get(entry_date=a.entry_date,
                                       day_of_birth=a.day_of_birth,
                                       available_from=a.available_from,
                                       available_to=a.available_to,
                                       line=a.line,
                                       database_id=a.database_id,
                                       lab_id=a.lab_id,
                                       location=a.location,
                                       sex=a.sex)
                except Animal.DoesNotExist:
                    a.save()
                    lines_count += 1
            print()

        self.stdout.write(self.style.SUCCESS('Successfully imported %i lines.' % lines_count))
    def handle(self, *args, **options):
        lines_count = 0
        fname = options['filename'][0]
        xl = xlrd.open_workbook(fname)  # Open the workbook
        #        for sheet in (2,0):
        for sheet in (0, ):
            print('Sheet #' + str(sheet))
            xl_sheet = xl.sheet_by_index(sheet)  # grab sheet

            num_cols = xl_sheet.ncols  # Number of columns
            for row_idx in range(1, xl_sheet.nrows):  # Iterate through rows
                print('.', end="", flush=True)
                #                print ('-'*40)
                #                print ('Row: %s' % row_idx)   # Print row number
                #                for col_idx in range(0, num_cols):  # Iterate through columns
                #                    cell_obj = xl_sheet.cell(row_idx, col_idx)  # Get cell object by row, col
                #                    print ('Column: [%s] cell_obj: [%s]' % (col_idx, cell_obj))

                a = Animal()

                #                a.pk = int(xl_sheet.cell(row_idx, 0).value)
                #a.entry_date = xldate_as_datetime(xl_sheet.cell(row_idx, 1).value, xl.datemode)
                #a.available_from = xldate_as_datetime(xl_sheet.cell(row_idx, 0).value, xl.datemode) # angeboten am
                a.animal_type = 'fish'
                a.available_from = datetime.today().date()
                a.comment = str(xl_sheet.cell(row_idx,
                                              0).value).strip()  # Kommentar
                a.sex = str(xl_sheet.cell(
                    row_idx, 1).value).strip().lower() or 'u'  # Geschlecht
                a.line = str(xl_sheet.cell(row_idx,
                                           2).value).strip()  # Zuchtlinie
                a.lab_id = str(xl_sheet.cell(row_idx,
                                             3).value).strip()  # Käfig-ID
                a.database_id = str(xl_sheet.cell(row_idx,
                                                  4).value).strip()  # Tier-ID
                a.day_of_birth = xldate_as_datetime(
                    xl_sheet.cell(row_idx, 5).value, xl.datemode)  #Geb.
                a.amount = int(xl_sheet.cell(row_idx, 7).value)  # Anzahl
                a.licence_number = str(xl_sheet.cell(
                    row_idx, 11).value).strip()  # Aktenzeichen
                location_name = str(xl_sheet.cell(row_idx,
                                                  13).value).strip()  # Raum
                responsible_person = str(xl_sheet.cell(
                    row_idx,
                    16).value).strip().strip()  # Verantwortliche Person
                #a.available_from = xldate_as_datetime(xl_sheet.cell(row_idx, 19).value, xl.datemode)
                a.available_to = xldate_as_datetime(
                    xl_sheet.cell(row_idx, 22).value, xl.datemode)
                #a.new_owner = str(xl_sheet.cell(row_idx, 21).value).strip()

                #                a.organ_type = 'whole animal'

                #a.mutations =

                try:
                    a.location = Location.objects.get(name=location_name)
                except Location.DoesNotExist:
                    loc = Location(name=location_name)
                    loc.save()
                    a.location = loc

                a.responsible_person = Person.objects.get(
                    Q(email=responsible_person.lower())
                    | Q(name__iexact=responsible_person.lower()))
                try:
                    Animal.objects.get(entry_date=a.entry_date,
                                       day_of_birth=a.day_of_birth,
                                       available_from=a.available_from,
                                       available_to=a.available_to,
                                       line=a.line,
                                       database_id=a.database_id,
                                       lab_id=a.lab_id,
                                       location=a.location,
                                       sex=a.sex)
                except Animal.DoesNotExist:
                    a.save()
                    lines_count += 1
            print()

        self.stdout.write(
            self.style.SUCCESS('Successfully imported %i lines.' %
                               lines_count))
Exemple #11
0
def populate(row):
    animal_id = row[3]
    image_updated = True if row[13] == "New Image Available" else False
    print "starting to process  %s" % animal_id
    if not Animal.objects.filter(animal_id=animal_id).exists():
        location = row[1]
        location_found = True
        try:
            (place, point) = g.geocode(location)
        except:
            location_found = False
            print "location not found"
        if location_found:
            a = Animal()
            a.animal_id = animal_id
            intake_date = row[0]
            dt = datetime.strptime(intake_date.strip(), "%m/%d/%Y")
            a.intake_date = date(year=dt.year, month=dt.month, day=dt.day)
            a.location = location
            a.intake_condition = row[2]
            a.animal_type = row[4]
            sex = {"UNKNOWN": "U", "MALE": "M", "FEMALE": "F"}
            a.sex = sex[row[5]]
            a.spayed = True if row[6] == "YES" else False
            a.name = row[7]
            a.age = int(float(row[8].replace(",", "")))
            a.description = row[9]
            a.intake_total = 1
            a.outcome_type = row[10]
            outcome_date = row[11]
            if outcome_date:
                odt = datetime.strptime(intake_date.strip(), "%m/%d/%Y")
                a.outcome_date = date(year=odt.year, month=odt.month, day=odt.day)
            a.transferred_to = row[12]
            a.geometry = "POINT (%s %s)" % (point[1], point[0])
            a.photo = ""
            a.save()
            print a
    elif image_updated:
        print "marking %s as having photo updated" % animal_id
        a = Animal.objects.get(animal_id=animal_id)
        a.photo_updated = image_updated
        a.save()
    return "finished processing %s" % (animal_id)
def create_from_landing(request, format=None):
    data = request.data

    ## Serializers created with django-rest-framework need csrf and CORS protection
    ## This is quick and dirty till I build authentication
    zooInfo = data['zoo']
    z, created = Zoo.objects.get_or_create(name=zooInfo['name'])
    if created:
        z.website = zooInfo['website']
        # Address lines are needed functions but I don't want to include these fields on the main form
        z.city = 'UPDATE ADDRESS FIELDS'
        z.st = 'CO'
        z.zip = '80205'
        z.country = 'US'
    z.save()

    userInfo = data['user']
    u, created = User.objects.get_or_create(email=userInfo['email'],
                                            first_name=userInfo['first_name'],
                                            last_name=userInfo['last_name'])
    u.zoo = z
    u.save()

    animals = data['animals']
    for e in animals:
        if e['dob'] == '':
            dob = None
        else:
            dob = e['dob']

        a = Animal(
            zoo=z,
            user=u,
            name=e['name'],
            date_of_birth=dob,
            bio=e['bio'],
        )
        species, created = Species.objects.get_or_create(
            common_name=e['species'])
        species.save()
        a.species = species
        a.save()

        # Create animal-image relationships by looking up the uuid of the image (auto uploaded by same form)
        for i in e['images']:
            # Using get_or_create here allows finding the image to fail gracefully
            # If it was created, then it's obviously not what we're looking for
            img, created = Image.objects.get_or_create(uuid=i['uuid'])
            if not created:
                a.images.add(img)

        for t in e['toys']:
            # Create new toy with user submitted URL
            # Set default price as 10 until it is manually set by admins
            if t['url'] != '':
                try:
                    toy = Toy.objects.get(url=t['url'])
                # get_or_create wasn't working correctly since 'name' is required
                except Toy.DoesNotExist:
                    toy = Toy(url=t['url'],
                              name='Default Toy Name',
                              price=10,
                              brand='')
                    toy.save()

                wish = Wish(toy=toy, animal=a, fund_amount=toy.price)
                wish.save()

        # Set the first wish as active
        w = a.wish_set.first()
        w.active = True
        w.save()
        a.save()

    return JsonResponse(data, safe=False)