Thursday, January 24, 2019

storing multiple images in python django

While storing image provided from template , a bit different scenario occurs which we will discuss below:

lets see create.html first:


       <label>Image Title</label>:<input class="form-control mr-sm-2" value="{{item.title}}" type="text"
                            name="title" placeholder="Title" required><br>

                        <div class="form-group">
                            <label for="image">Image</label>
                            <input type="file" class="form-control" name="image" id="image" multiple value="">
                        </div>

<div> <input type=text value="normaldata" name="staticdatas"></div>

here lets say image is multiple field and other are statuc field now,
on the views where we used to store data :

def store(request):
        if request.method=='POST':
                form=HotelGalleryForm(request.POST or None,request.FILES)
                if form.is_valid():
                        form=form.save(commit=False)    
                        images=request.FILES.getlist('image')
             
                        for img in images:
                                alldata=HotelGallery()
                                alldata.image=img
                                alldata.staticdatas=form.staticdatas
                                alldata.title=form.title
                                alldata.save()

                           
                        return redirect('hotel:hotelgallery')

                else:

                        return HttpResponse("KAAM vayena")   

it will sttore each image with static data in loop in database and will return to index page 


storing data in many to many relationship in python dango

When it comes about relationship, its always been a bit difficult in any programming languages,
so i am going straight forward in most efficient way to create pivot table and store data in pivot table.

lets say, hotel and its amenities are in many to many relationship so, in hotels model

class HotelInventory(models.Model):
    other fields here ,

    amenities=models.ManyToManyField(HotelAmenities) // this line will create many to many pivot table 


now on migrating it will create pivot table  with hotel_id and amenities_id as its field.

now store individual amenities on amenities table and then,

on creating hotel inventory:

create.html
<select class="form-control mr-sm-2 " value="" name="amenities_id" multiple>
{% for things in hotelamenities %}
<option value="{{things.id}}">{{things.name}}{{things.id}}</option>
{% endfor %}
</select>

this is for multiple selection of amenities

now, in store function , of function where you perform store:

class InventoryCreate(SuccessMessageMixin,CreateView):
    template_name = 'hotelInventory/create.html'
    model=HotelInventory 
    form_class=HotelInvForm
    success_message='Information Added Successfully'
    success_url=reverse_lazy('hotel:hotelinv-index')

    def form_valid(self,form):
        inv=form.save(commit=False)    
        inv.save() 
        amenitiy=form.data.getlist('amenities_id')
      
        for amenity in amenitiy:
                inv.amenities.add(amenity)   
  
        return redirect('hotel:hotelinv-index')


Ok, this much is enough for storing data in pivot table,



Generate API in python django

Welcome to best code practices of python ,
we will be discussing about how to create api in python in most effective way,

lets start rest framework package for creating api,
install restframework:
pip install djangorestframework


now ,
keep name in installedapp i.e. inside settings.py

now create new folder lets say "api" inside your app ,of which you want to create api.

inculde urls.py of api folder inside urls.py of the app

path('api/', include('hotel.api.urls')),

now, inside urls.py of api folder

from . import views
from rest_framework import routers
from django.urls import path, include

router = routers.DefaultRouter()
router.register('hotels', views.HotelViewSet)
router.register('city', views.HotelCitySet)
router.register('hotelname', views.HotelNameSet)
router.register('hotellandmark', views.HotelLandmarkSet)

urlpatterns = [
path('', include(router.urls)),
]

create serializers.py inside api folder

localhost:8000/api/
will show all apis available and you can click on those api to see json data send fron the system.


inside serializers.py

from rest_framework import serializers
from hotel.models import Hotels
from hotel.address.models import HotelAddress

class HotelSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Hotels
fields = ('name', 'owner_id_id', 'created_at', 'description')

class HotelCitySerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = HotelAddress
fields = ('city',)

class HotelLandmarkSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = HotelAddress
fields = ('landmarks',)

class HotelNameSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Hotels
fields = ('name',)

here, write the fields that you want to send in api , when you need to send just single filed it should in tuple form so, comma is necessary.


Now inside views.py of api folder:

from hotel.api.serializers import HotelSerializer
from rest_framework import viewsets
from hotel.models import Hotels
from hotel.address.models import HotelAddress
from hotel.api.serializers import HotelCitySerializer
from hotel.api.serializers import HotelNameSerializer
from hotel.api.serializers import HotelLandmarkSerializer


class HotelViewSet(viewsets.ModelViewSet):
queryset = Hotels.objects.all().order_by('created_at')
serializer_class = HotelSerializer

class HotelCitySet(viewsets.ModelViewSet):
queryset = HotelAddress.objects.values('city')
serializer_class = HotelCitySerializer

class HotelNameSet(viewsets.ModelViewSet):
queryset = Hotels.objects.values('name')
serializer_class = HotelNameSerializer

class HotelLandmarkSet(viewsets.ModelViewSet):
queryset = HotelAddress.objects.values('landmarks')
serializer_class = HotelLandmarkSerializer



This is all we need to do for  creating and using apis,


Now this is all about simple form of API's  : what about a bit complex and more usefull :
For now here are some importatnt links:
for videos:
https://www.youtube.com/watch?v=XMu0T6L2KRQ&list=PLEsfXFp6DpzTOcOVdZF-th7BS_GYGguAS

Other Best reference:
https://blog.dbrgn.ch/2015/2/19/django-rest-framework-serializer-method-field/?fbclid=IwAR18H8bZtPwq82kAubcjOojfeTAaLro4ry2M5cuSek0KqFW2J9XxkC02vTQ

https://www.django-rest-framework.org/api-guide/filtering/?fbclid=IwAR1a50ov8abkG6BbYNLMbipe5si-kG-WuiPjXIie0LNHP92sbeUWkP9KELQ



Some other references that i have Obtained on my research are:




  • for basic of api :


  •  https://medium.com/the-andela-way/creating-a-django-api-using-django-rest-framework-apiview-b365dca53c1d
    • second one : https://codeburst.io/building-an-api-with-django-rest-framework-and-class-based-views-75b369b30396
    • https://www.django-rest-framework.org/tutorial/1-serialization/#introduction
    • https://www.django-rest-framework.org/api-guide/serializers/
    • http://www.tomchristie.com/rest-framework-2-docs/api-guide/serializers
    • https://medium.freecodecamp.org/nested-relationships-in-serializers-for-onetoone-fields-in-django-rest-framework-bdb4720d81e6
    • https://docs.djangoproject.com/en/2.1/howto/custom-model-fields/
    • https://www.quora.com/Do-I-really-need-serializers-in-Django-Rest-Framework-app
    • https://www.django-rest-framework.org/api-guide/filtering/?fbclid=IwAR3WQ3QfdN8Od66OflIxrgu7meE1AKLLvVso48G-qRnyWerD9Ts5YKUphyo
    • https://blog.dbrgn.ch/2015/2/19/django-rest-framework-serializer-method-field/?fbclid=IwAR0_-GFZMZxrJnwZI-_ALyidfvg40XZwhPSiGbaxgQrH51376bU5KdoXe2A
    • https://stackoverflow.com/questions/28078092/django-rest-framework-writable-nested-serializers

    • for best api guide:

    • https://www.django-rest-framework.org/api-guide/relations/

    • For many to many relation for  API :

    • https://www.reddit.com/r/django/comments/6yrh9k/drf_serialization_not_working_on_many_to_many/dms01dv/

    • More information:

    • https://stackoverflow.com/questions/17256724/include-intermediary-through-model-in-responses-in-django-rest-framework

    • Create customize many to many field in python  i.e. overriding normal many to many fields:

    • https://docs.djangoproject.com/en/2.1/topics/db/models/

    I am also going through them, soon i eill describe in best understandable way.


    OK Now lets Go through Detail From begning



    Lets create a normal serializer first for the address of hotel:


    in serializers.py

    class HotelAddressSerializer(ModelSerializer):
        class Meta:
            model = HotelAddress
            fields = [
                'city',            'state',            'country',            'address',            'contact1',            'contact2',            'latitude',            'longitude',        ]
    
    
    class HotelAmenitiesSerializer(ModelSerializer):
        # hotel=HotelSearchSerializer()    class Meta:
            model = HotelFacilities
            fields = [
                'name',            'image',
            ]
    
    
    
    
    Now lets use this two serializer in hotel serializer :
    
    
    
    
    class HotelSearchSerializer(ModelSerializer):
        galleries = HotelGallerySerializer(many=True, read_only=True)
        facilities = HotelAmenitiesSerializer(many=True, read_only=True)
        # hotel=HotelMiddleSerializer(many=True,read_only=True)    address = HotelAddressSerializer(read_only=True)
        # facilities = HotelMiddleSerializer(source='HotelFacilitiesMiddle', many=True)    # facilities = HotelMiddleSerializer(many=True)
        class Meta:
            model = Hotels
            fields = [
                'name',            'description',            'galleries',            'address',            'facilities',            # 'hotel'
            ]

    Here, hotelfacilities is in many to many relation with hotel:


    for this lets , create a customize relation wsing through so that api with including many to many relation can be generated :


    for that : inside models.py:

    class Hotels(models.Model):
        name = models.CharField(max_length=200)
        owner_id = models.ForeignKey(HotelOwner, on_delete=models.CASCADE)
    
        description = models.TextField(blank=True)
        is_active = models.BooleanField(default=False)
        # description = HTMLField()    created_at = models.DateTimeField(default=datetime.now, blank=True)
        facilities = models.ManyToManyField(HotelFacilities, through="HotelFacilitiesMiddle")
    
        def __str__(self):
            return self.name
    
        class Meta:
            verbose_name_plural = "Hotels"
    
    class HotelFacilitiesMiddle(models.Model):
        hotels = models.ForeignKey(Hotels,related_name="hotel", on_delete=models.CASCADE)
        hotelsfacilities = models.ForeignKey(HotelFacilities,related_name="hotelfacility", on_delete=models.CASCADE)
    
    
    
    
    now, in Views.py

    class HotelAddressViewSet(generics.ListAPIView):
        queryset = HotelAddress.objects.all().order_by('created_at')
        serializer_class = HotelAddressSerializer

    in urls.py

    path('hoteladdresslist/', HotelAddressViewSet.as_view(), name = 'hotelsearchlist'),
    
    
    path('initialhotellist/', HotelSearchViewSet.as_view(), name = 'hotelsearchlist'),
    
    





    Thank you for concerning, if any trouble occurs then please  comment below.