Beispiel #1
0
class IndexView(View):
    template_name = 'web/index.html'
    context_object_name = 'items_list'
    kennels_handler = KennelsHandler()

    def get(self, request, *args, **kwargs):
        registered_user = False
        if request.user.is_authenticated:
            registered_user = True
        context = dict(registered_user=registered_user)

        return render(request, 'web/index.html', context=context)
Beispiel #2
0
class KennelRUDView(generics.RetrieveUpdateDestroyAPIView):
    handler = KennelsHandler()

    lookup_field = 'slug'
    serializer_class = KennelSerializer
    permission_classes = [IsOwnerOrReadOnly]

    def get_queryset(self):
        return self.handler.get_all_by_params(params={}, order_by='title')

    def get_serializer_context(self, *args, **kwargs):
        return {"request": self.request}
Beispiel #3
0
class KennelTest(TestCase):
    handler = KennelsHandler()

    def test_create_model(self):
        kennel = self.handler.create(dict(title="test 1", type="dogs"))
        self.assertEqual(kennel.title, "test 1")
        self.assertEqual(kennel.type, "dogs")
        self.assertEqual(kennel.slug, "test_1")

    def test_get_by_slug(self):
        kennel_1 = self.handler.create(dict(title="test 1", type="dogs"))
        kennel_2 = self.handler.get_by_slug("test_1")

        self.assertEqual(kennel_1, kennel_2)
        self.assertEqual(kennel_1.title, kennel_2.title)

    def test_get_by_id(self):

        kennel_1 = self.handler.create(dict(title="test 1", type="dogs"))

        kennel_2 = self.handler.get_by_id(1)

        self.assertEqual(kennel_1, kennel_2)
        self.assertEqual(kennel_1.id, kennel_2.id)
        self.assertEqual(kennel_1.title, kennel_2.title)

    def test_make_slug(self):

        slug = self.handler.make_slug('test_1')

        self.assertEqual(slug, "test_1")

        kennel = self.handler.create(dict(title="test 2", type="dogs"))
        slug_2 = self.handler.make_slug('test 2')
        self.assertNotEqual(slug_2, "test_2")

    def test_delete(self):
        kennel_1 = self.handler.create(dict(title="test 1", type="dogs"))
        kennel_2 = self.handler.create(dict(title="test 2", type="dogs"))

        self.handler.delete(kennel_1.slug)

        kennel_1 = self.handler.get_by_slug(kennel_1.slug)
        kennel_2 = self.handler.get_by_slug(kennel_2.slug)

        self.assertTrue(kennel_1.is_deleted)
        self.assertFalse(kennel_2.is_deleted)
Beispiel #4
0
class KennelSerializer(serializers.ModelSerializer):
    url = serializers.SerializerMethodField(read_only=True)
    owner = serializers.SerializerMethodField(read_only=True)
    owner_name = serializers.ReadOnlyField(source='owner.username')
    # country_club = serializers.SerializerMethodField(source='country_club.id')

    handler = KennelsHandler()

    read_only_field = ['id']

    class Meta:
        model = Kennel
        fields = [
            'id', 'url', 'title', 'type', 'reg_number', 'about', 'url',
            'cover', 'slug', 'address', 'timezone', 'skype', 'facebook',
            'site', 'owner', 'owner_name', 'country_club', 'country'
        ]

    def get_url(self, obj):
        request = self.context.get('request')
        return obj.get_api_url(request=request)

    def validate_slug(self, value):
        slug = value.replace(' ', '_')
        kennels = self.handler.get_by_slug(slug)
        if kennels and self.instance and kennels.id != int(self.instance.id):
            raise serializers.ValidationError(
                _(u'This page address is already in use. Try another one'))
        return slug

    def create(self, validated_data):
        """
        Create and return a new `Kennel` instance, given the validated data.
        """
        validated_data['slug'] = self.handler.make_slug(
            validated_data.get('title'))
        return Kennel.objects.create(**validated_data)

    def get_owner(self, obj):
        request = self.context.get('request')
        if request and request.user.is_authenticated:
            if obj.owner == request.user:
                return True
        return False
Beispiel #5
0
class KennelAPIView(generics.ListCreateAPIView):
    handler = KennelsHandler()

    lookup_field = 'slug'
    serializer_class = KennelSerializer
    pagination_class = KennelPageNumberPagination

    def get_queryset(self):
        query = self.request.GET
        params = dict()
        for key, value in query.items():
            params[key] = value
        return self.handler.get_all_by_params(params=params,
                                              order_by='-created_at')

    def perform_create(self, serializer):
        serializer.save(owner=self.request.user)

    def get_serializer_context(self, *args, **kwargs):
        return {"request": self.request}
Beispiel #6
0
class AnimalsHandler(BaseHandler):
    model_instance = BaseAnimal
    kennels_handler = KennelsHandler()
    breeds_handler = BreedsHandler()

    def create_from_kennel(self, data, user):
        kennel_live = self.kennels_handler.get_by_slug(data.get('kennel_live'))
        data['kennel_live'] = kennel_live
        data['is_owner'] = True
        data['owner'] = user
        data['slug'] = self.make_slug(data.get('full_name'))
        animal = self.model_instance(**data)
        animal.save()
        return animal

    def get_by_slug(self, slug):
        return self.model_instance.objects.filter(slug=slug, is_deleted=False).order_by('-created_at').first()

    def get_all_by_params(self, params, order_by='-created_at'):
        # params['is_deleted'] = False
        return self.model_instance.objects.filter(**params, is_deleted=False).order_by(order_by)

    def get_all_by_params_json(self, params, order_by='-created_at'):
        if params.get('kennel_live', None):
            params['kennel_live'] = self.kennels_handler.get_by_slug(params.get('kennel_live'))
        if params.get('kennel_of_birth', None):
            params['kennel_of_birth'] = self.kennels_handler.get_by_slug(params.get('kennel_of_birth'))
        animals = self.get_all_by_params(params, order_by)
        return [self.humanize_animal(animal) for animal in animals]

    def humanize_animal(self, animal):
        animal_data = dict()
        animal_data['id'] = animal.id
        animal_data['full_name'] = animal.full_name
        animal_data['home_name'] = animal.home_name
        animal_data['type'] = animal.humanize_type()
        animal_data['gender'] = animal.humanize_gender()
        if animal.birthday:
            animal_data['birthday'] = animal.birthday.strftime("%d.%m.%Y")
        if animal.deathday:
            animal_data['deathday'] = animal.deathday.strftime("%d.%m.%Y")
        if animal.mother:
            animal_data['mother_slug'] = animal.mother.slug
            animal_data['mother'] = animal.mother.full_name

        if animal.father:
            animal_data['father_slug'] = animal.father.slug
            animal_data['father'] = animal.father.full_name

        if animal.breed:
            animal_data['breed'] = animal.breed.title

        if animal.kennel_of_birth:
            animal_data['kennel_of_birth_slug'] = animal.kennel_of_birth.slug
            animal_data['kennel_of_birth_title'] = animal.kennel_of_birth.title

        if animal.kennel_live:
            animal_data['kennel_live_slug'] = animal.kennel_live.slug
            animal_data['kennel_live_title'] = animal.kennel_live.title

        animal_data['color'] = animal.color
        animal_data['height'] = animal.height
        animal_data['registry'] = animal.registry
        animal_data['pedigree'] = animal.pedigree
        animal_data['entitlements'] = animal.entitlements
        animal_data['achievements'] = animal.achievements
        animal_data['elbow_ed'] = animal.elbow_ed
        animal_data['hip_hd'] = animal.hip_hd
        animal_data['tattoo'] = animal.tattoo
        animal_data['dna_data'] = animal.dna_data
        animal_data['microchip'] = animal.microchip
        animal_data['about'] = animal.about
        animal_data['slug'] = animal.slug
        animal_data['is_owner'] = animal.is_owner
        if animal.photo:
            animal_data['photo'] = animal.photo.url

        return animal_data

    def edit_animal(self, animal, data, user):
        for key, value in data.items():
            if value is not None:
                if key == 'birthday' or key == 'deathday':
                    if value != '':
                        animal.__dict__[key] = datetime.datetime.strptime(value, '%d.%m.%Y')
                elif key == 'mother_slug' or key == 'father_slug':
                    # TODO: check if works Foreign Key update
                    item = self.get_by_slug(value)
                    animal.__dict__[key] = item

                elif key == 'breed':
                    item = self.breeds_handler.get_by_slug(value)
                    animal.breed = item

                elif key == 'is_owner':
                    animal.__dict__[key] = value
                    animal.__dict__['owner'] = user

                elif key == 'kennel_of_birth_slug' or key == 'kennel_live_slug':
                    kennel = self.kennels_handler.get_by_slug(value)
                    animal.__dict__[key] = kennel

                else:
                    animal.__dict__[key] = value

        animal.save()
        return animal

    def make_slug(self, full_name):
        slug = full_name.replace(' ', '_')

        while True:
            animal = self.get_by_slug(slug)
            if animal:
                slug += str(random.randint(0, 10000))
            else:
                return slug

    def dump_animals(self, kennel_data, kennel):
        animals = self.get_all_by_params(dict(kennel_live=kennel,
                                              deathday=None,
                                              gender=self.model_instance.GENDER_MALE, is_deleted=False))
        kennel_data['male'] = self.dump_items(animals)

        animals = self.get_all_by_params(dict(kennel_live=kennel,
                                              deathday=None,
                                              gender=self.model_instance.GENDER_FEMALE, is_deleted=False))
        kennel_data['female'] = self.dump_items(animals)

        animals = self.get_all_by_params(dict(kennel_of_birth=kennel))
        kennel_data['offsprings'] = self.dump_items(animals)

        breeds = []
        animals = kennel_data['male'] + kennel_data['female']
        for animal in animals:
            if animal.get('breed') not in animals and animal.get('breed'):
                breeds.append(animal.get('breed'))
        kennel_data['breeds'] = ', '.join(breeds)

        return kennel_data

    def dump_items(self, animals):
        return [self.humanize_animal(animal) for animal in animals]
Beispiel #7
0
class EditAnimalForm(forms.Form):
    handler = AnimalsHandler()
    kennels_handler = KennelsHandler()
    breeds_handler = BreedsHandler()

    id = forms.IntegerField(required=False)
    home_name = forms.CharField(required=False)
    full_name = forms.CharField(required=False)
    birthday = forms.CharField(required=False)
    deathday = forms.CharField(required=False, label=_(u'Date of death'))
    kennel_of_birth_slug = forms.CharField(required=False,
                                           widget=forms.HiddenInput)
    kennel_of_birth_title = forms.CharField(required=False
                                            # , widget=forms.Select
                                            )
    kennel_live_slug = forms.CharField(required=False,
                                       widget=forms.HiddenInput)
    kennel_live_title = forms.CharField(required=False,
                                        # widget=forms.Select
                                        )
    mother = forms.CharField(required=False
                             # , widget=forms.Select
                             )
    mother_slug = forms.CharField(required=False, widget=forms.HiddenInput)
    father = forms.CharField(required=False
                             # , widget=forms.Select
                             )
    father_slug = forms.CharField(required=False, widget=forms.HiddenInput)

    breed = forms.CharField(required=False, widget=forms.Select)
    color = forms.CharField(required=False)
    height = forms.CharField(required=False)
    pedigree = forms.URLField(required=False)
    registry = forms.CharField(required=False, label=_(u'Registry №'))
    entitlements = forms.CharField(required=False)
    gender = forms.ChoiceField(required=False,
                               choices=handler.model_instance.GENDER_CHOICES,
                               widget=forms.Select)
    achievements = forms.CharField(required=False)
    elbow_ed = forms.CharField(required=False)
    hip_hd = forms.CharField(required=False)
    tattoo = forms.CharField(required=False)
    dna_data = forms.CharField(required=False, label=_(u'DNA data'))
    microchip = forms.CharField(required=False)
    photo = forms.IntegerField(required=False)
    about = forms.CharField(required=False, widget=forms.Textarea)
    slug = forms.CharField(required=False, label=_(u'Page address'))
    is_owner = forms.BooleanField(required=False, label=_(u'I am owner'))
    type = forms.CharField(required=False)

    def __init__(self, *args, **kwargs):
        type = kwargs.pop('type', None)
        super(EditAnimalForm, self).__init__(*args, **kwargs)
        kennels = [('', '')]
        params = dict(type=type)
        for kennel in self.kennels_handler.get_all_by_params(params,
                                                             order_by='title'):
            kennels.append((kennel.slug, kennel.title))
        females = [('', '')]
        params = dict(gender=self.handler.model_instance.GENDER_FEMALE)
        for animal in self.handler.get_all_by_params(params,
                                                     order_by='full_name'):
            females.append(
                (animal.slug,
                 animal.full_name if animal.full_name else animal.home_name))

        males = [('', '')]
        params = dict(gender=self.handler.model_instance.GENDER_MALE)
        for animal in self.handler.get_all_by_params(params=params,
                                                     order_by='full_name'):
            males.append(
                (animal.slug,
                 animal.full_name if animal.full_name else animal.home_name))

        breeds = [('', '')]
        breeds.extend(
            list(self.breeds_handler.get_breeds_choices_by_type(type)))
        self.fields['kennel_of_birth_title'].widget.choices = kennels
        self.fields['kennel_live_title'].widget.choices = kennels
        self.fields['mother'].widget.choices = females
        self.fields['father'].widget.choices = males
        self.fields['breed'].widget.choices = breeds
        self.fields['pedigree'].widget.attrs['placeholder'] = _(
            u'link to pedigree')
        self.fields['mother'].widget.attrs['class'] = 'select-input-field'
        self.fields['mother'].widget.attrs['data-gender'] = 'female'
        self.fields['mother'].widget.attrs['data-type'] = 'animal'
        self.fields['mother'].widget.attrs['data-animal-type'] = type
        self.fields['mother'].widget.attrs['autocomplete'] = 'off'
        self.fields['father'].widget.attrs['class'] = 'select-input-field'
        self.fields['father'].widget.attrs['data-gender'] = 'male'
        self.fields['father'].widget.attrs['data-type'] = 'animal'
        self.fields['father'].widget.attrs['data-animal-type'] = type
        self.fields['father'].widget.attrs['autocomplete'] = 'off'
        # self.fields['kennel_live'].widget.attrs['class'] = 'select-input-field'
        # self.fields['kennel_live'].widget.attrs['data-type'] = 'kennel'
        # self.fields['kennel_live'].widget.attrs['data-animal-type'] = type
        # self.fields['kennel_live'].widget.attrs['autocomplete'] = 'off'
        # self.fields['kennel_of_birth'].widget.attrs['class'] = 'select-input-field'
        # self.fields['kennel_of_birth'].widget.attrs['data-type'] = 'kennel'
        # self.fields['kennel_of_birth'].widget.attrs['data-animal-type'] = type
        # self.fields['kennel_of_birth'].widget.attrs['autocomplete'] = 'off'

    def clean_slug(self):

        cleaned_data = super(EditAnimalForm, self).clean()
        slug = cleaned_data.get('slug')
        slug = slug.replace(' ', '_')

        params = dict(slug=slug)
        animals = self.handler.get_all_by_params(params=params,
                                                 order_by='created_at')
        if animals and animals[0].id != cleaned_data.get('id'):
            raise ValueError(
                _(u'This page address is already in use. Try another one'))
        return slug
Beispiel #8
0
class LittersHandler(BaseHandler):
    model_instance = Litter
    kennels_handler = KennelsHandler()
    news_handler = NewsHandler()
    animals_handler = AnimalsHandler()
    breeds_handler = BreedsHandler()

    def create_litter(self, data):
        kennel = self.kennels_handler.get_by_slug(data.get('kennel'))
        litter = self.model_instance(litter=data.get('litter'),
                                     kennel=kennel,
                                     slug=self.make_slug(
                                         data.get('litter', is_deleted=False),
                                         kennel.title))
        litter.save()
        return litter

    def get_by_slug(self, slug):
        return self.model_instance.objects.filter(
            slug=slug, is_deleted=False).order_by('-created_at').first()

    def get_all_by_kennel_slug(self, kennel_slug, order_by='-created_at'):
        kennel = self.kennels_handler.get_by_slug(kennel_slug)
        return self.model_instance.objects.filter(
            kennel=kennel, is_deleted=False).order_by(order_by)

    def get_all_by_params(self, params, order_by='-created_at'):
        return self.model_instance.objects.filter(**params).order_by(order_by)

    def get_all_by_kennel(self, kennel, order_by='-created_at'):
        return self.model_instance.objects.filter(
            kennel=kennel, is_deleted=False).order_by(order_by)

    def delete(self, slug):
        litter = self.get_by_slug(slug)
        try:
            litter.is_deleted = True
            litter.save()
        except self.model_instance.DoesNotExist:
            pass

    def make_slug(self, title, kennel_title):
        slug = '{}_{}'.format(kennel_title.replace(' ', '_'), title).lower()
        while True:
            litter = self.get_by_slug(slug)
            if not litter:
                return slug
            slug = '{}_{}'.format(slug, random.randint(1, 1000))

    def update(self, litter, data):
        if data.get('type') == 'photo':
            if data.get('photo', None):
                pass
                # image_object = self.image_handler.get_by_id(data['photo'])
                # item_data.photo = image_object.image
            else:
                litter.photo = None
        else:
            for key, value in data.items():
                if value is not None and value != '':
                    if key == 'dam_slug' or key == 'sir_slug':
                        # TODO: check if works Foreign Key update

                        value = self.animals_handler.get_by_slug(value)
                    elif key == 'breed':
                        value = self.breeds_handler.get_by_slug(value)
                    elif key == 'kennel':
                        value = self.kennels_handler.get_by_slug(value)

                    setattr(litter, key, value)
        litter.save()
        return litter

    def dump(self, item):

        plain_data = dict()
        plain_data['id'] = item.id
        plain_data['litter'] = item.litter
        plain_data['slug'] = item.slug
        plain_data['photo'] = item.photo.url if item.photo else None
        plain_data['is_photo'] = True if item.photo else False

        plain_data['pedigree'] = item.pedigree
        plain_data['birthday'] = item.birthday
        plain_data['males'] = item.males
        plain_data['females'] = item.females
        plain_data['about'] = item.about

        if item.kennel:
            plain_data['kennel'] = item.kennel.slug
            plain_data['kennel_title'] = item.kennel.title
            plain_data['kennel_url'] = reverse(
                'kennels:kennel_page', kwargs={'slug': item.kennel.slug})

        if item.breed:
            plain_data['breed'] = item.breed.title

        if item.dam:
            plain_data['dam'] = self.animals_handler.humanize_animal(item.dam)

        if item.sir:
            plain_data['sire'] = self.animals_handler.humanize_animal(item.sir)
        plain_data['news'] = self.news_handler.get_dump_news_by_params(
            dict(type='litter', source_id=item.id))
        # plain_data['album'] = self.gallery_handler.get_dump_album('litter', item.id) if \
        #     self.gallery_handler.get_album('litter', item.id) else dict(images=[], images_preview=[])
        # plain_data['album'].get('images').insert(0, dict(id='', url=plain_data['photo']))
        return plain_data