↓↓クリックして頂けると励みになります。
【32 | 支払い】 << 【ホーム】 >> 【34 | 配達依頼詳細ページ】
「crowdsource/urls.py」ファイルを編集します。
記述追加 【Desktop/crowdsource/crowdsource/urls.py】18行目
from django.contrib import admin from django.urls import path, include from django.contrib.auth import views as auth_views from django.conf import settings from django.conf.urls.static import static from core import views from core.customer import views as customer_views from core.courier import views as courier_views customer_urlpatters = [ path('', customer_views.home, name="home"), path('profile/', customer_views.profile_page, name="profile"), path('payment_method/', customer_views.payment_method_page, name="payment_method"), path('create_job/', customer_views.create_job_page, name="create_job"), path('jobs/current/', customer_views.current_jobs_page, name="current_jobs"), path('jobs/archived/', customer_views.archived_jobs_page, name="archived_jobs"), ] courier_urlpatters = [ path('', courier_views.home, name="home"), ] urlpatterns = [ path('admin/', admin.site.urls), path('oauth/', include('social_django.urls', namespace='social')), path('', views.home), path('sign-in/', auth_views.LoginView.as_view(template_name="sign_in.html")), path('sign-out/', auth_views.LogoutView.as_view(next_page="/")), path('sign-up/', views.sign_up), path('customer/', include((customer_urlpatters, 'customer'))), path('courier/', include((courier_urlpatters, 'courier'))), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
「core/customer/views.py」ファイルを編集します。
記述編集 【Desktop/crowdsource/core/customer/views.py】
import requests import firebase_admin from firebase_admin import credentials, auth import stripe from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from django.urls import reverse from core.customer import forms from django.contrib import messages from django.contrib.auth.forms import PasswordChangeForm from django.contrib.auth import update_session_auth_hash from django.conf import settings from core.models import * cred = credentials.Certificate(settings.FIREBASE_ADMIN_CREDENTIAL) firebase_admin.initialize_app(cred) stripe.api_key = settings.STRIPE_API_SECRET_KEY @login_required() def home(request): return redirect(reverse('customer:profile')) @login_required(login_url="/sign-in/?next=/customer/") def profile_page(request): user_form = forms.BasicUserForm(instance=request.user) customer_form = forms.BasicCustomerForm(instance=request.user.customer) password_form = PasswordChangeForm(request.user) if request.method == "POST": if request.POST.get('action') == 'update_profile': user_form = forms.BasicUserForm(request.POST, instance=request.user) customer_form = forms.BasicCustomerForm(request.POST, request.FILES, instance=request.user.customer) if user_form.is_valid() and customer_form.is_valid(): user_form.save() customer_form.save() messages.success(request, 'プロフィールが更新されました。') return redirect(reverse('customer:profile')) elif request.POST.get('action') == 'update_password': password_form = PasswordChangeForm(request.user, request.POST) if password_form.is_valid(): user = password_form.save() update_session_auth_hash(request, user) messages.success(request, 'パスワードが更新されました。') return redirect(reverse('customer:profile')) elif request.POST.get('action') == 'update_phone': # Get Firebase user data firebase_user = auth.verify_id_token(request.POST.get('id_token')) request.user.customer.phone_number = firebase_user['phone_number'] request.user.customer.save() messages.success(request, '電話番号が更新されました。') return redirect(reverse('customer:profile')) return render(request, 'customer/profile.html', { "user_form": user_form, "customer_form": customer_form, "password_form": password_form, }) @login_required(login_url="/sign-in/?next=/customer/") def payment_method_page(request): current_customer = request.user.customer # Remove existing card if request.method == "POST": stripe.PaymentMethod.detach(current_customer.stripe_payment_method_id) current_customer.stripe_payment_method_id = "" current_customer.stripe_card_last4 = "" current_customer.save() return redirect(reverse('customer:payment_method')) # Save stripe customer infor if not current_customer.stripe_customer_id: customer = stripe.Customer.create() current_customer.stripe_customer_id = customer['id'] current_customer.save() # Get Stripe payment method stripe_payment_methods = stripe.PaymentMethod.list( customer = current_customer.stripe_customer_id, type = "card", ) print(stripe_payment_methods) if stripe_payment_methods and len(stripe_payment_methods.data) > 0: payment_method = stripe_payment_methods.data[0] current_customer.stripe_payment_method_id = payment_method.id current_customer.stripe_card_last4 = payment_method.card.last4 current_customer.save() else: current_customer.stripe_payment_method_id = "" current_customer.stripe_card_last4 = "" current_customer.save() if not current_customer.stripe_payment_method_id: intent = stripe.SetupIntent.create( customer = current_customer.stripe_customer_id ) return render(request, 'customer/payment_method.html', { "client_secret": intent.client_secret, "STRIPE_API_PUBLIC_KEY": settings.STRIPE_API_PUBLIC_KEY, }) else: return render(request, 'customer/payment_method.html') @login_required(login_url="/sign-in/?next=/customer/") def create_job_page(request): current_customer = request.user.customer if not current_customer.stripe_payment_method_id: return redirect(reverse('customer:payment_method')) creating_job = Job.objects.filter(customer=current_customer, status=Job.CREATING_STATUS).last() step1_form = forms.JobCreateStep1Form(instance=creating_job) step2_form = forms.JobCreateStep2Form(instance=creating_job) step3_form = forms.JobCreateStep3Form(instance=creating_job) if request.method == "POST": if request.POST.get('step') == '1': step1_form = forms.JobCreateStep1Form(request.POST, request.FILES) if step1_form.is_valid(): creating_job = step1_form.save(commit=False) creating_job.customer = current_customer creating_job.save() return redirect(reverse('customer:create_job')) elif request.POST.get('step') == '2': step2_form = forms.JobCreateStep2Form(request.POST, instance=creating_job) if step2_form.is_valid(): creating_job = step2_form.save() return redirect(reverse('customer:create_job')) elif request.POST.get('step') == '3': step3_form = forms.JobCreateStep3Form(request.POST, instance=creating_job) if step3_form.is_valid(): creating_job = step3_form.save() try: r = requests.get("https://maps.googleapis.com/maps/api/distancematrix/json?origins={}&destinations={}&language=ja&mode=driving®ion=ja&key={}".format( creating_job.pickup_address, creating_job.delivery_address, settings.GOOGLE_MAP_API_KEY, )) print(r.json()['rows']) distance = r.json()['rows'][0]['elements'][0]['distance']['value'] duration = r.json()['rows'][0]['elements'][0]['duration']['value'] creating_job.distance = round(distance / 1000, 2) #距離 creating_job.duration = int(duration / 60) #移動時間 creating_job.price = int(creating_job.distance * 35) # kmあたり35円 creating_job.save() except Exception as e: print(e) messages.error(request, "残念ながら、この距離での配送はサポートされていません。") elif request.POST.get('step') == '4': if creating_job.price: try: payment_intent = stripe.PaymentIntent.create( amount=int(creating_job.price), currency='jpy', customer=current_customer.stripe_customer_id, payment_method=current_customer.stripe_payment_method_id, off_session=True, confirm=True, ) Transaction.objects.create( stripe_payment_intent_id = payment_intent['id'], job = creating_job, amount = creating_job.price, ) creating_job.status = Job.PROCESSING_STATUS creating_job.save() return redirect(reverse('customer:home')) except stripe.error.CardError as e: err = e.error # Error code will be authentication_required if authentication is needed print("Code is: %s" % err.code) payment_intent_id = err.payment_intent['id'] payment_intent = stripe.PaymentIntent.retrieve(payment_intent_id) # 現在のステップ if not creating_job: current_step = 1 elif creating_job.delivery_name: current_step = 4 elif creating_job.pickup_name: current_step = 3 else: current_step = 2 return render(request, 'customer/create_job.html', { "job": creating_job, "step": current_step, "step1_form": step1_form, "step2_form": step2_form, "step3_form": step3_form, "GOOGLE_MAP_API_KEY": settings.GOOGLE_MAP_API_KEY, }) @login_required(login_url="/sign-in/?next=/customer/") def current_jobs_page(request): jobs = Job.objects.filter( customer=request.user.customer, status__in=[ Job.PROCESSING_STATUS, Job.PICKING_STATUS, Job.DELIVERING_STATUS ] ) return render(request, 'customer/jobs.html', { "jobs": jobs }) @login_required(login_url="/sign-in/?next=/customer/") def archived_jobs_page(request): jobs = Job.objects.filter( customer=request.user.customer, status__in=[ Job.COMPLETED_STATUS, Job.CANCELED_STATUS ] ) return render(request, 'customer/jobs.html', { "jobs": jobs })
「core/templates/customer」フォルダに「jobs.html」ファイルを新規作成します。
新規作成 【Desktop/crowdsource/core/templates/customer/jobs.html】
{% extends 'customer/base.html' %} {% block main %} 依頼した配達 {% endblock %}
「core/templates/customer/base.html」ファイルを編集します。
記述編集 【Desktop/crowdsource/core/templates/customer/base.html】
{% extends 'base.html' %} {% load static %} {% block content %} {% url 'customer:create_job' as create_job_url %} {% url 'customer:profile' as profile_url %} {% url 'customer:current_jobs' as current_jobs_url %} {% url 'customer:archived_jobs' as archived_jobs_url %} {% url 'customer:payment_method' as payment_method_url %} <div class="container bg-light mt-4 pt-3 pb-3"> <div class="row"> <div class="col-lg-4"> <div class="text-center"> <img src="{% if request.user.customer.avatar %}{{ request.user.customer.avatar.url }}{% else %}{% static 'img/avatar01.jpg' %}{% endif %}" alt="" class="rounded-circle mb-2" width="150"> <h4>{{ request.user.last_name }} {{ request.user.first_name }}</h4> <p class="text-secondary">{{ request.user.email }}</p> </div> <div class="list-group mt-5"> <a href="{% url 'customer:create_job' %}" class="list-group-item list-group-item-info list-group-item-action {% if request.path == create_job_url %}active{% endif %}">配達を依頼する</a> <a href="{% url 'customer:current_jobs' %}" class="list-group-item list-group-item-info list-group-item-action {% if request.path == current_jobs_url or request.path == archived_jobs_url %}active{% endif %}">依頼した配達</a> <a href="{% url 'customer:profile' %}" class="list-group-item list-group-item-info list-group-item-action {% if request.path == profile_url %}active{% endif %}">プロフィール</a> <a href="{% url 'customer:payment_method' %}" class="list-group-item list-group-item-info list-group-item-action {% if request.path == payment_method_url %}active{% endif %}">支払い方法</a> </div> </div> <div class="col-lg-8"> {% block main %} {% endblock %} </div> </div> </div> {% endblock %}
ブラウザを確認します。
http://127.0.0.1:8000/customer/jobs/current/
「core/customer/views.py」ファイルを編集します。
記述編集 【Desktop/crowdsource/core/customer/views.py】
import requests import firebase_admin from firebase_admin import credentials, auth import stripe from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from django.urls import reverse from core.customer import forms from django.contrib import messages from django.contrib.auth.forms import PasswordChangeForm from django.contrib.auth import update_session_auth_hash from django.conf import settings from core.models import * cred = credentials.Certificate(settings.FIREBASE_ADMIN_CREDENTIAL) firebase_admin.initialize_app(cred) stripe.api_key = settings.STRIPE_API_SECRET_KEY @login_required() def home(request): return redirect(reverse('customer:profile')) @login_required(login_url="/sign-in/?next=/customer/") def profile_page(request): user_form = forms.BasicUserForm(instance=request.user) customer_form = forms.BasicCustomerForm(instance=request.user.customer) password_form = PasswordChangeForm(request.user) if request.method == "POST": if request.POST.get('action') == 'update_profile': user_form = forms.BasicUserForm(request.POST, instance=request.user) customer_form = forms.BasicCustomerForm(request.POST, request.FILES, instance=request.user.customer) if user_form.is_valid() and customer_form.is_valid(): user_form.save() customer_form.save() messages.success(request, 'プロフィールが更新されました。') return redirect(reverse('customer:profile')) elif request.POST.get('action') == 'update_password': password_form = PasswordChangeForm(request.user, request.POST) if password_form.is_valid(): user = password_form.save() update_session_auth_hash(request, user) messages.success(request, 'パスワードが更新されました。') return redirect(reverse('customer:profile')) elif request.POST.get('action') == 'update_phone': # Get Firebase user data firebase_user = auth.verify_id_token(request.POST.get('id_token')) request.user.customer.phone_number = firebase_user['phone_number'] request.user.customer.save() messages.success(request, '電話番号が更新されました。') return redirect(reverse('customer:profile')) return render(request, 'customer/profile.html', { "user_form": user_form, "customer_form": customer_form, "password_form": password_form, }) @login_required(login_url="/sign-in/?next=/customer/") def payment_method_page(request): current_customer = request.user.customer # Remove existing card if request.method == "POST": stripe.PaymentMethod.detach(current_customer.stripe_payment_method_id) current_customer.stripe_payment_method_id = "" current_customer.stripe_card_last4 = "" current_customer.save() return redirect(reverse('customer:payment_method')) # Save stripe customer infor if not current_customer.stripe_customer_id: customer = stripe.Customer.create() current_customer.stripe_customer_id = customer['id'] current_customer.save() # Get Stripe payment method stripe_payment_methods = stripe.PaymentMethod.list( customer = current_customer.stripe_customer_id, type = "card", ) print(stripe_payment_methods) if stripe_payment_methods and len(stripe_payment_methods.data) > 0: payment_method = stripe_payment_methods.data[0] current_customer.stripe_payment_method_id = payment_method.id current_customer.stripe_card_last4 = payment_method.card.last4 current_customer.save() else: current_customer.stripe_payment_method_id = "" current_customer.stripe_card_last4 = "" current_customer.save() if not current_customer.stripe_payment_method_id: intent = stripe.SetupIntent.create( customer = current_customer.stripe_customer_id ) return render(request, 'customer/payment_method.html', { "client_secret": intent.client_secret, "STRIPE_API_PUBLIC_KEY": settings.STRIPE_API_PUBLIC_KEY, }) else: return render(request, 'customer/payment_method.html') @login_required(login_url="/sign-in/?next=/customer/") def create_job_page(request): current_customer = request.user.customer if not current_customer.stripe_payment_method_id: return redirect(reverse('customer:payment_method')) has_current_job = Job.objects.filter( customer = current_customer, status__in = [ Job.PROCESSING_STATUS, Job.PICKING_STATUS, Job.DELIVERING_STATUS ] ).exists() if has_current_job: messages.warning(request, "現在依頼中の仕事があります") return redirect(reverse('customer:current_jobs')) creating_job = Job.objects.filter(customer=current_customer, status=Job.CREATING_STATUS).last() step1_form = forms.JobCreateStep1Form(instance=creating_job) step2_form = forms.JobCreateStep2Form(instance=creating_job) step3_form = forms.JobCreateStep3Form(instance=creating_job) if request.method == "POST": if request.POST.get('step') == '1': step1_form = forms.JobCreateStep1Form(request.POST, request.FILES) if step1_form.is_valid(): creating_job = step1_form.save(commit=False) creating_job.customer = current_customer creating_job.save() return redirect(reverse('customer:create_job')) elif request.POST.get('step') == '2': step2_form = forms.JobCreateStep2Form(request.POST, instance=creating_job) if step2_form.is_valid(): creating_job = step2_form.save() return redirect(reverse('customer:create_job')) elif request.POST.get('step') == '3': step3_form = forms.JobCreateStep3Form(request.POST, instance=creating_job) if step3_form.is_valid(): creating_job = step3_form.save() try: r = requests.get("https://maps.googleapis.com/maps/api/distancematrix/json?origins={}&destinations={}&language=ja&mode=driving®ion=ja&key={}".format( creating_job.pickup_address, creating_job.delivery_address, settings.GOOGLE_MAP_API_KEY, )) print(r.json()['rows']) distance = r.json()['rows'][0]['elements'][0]['distance']['value'] duration = r.json()['rows'][0]['elements'][0]['duration']['value'] creating_job.distance = round(distance / 1000, 2) #距離 creating_job.duration = int(duration / 60) #移動時間 creating_job.price = int(creating_job.distance * 35) # kmあたり35円 creating_job.save() except Exception as e: print(e) messages.error(request, "残念ながら、この距離での配送はサポートされていません。") elif request.POST.get('step') == '4': if creating_job.price: try: payment_intent = stripe.PaymentIntent.create( amount=int(creating_job.price), currency='jpy', customer=current_customer.stripe_customer_id, payment_method=current_customer.stripe_payment_method_id, off_session=True, confirm=True, ) Transaction.objects.create( stripe_payment_intent_id = payment_intent['id'], job = creating_job, amount = creating_job.price, ) creating_job.status = Job.PROCESSING_STATUS creating_job.save() return redirect(reverse('customer:home')) except stripe.error.CardError as e: err = e.error # Error code will be authentication_required if authentication is needed print("Code is: %s" % err.code) payment_intent_id = err.payment_intent['id'] payment_intent = stripe.PaymentIntent.retrieve(payment_intent_id) # 現在のステップ if not creating_job: current_step = 1 elif creating_job.delivery_name: current_step = 4 elif creating_job.pickup_name: current_step = 3 else: current_step = 2 return render(request, 'customer/create_job.html', { "job": creating_job, "step": current_step, "step1_form": step1_form, "step2_form": step2_form, "step3_form": step3_form, "GOOGLE_MAP_API_KEY": settings.GOOGLE_MAP_API_KEY, }) @login_required(login_url="/sign-in/?next=/customer/") def current_jobs_page(request): jobs = Job.objects.filter( customer=request.user.customer, status__in=[ Job.PROCESSING_STATUS, Job.PICKING_STATUS, Job.DELIVERING_STATUS ] ) return render(request, 'customer/jobs.html', { "jobs": jobs }) @login_required(login_url="/sign-in/?next=/customer/") def archived_jobs_page(request): jobs = Job.objects.filter( customer=request.user.customer, status__in=[ Job.COMPLETED_STATUS, Job.CANCELED_STATUS ] ) return render(request, 'customer/jobs.html', { "jobs": jobs })
依頼した配達のステータスがまだ「processing」の場合、新たに配達を依頼しようとしてもできないようになりました。
ページの内容を編集します。
「core/templates/customer/jobs.html」ファイルを編集します。
記述編集 【Desktop/crowdsource/core/templates/customer/jobs.html】
{% extends 'customer/base.html' %} {% block main %} {% url 'customer:current_jobs' as current_jobs_url %} {% url 'customer:archived_jobs' as archived_jobs_url %} <style> .nav-pills .nav-link.active{ background-color: rgb(27, 73, 66); } /* タブの文字色変更 */ .nav-pills .nav-link{ color: rgb(27, 73, 66); } </style> <!-- タブ --> <ul class="nav nav-pills nav-fill"> <li class="nav-item"> <a class="nav-link {% if request.path == current_jobs_url %}active{% endif %}" href="{% url 'customer:current_jobs' %}">依頼中の配達</a> </li> <li class="nav-item"> <a class="nav-link {% if request.path == archived_jobs_url %}active{% endif %}" href="{% url 'customer:archived_jobs' %}">終了した配達依頼</a> </li> </ul> <!-- 配達依頼リスト --> <div class="list-group mt-3"> {% if jobs %} {% for job in jobs %} <a href="#" class="list-group-item list-group-item-action"> <div class="media"> <img src="{{ job.photo.url }}" class="rounded-lg mr-3" width="100" height="100"> <div class="media-body"> <div class="row"> <div class="col-lg-9"> <h5 class="mb-1">{{ job.name }}</h5> <p>{{ job.description }}</p> <div class="d-flex mb-4"> <i class="fas fa-map-marker-alt"></i> <div class="ml-2"> <b>{{ job.pickup_name }}</b><br /> <small>{{ job.pickup_address }}</small> </div> </div> <div class="d-flex"> <i class="fas fa-flag-checkered"></i> <div class="ml-2"> <b>{{ job.delivery_name }}</b><br /> <small>{{ job.delivery_address }}</small> </div> </div> </div> <div class="col-lg-3 text-right d-flex flex-column justify-content-between"> <div> <span class="badge badge-warning mb-2"> {% if job.get_status_display == 'Processing' %} 進行中 {{ job.get_status_display }} {% else %} 完了 {{ job.get_status_display }} {% endif %} </span> </div> <h2 class="mb-1">{{ job.price }}円</h2> </div> </div> </div> </div> </a> {% endfor %} {% else %} <div class="card"> <div class="card-body text-center"> 表示できる配達依頼がありません </div> </div> {% endif %} </div> {% endblock %}
配達依頼の確認ページができました。
↓↓クリックして頂けると励みになります。
【32 | 支払い】 << 【ホーム】 >> 【34 | 配達依頼詳細ページ】