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.





    Tuesday, January 22, 2019

    use of decorator for authorization, multiple user access control in django python

    You may have need authorization of multiple users i.e. specified user is provided access to special feature of an app,
    let us say,
    owner can create update delete data where  staff can only view and edit the data stored by owner.
    For handling such king of requirements in python there is much easier and secure way of doing.

    lets go through it now.

    create decorators.py  inside the app where you need to authorize multiple user with multiple functionality.

    inside decoratrs.py


    from django.core.exceptions import PermissionDenied
    from hotel.models import Hotels
    def hotel_create_decorator(function):
    def wrap(request, *args, **kwargs):
    if request.user.is_hotel_owner==True:
    return function(request, *args, **kwargs)
    else:
    raise PermissionDenied
    return wrap

    def hotel_update_decorator(function):
    def wrap(request, *args, **kwargs):
    entry = Hotels.objects.get(pk=kwargs['pk'])
    if request.user.is_hotel_staff==True
    and entry.owner_id_id == request.user.owner_id_id:
    return function(request, *args, **kwargs)
    else:
    raise PermissionDenied
    return wrap

    here to update if the requested user is staff and if owner of the hotel is associated with the owner_id_id of the staff table then that staff can update the information about the hotel,

    and for create:
    if the logged in user is the owner then they can create the hotel

    Now ,

    inside views.py of teh app :

    from django.contrib.auth.decorators import login_required
    from django.utils.decorators import method_decorator
    from hotel.decorators import hotel_update_decorator
    from hotel.decorators import hotel_delete_decorator

    @method_decorator([login_required],name='dispatch')
    class HotelDetail(DetailView):
    model=Hotels
    template_name='hotel/show.html'
    queryset=Hotels.objects.all()


    @method_decorator(login_required,name='dispatch')
    @method_decorator(hotel_update_decorator,name='dispatch')
    class HotelUpdate(SuccessMessageMixin,UpdateView):
    template_name='hotel/create.html'
    model=Hotels
    form_class=HotelForm
    success_message='Information Updated Successfully'
    success_url=reverse_lazy('hotelindex')
    queryset=Hotels.objects.all()

    def form_invalid(self,form):
    messages.warning(self.request,form.errors)
    return self.render_to_response(self.get_context_data(object=form.data))
    def get_context_data(self, **kwargs):
    context = super(HotelUpdate, self).get_context_data(**kwargs)
    context['owners'] = HotelOwner.objects.all().order_by('id').reverse()
    return context


    here, @method_decorator(hotel_update_decorator,name='dispatch')
    refers to the hotel_update_decorator function of the decorators.py , if the condition inside of the function i.e.(hotel_update_decorator) all are satisfied then you will be able to update , else you will obtain forbidden message.

    here, in the above code  you have seen
    @method_decorator(login_required,name='dispatch')

    this refers that: login is required , write this kine at the top of the class where you feels it is nessary to be logged in for accessing that feature of the app.


    another way:
    inside urls.py

    from django.contrib.auth.decorators import login_required
    path('', login_required(views.HotelListView.as_view()), name="hotelindex"),


    Simply this is done now,



    reset password , update password of logged in user

    After user is logged in to the system they can update there password, this is the scenario now, lets start to dig in to the process:

    after logged in , inside dash board :
    somewhere you like ,
    <a class="nav-link" href="{%url 'reset_account_password' %}"> Reset Password</a>

    define the url in urls.py
    path('ResetPassword/',views.reset_account_password,name="reset_account_password"),

    Now, inside views.py
    from django.contrib.auth.tokens import PasswordResetTokenGenerator
    from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode

    def reset_account_password(request):
    user=request.user
    pwtoken=PasswordResetTokenGenerator().make_token(user)
    newuid=urlsafe_base64_encode(force_bytes(user.pk)).decode()
    return redirect('password_reset_confirm',uidb64=newuid,token=pwtoken)

    For using this you need to import above lines in views.py

    Its done , Simplest and secure way for doing ,
    If you have any confussion then please leave comment below:

    Monday, January 21, 2019

    User login email verification in python with reset password after successful verification

    When you really need more security while making accounts and secure registration towards the system you actually need is to authenticate email address via email:

    Before going through this one: please kindly visit the following blog , so that you will be a be more clear , 
    # IMPORTANT

    But if you want direct coding here is how this is done, :

    Lets start from beginning :

    lets setup email first:

    inside settings.py:

    EMAIL_USE_TLS=True
    EMAIL_HOST='smtp.gmail.com'
    EMAIL_HOST_USER='youremail'
    EMAIL_HOST_PASSWORD='yourpassword'
    EMAIL_PORT=587


    create app account and setup basics : go to link provided above for detail:

    now inside forms.py of the account app:

    from django import forms
    from django.contrib.auth.forms import UserCreationForm
    from django.db import transaction
    from account.models import User
    from hotel.owner.models import HotelOwner
    from hotel.staff.models import HotelStaff

    class HotelOwnerSignUpForm(UserCreationForm):
    email=forms.EmailField(required=True,label='Email')
    first_name=forms.CharField(required=True,label='First Name')
    last_name=forms.CharField(required=True,label='Last Name')
    class Meta(UserCreationForm.Meta):
    model=User
    fields=("first_name","last_name","email","username","password1","password2")

    class HotelStaffSignUpForm(UserCreationForm):
    class Meta(UserCreationForm.Meta):
    model=User
    fields=("first_name","last_name","email","username","password1","password2")

    create tokens.py inside account app

    from django.contrib.auth.tokens import PasswordResetTokenGenerator
    from django.utils import six
    class TokenGenerator(PasswordResetTokenGenerator):
    def _make_hash_value(self, user, timestamp):
    return (
    six.text_type(user.pk) + six.text_type(timestamp) +
    six.text_type(user.is_active)
    )
    account_activation_token = TokenGenerator()  


    Now inside urls.py  of account app


    path('ResetPassword/',views.reset_account_password,name="reset_account_password"),
    url(r'^activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',views.activate, name='activate'),

    Inside views.py of account app
    from django.shortcuts import render
    from django.shortcuts import redirect
    from django.views.generic import CreateView
    from .forms import HotelOwnerSignUpForm
    from .forms import HotelStaffSignUpForm
    from django.http import HttpResponse
    from account.models import User
    from hotel.owner.models import HotelOwner

    from django.contrib.auth import login, authenticate
    from django.contrib.sites.shortcuts import get_current_site
    from django.utils.encoding import force_bytes, force_text
    from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode
    from django.template.loader import render_to_string
    from .tokens import account_activation_token
    from django.core.mail import EmailMessage
    from django.contrib.auth.tokens import PasswordResetTokenGenerator

    def signup(request):
    if request.method == 'POST':
    form = HotelOwnerSignUpForm(request.POST)
    if form.is_valid():
    user = form.save(commit=False)
    user.is_active = False
    user.save()
    current_site = get_current_site(request)
    mail_subject = 'Activate your blog account.'
    message = render_to_string('account/active_email.html', {
    'user': user,
    'domain': current_site.domain,
    'uid':urlsafe_base64_encode(force_bytes(user.pk)).decode(),
    'token':account_activation_token.make_token(user),
    })
    to_email = form.cleaned_data.get('email')
    email = EmailMessage(
    mail_subject, message, to=[to_email]
    )
    email.send()
    return HttpResponse('Please confirm your email address to complete the registration')
    else:
    form = HotelOwnerSignUpForm()
    return render(request, 'account/signup_form.html', {'form': form})

    def activate(request, uidb64, token):
    try:
    uid = force_text(urlsafe_base64_decode(uidb64))
    user = User.objects.get(pk=uid)
    except(TypeError, ValueError, OverflowError, User.DoesNotExist):
    user = None
    if user is not None and account_activation_token.check_token(user, token):
    user.is_active = True
    user.save()
    owner=HotelOwner.objects.create(user=user)
    id=user.id
    login(request, user)
    pwtoken=PasswordResetTokenGenerator().make_token(user)
    newuid=urlsafe_base64_encode(force_bytes(user.pk)).decode()
    return redirect('password_reset_confirm',uidb64=newuid,token=pwtoken)
    #return redirect('hotel:ownerupdate',id)
    else:
    return HttpResponse('Activation link is invalid!')

    class HotelStaffSignUpView(CreateView):
    model = User
    form_class = HotelStaffSignUpForm
    template_name = 'account/signup_form.html'
    # print(request.user)

    def form_valid(self, form):
    # user = form.save()
    user=form.save(commit=False)
    user.is_hotel_staff=True
    user.save()
    owner_id=self.request.user.id
    staff=HotelStaff.objects.create(user=user,owner_id_id=owner_id)
    id=user.id
    return redirect('hotel:staffupdate',id)



    here, after you fillup signup form it, will send email a link of password reset form and on clicking that password can be changed.

    now , tehre is just few steps to follow:

    create active_email.html inside templates of account app and:

    Hi {{ user.username }},
    Please click on the link to confirm your registration,
    http://{{ domain }}{% url 'activate' uidb64=uid token=token %}

    this is the message you are sending to the email obtained form signup form :

    all about signup forms are described on the previous blog and link of blog is provided above.



    This is all we need for email verification in python django project



    Custom login and signup for multiple user in python

    For making customize login in python , its a bit lengthy process and a bit difficult to understand but, i am trying to go straight forward towards the implementation and describe what exactly required ,
    So, lets start the now:

    lets start with surrounding  first: i am trying to create owner and staff for as multiple users , say owner can only create user and owner can be created by super users only , for such thing we need to have multiple logins access i.e login for owner and staff along with signup also,

    now for this , lets create new app named account:

    register the created app inside settings.py of the project

    and inside urls.py  of the project :
    path('account/', include('account.urls')),

    now, inside urls.py of account app


    from django.contrib import admin
    from django.urls import path
    from django.conf.urls import url, include
    from django.conf.urls.static import static
    from .import views
    urlpatterns = [
    path('hotelowner/', views.HotelOwnerSignUpView.as_view(), name="hotelowner_signup"),
    #path('hotelowner/', views.signup, name="hotelowner_signup"),
    path('hotelstaff/', views.HotelStaffSignUpView.as_view(), name="hotelstaff_signup"),

    ]

    Main important section is models.py of the account app  where we are going to overwrite Abstractclass of django default auth to add more fields on the form

    from django.db import models
    from django.contrib.auth.models import AbstractUser

    class User(AbstractUser):
    email=models.EmailField(
    verbose_name='email address',
    max_length=255,
    unique=True,
    )
    is_hotel_staff=models.BooleanField(default=False)
    is_hotel_owner=models.BooleanField(default=False)

    form here we create our own user where all default feature of Abstract class is included like : username ,password, firstname etc. along with our customized field is_hotel_staff , is_hotel_owner

    now , lets make forms.py  of the account app:

    from django import forms
    from django.contrib.auth.forms import UserCreationForm
    from django.db import transaction
    from account.models import User
    from hotel.owner.models import HotelOwner
    from hotel.staff.models import HotelStaff

    class HotelOwnerSignUpForm(UserCreationForm):
    email=forms.EmailField(required=True,label='Email')
    first_name=forms.CharField(required=True,label='First Name')
    last_name=forms.CharField(required=True,label='Last Name')
    class Meta(UserCreationForm.Meta):
    model=User
    fields=("first_name","last_name","email","username","password1","password2")

    @transaction.atomic
    def save(self):
    user=super().save(commit=False)
    user.is_hotel_owner=True
    user.save()
    owner=HotelOwner.objects.create(user=user)
    return user

    class HotelStaffSignUpForm(UserCreationForm): class Meta(UserCreationForm.Meta): model=User fields=("first_name","last_name","email","username","password1","password2") # @transaction.atomic # def save(self): # user=super().save(commit=False) # user.is_hotel_staff=True # user.save() # staff=HotelStaff.objects.create(user=user) # return user


    Here,

    we store general information to the Users table and also store the user id just been created to the hotel owners table so that we can identify this one is the hotel ownera nd we can update extra information:
    for more clearity lets see what is there in hotel owner model.py:

    from account.models import User

    class HotelOwner(models.Model):
    name = models.CharField(max_length=80,null=True)
    contact = models.BigIntegerField(null=True)
    # email = models.EmailField(unique=True,null=True)
    # password = models.CharField(max_length = 30,null=True)
    image = models.ImageField(default='default.png')
    address = models.CharField(max_length=80,null=True)
    created_at = models.DateTimeField(default=datetime.now, blank=True)
    user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)


    here,  we import user form account model, because now our default user is user created from accounts app, and also we make that user as primary key .

     also see the forms.py of owner for more clearity
    from django import forms
    from ..models import Hotels
    from .models import HotelOwner

    class HotelOwnerForm(forms.ModelForm):
    class Meta:
    model = HotelOwner
    fields = ["name","contact","image","address","created_at"]

    here, we haven't included user_id field in fields because we will not create input field for the user_id  we obtain that directly after username and password and other general information about the user is stored in account.users table previously.

    Now its time to go deep towards views.py of account app, where there is major functioning

    from django.shortcuts import render
    from django.shortcuts import redirect
    from django.views.generic import CreateView
    from .forms import HotelOwnerSignUpForm
    from .forms import HotelStaffSignUpForm
    from django.http import HttpResponse
    from account.models import User
    from hotel.owner.models import HotelOwner

    class HotelOwnerSignUpView(CreateView):
    model = User
    form_class = HotelOwnerSignUpForm
    template_name = 'account/signup_form.html'


    def form_valid(self, form):
    user = form.save()
    login(self.request, user)
    user.save()
    id=user.id
    return redirect('hotel:ownerupdate',id)

    class HotelStaffSignUpView(CreateView):
    model = User
    form_class = HotelStaffSignUpForm
    template_name = 'account/signup_form.html'
    # print(request.user)

    def form_valid(self, form):
    # user = form.save()
    user=form.save(commit=False)
    user.is_hotel_staff=True
    user.save()
    owner_id=self.request.user.id
    staff=HotelStaff.objects.create(user=user,owner_id_id=owner_id)
    id=user.id
    return redirect('hotel:staffupdate',id)


    after storing user in account_users table and storing user_id inside owners table, first the created user will be logged in to the system then will  redirect to the update function of the owner so that we can add general information to the owners profile or say update owners detail.

    let me explain about namespace mathod used in the system:

    return redirect('hotel:ownerupdate',id)

    here hotel:ownerupdate refers to the updatefunction of the owner module which is included inside  hotel app ursl.py i.e.

    # urls.py of hotel app

    app_name='hotel'
    urlpatterns = [
    path('owner/', include('hotel.owner.urls')),
    ]

    # urls.py of owner module of hotel app

    path('update/<int:pk>', views.OwnerUpdate.as_view(), name="ownerupdate"),



    now lets see the signup_forms.html inside of account app template:

    {% extends 'travel/sign_base.html' %}
    {% load crispy_forms_tags %}

    {% block content %}
    <div class="row">
    <div class="col-md-8 col-sm-10 col-12">
    <h2>Sign up as a {{ user_type }}</h2>
    <form method="post" novalidate>
    {% csrf_token %}
    <input type="hidden" name="next" value="{{ next }}">
    {{ form|crispy }}
    <button type="submit" class="btn btn-success">Sign up</button>
    </form>
    </div>
    </div>
    {% endblock %}

    for using  'crispy_forms'

     install django-crispy-forms-1.7.2 in your environment and then include the in installed app thats all you need to do ,
    and include crispy template pack also inside settings.py i.e:
    CRISPY_TEMPLATE_PACK='bootstrap4'

    since we are customizing everything so, lets make one small costumization for our easyness : i.e make out own login form, logout and our own redirect path after login , logout etc, for that just write following lines of codes inside settings.py

    AUTH_USER_MODEL='account.User'
    LOGIN_URL='login'
    LOGOUT_URL='logout'
    LOGIN_REDIRECT_URL='urltoredirect'
    LOGOUT_REDIRECT_URL='login'


    • we set auth user model which was default user model of python to our user of account app 
    • login url to login which will understand  as login.html of registration template which will be override by our custom register template's login.html .
    • after logout we redirect to login.html again


    Now, lets create registration folder inside templates folder of the project 

    login.html 


    {% extends 'travel/sign_base.html' %}

    {% load crispy_forms_tags %}

    {% block content %}
    {% if form.non_field_errors %}
    <div class="alert alert-danger alert-dismissible fade show" role="alert">
    {% for error in form.non_field_errors %}
    <p{% if forloop.last %} class="mb-0"{% endif %}>{{ error }}</p>
    {% endfor %}
    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
    <span aria-hidden="true">&times;</span>
    </button>
    </div>
    {% endif %}
    <div class="row">
    <div class="col-lg-4 col-md-6 col-sm-8 col-12">
    <h2>Log in</h2>
    <form method="post" novalidate>
    {% csrf_token %}
    <input type="hidden" name="next" value="{{ next }}">
    {{ form.username|as_crispy_field }}
    {{ form.password|as_crispy_field }}
    <button type="submit" class="btn btn-primary">Log in</button>
    </form>
    </div>
    </div>
    {% endblock %}


    For logout :
    <a class="nav-link" href="{%url 'logout' %}"> Logout</a>

    on clicking the logout button with above url  it will destroy the session and will be logged out automatically and redirect to the url that you have specified above.


    Finally , you have come this way long and completed multple authentication  for multiple user

                                                        THANK YOU FOR SUPPORT AND TRUST :

    If any problems occured while following this steps you cam comment below and get direct support form me













    Sunday, January 20, 2019

    simplest and easy way to use git git flow

    first of all, lets discuss about git first, gitlab, github are most helpfull when, you are working on team, as team it is important to communicate with you team and provide your portion of source code to you team mates, so for that purpose i prefer gitlab
    link for gitlab is : https://gitlab.com

    Now, lets go deeper in it...
    when yo have your own git account and you have created your project, after creating a project you can easily follow the steps that will be provided below your project just you have created for first time.
    After following those steps you will push your project for first time in your git repo,
    Now what after it ? what more? i will describe in best way:

    Steps to follow:
    1.  for first time , when your team member want to get your project :
           

              Approach 1:
                                   Go to the directory where you want to put your project and open git bash there and use following command:

    git clone https://gitlab.com/...


    git clone and after that get the git cloning address from the git and paste that .
    copy clone address shown


    Now you will have a local copy of the project within your distination folder.

    Approach 2: 

    By this approach every thing is done from git bash, or you also can use cmd


    1.     mkdir FolderName
    2.     cd FolderName
    3.     git init
    4.     git remote add origin https://gitlab.com/...
    5.     git pull origin master


    2.  never work on master branch directly, i.e create your own branch and push that branch to git so you can work on your own branch


    for creating branch from command line  

           git checkout -b new_branch_name

    Now you have switched to your own branch , it is  the copy of you master branch and you can do code you portion on that branch , 
    after completion your day or targeted mission now, its time to push your branch to the git

    For that:

    git remote add origin https://gitlab.com/...

    after using this command now instead of writting whole url every time , simply you can use word origin .


    1. git add -A
    2. git commit -m "Commit message"
    3. git push origin branch_name 

    branch_name refers to the branch name that you have created earlier ...


    now you have pushed your code to the git with new branch with branch name you just created above.

    now , its time to merge your work to the master branch :
    for that:
    Create the merge request and see whether there is any conflict on merging or not , if no conflict then, you are luckey one, just merge you branch 
    if there is conflict then, nothing to be done from my side, now its your turn to fix those conflict, but no worries git will provide you guideline to manage conflict. 

    After Successfull merge , now just delete your branch from git , now you are going to clone that master branch and use it again.

    Every day workflow:

    git remote add origin https://gitlab.com/...

    1. git pull origin master
    2. git checkout -b new_branch_name
    3. git add -A
    4. git commit -m "Commit message"
    5. git push origin branch_name


    When conflict arrises, i.e 2 commit behinds ... then:

    first git pull origin master
    - solve the conflict locally on your file
    - commit the file to your branch
    then merge your branch to the master then it will work fine





    Converting string date to date format and use of it in laravel

    Though you can store code directly as time stamp in database , but any time you missed it, no worries there are many ways to use those string type of date as real date time formatted date:
    here is how i did it for my best practice:

    let , you take date store  in database in some  variable say : $date, now to convert it to usable date format:

    $date= date('Y-M-D', strtotime($date));

    now, $date variable will get date where you can operate any type of date query :
    here is small example of query i have used: or also i can say that this query which i am going to show below will also help to convert and format unformated date in proper format :

    lets say $item->date carries date from controller to blade template , where i write logic to format the code :

    @php
    $realdate=$item->date;
    $myDateTime = DateTime::createFromFormat('Y-m-d', $realdate);
    @endphp


    $myDateTime is the perfectly formatted form of the date, now on this formatted date you can do and date operations such as:
    {{date_format($myDateTime,'M j, Y')}} //eg: 2019-11-26 to : October 26, 2019
    {{date_format($myDateTime,'j')}}//eg: 2019-11-26 to : 26
    {{date_format($myDateTime,'M')}}//eg: 2019-11-26 to : October
    {{date_format($myDateTime,'y')}}//eg: 2019-11-26 to : 2019

    I hope you get this all easily ,