投稿時間:2022-05-01 17:21:58 RSSフィード2022-05-01 17:00 分まとめ(27件)

カテゴリー等 サイト名等 記事タイトル・トレンドワード等 リンクURL 頻出ワード・要約等/検索ボリューム 登録日
IT 気になる、記になる… 2022年4月のWebブラウザやOSのシェア https://taisy0.com/2022/05/01/156485.html statcounter 2022-05-01 07:46:23
AWS lambdaタグが付けられた新着投稿 - Qiita AWS Lambda Function URLsでEverything(It's you)をおうむ返しするLINE bot https://qiita.com/h2m_kinoko/items/c82ade553f5e1e112ad9 everythingitsyou 2022-05-01 16:23:29
python Pythonタグが付けられた新着投稿 - Qiita BigQueryの操作。pandas.DataFrameで。 https://qiita.com/yo16/items/1e7ed021aa6568828e94 bigquery 2022-05-01 16:38:48
AWS AWSタグが付けられた新着投稿 - Qiita 【AWS】AutoScaling検証 https://qiita.com/ramusesu701/items/47bd944e8eec5bb4c105 autosc 2022-05-01 16:32:18
AWS AWSタグが付けられた新着投稿 - Qiita AWS Lambda Function URLsでEverything(It's you)をおうむ返しするLINE bot https://qiita.com/h2m_kinoko/items/c82ade553f5e1e112ad9 everythingitsyou 2022-05-01 16:23:29
Docker dockerタグが付けられた新着投稿 - Qiita コンテナの基盤技術 Namespace 入門 https://qiita.com/sasamuku/items/8f09307dc9bdfe26a2db cgroups 2022-05-01 16:11:58
golang Goタグが付けられた新着投稿 - Qiita Goで安価なAPIサーバーをデプロイする https://qiita.com/ymktmk/items/8075a456beeb3fdf2e05 fargate 2022-05-01 16:56:10
GCP gcpタグが付けられた新着投稿 - Qiita BigQueryの操作。pandas.DataFrameで。 https://qiita.com/yo16/items/1e7ed021aa6568828e94 bigquery 2022-05-01 16:38:48
GCP gcpタグが付けられた新着投稿 - Qiita 権限管理から考えるBiglake Tableの利点 https://qiita.com/Ta_Kimura_de/items/9d8ce03ae5fda152d6b9 biglake 2022-05-01 16:02:03
Git Gitタグが付けられた新着投稿 - Qiita 初めて git rebase してみた https://qiita.com/comachi/items/1fe3e98dcbf803b85f1b githubdesktop 2022-05-01 16:56:07
海外TECH DEV Community Django Charts via DRF - Step-by-Step Tutorial https://dev.to/sm0ke/django-charts-via-drf-and-chartjs-with-samples-4dh0 Django Charts via DRF Step by Step TutorialHello Coders Django is a powerful web framework built with Python that you can use to create fully functional web applications or web APIs This article explains step by step how to showcase three different charts pie line and bar chart using Django Django REST Framework and Chart js The content presents all layers and concepts API JS Html and also provides the link to the source code saved on Github Thanks for reading Content provided by App Generator Setup the Django projectWriting the app modelsLoad sample dataCode the serializersWriting the API via DRFCode the Javascript partUpdate Configuration and routingDjango Charts via DRF source codeMore Django Apps and DashboardsFree support via email and Discord Setup the projectBefore going make sure that first of all let s set up the project Feel free to use your favorite python environment management tool I ll be using virtualenv here virtualenv env source env bin activateAfter that we install the libraries we ll be using for the development and create the project pip install django pip install djangorestframework pip install djangorestframework simplejwt pip install django import exportCreate the project django admin startproject coreWe ll first create an app that will contain all the project specific features django admin startapp appsAfter creating delete all files and folders except init py views py models py and apps py Then open the settings file containing Django configurations and add core to the INSTALLED APPS core settings py django contrib messages django contrib staticfiles apps Great Ensure that the project is well set up by running the following commands python manage py makemigrations python manage py migrateAfter that run the following command to start the server python manage runserverIf you access localhost we should see the Django default splash screen Writing the modelsThis project will contain two models The User model And the Product model Following the figure we notice that the models have the same fields as created and updated Before creating the application for each feature user and product let s create a base model that will be used by the User model and the Product model In the apps models py add the following content from django db import modelsfrom django utils import timezoneclass BaseModel models Model created models DateTimeField default timezone now updated models DateTimeField auto now True class Meta abstract TrueThe abstract True makes sure that no migrations are generated for this model Let s move to write the User model User modelBefore writing the model we need to create a Django application In the apps directory enter the following command django admin startapp userOnce it s done rewrite the apps user apps py file from django apps import AppConfigclass UserConfig AppConfig default auto field django db models BigAutoField name apps user label apps user And we can register the application in the settings py file now INSTALLED APPS django contrib admin django contrib auth django contrib contenttypes django contrib sessions django contrib messages django contrib staticfiles apps lt OLD apps user lt NEW import export rest framework Let s write the User model now based on the BaseModel class from django contrib auth models import AbstractUserfrom django db import modelsfrom apps models import BaseModel class User AbstractUser BaseModel has purchased models BooleanField default False Django provides a class called AbstractUser that comes with the following fields username models CharField username max length unique True help text Required characters or fewer validators username validator error messages unique A user with that username already exists first name models CharField first name max length blank True last name models CharField last name max length blank True email models EmailField email address blank True is staff models BooleanField staff status default False help text Designates whether the user can log into this admin site is active models BooleanField active default True help text Designates whether this user should be treated as active date joined models DateTimeField date joined default timezone now It s very effective for what we want here We are also adding a new field has purchased to track a user who has made at least a purchase on the API Before running the migrations and committing the changes to the database let s add in the settings py a configuration for the AUTH USER MODEL that will be used by Django AUTH USER MODEL apps user User Now run the following commands python manage py makemigrations python manage py migrateWith the User model added let s write a custom admin class to allow data importation with files django import export is a Django application and library for importing and exporting data with included admin integration In the apps user admin py add the following content from django contrib import adminfrom import export import resourcesfrom import export admin import ImportMixinfrom apps user models import Userclass UserResource resources ModelResource class Meta model User fields id username email has purchased created updated admin register User class UserAdmin ImportMixin admin ModelAdmin resource class UserResource list display id username email has purchased created updated list filter has purchased search fields username email A resource defines how objects are mapped to their import and export representations and handle importing and exporting data In this filed we declare the UserResource class containing the model and the fields needed when data is imported The UserAdmin class also takes the fields displayed the field used for filtering data and the fields used for search Product ModelBefore writing the Product model let s create a Django application called product django admin startapp product After the application has been created modify the apps py file in the product directory from django apps import AppConfig class ProductConfig AppConfig default auto field django db models BigAutoField name apps product label apps product And then let s register the application in the settings py file INSTALLED APPS django contrib admin django contrib auth django contrib contenttypes django contrib sessions django contrib messages django contrib staticfiles apps apps product lt NEW apps user import export rest framework We can now write the Product model from django db import modelsfrom apps models import BaseModelclass Product BaseModel name models CharField max length description models TextField price models DecimalField max digits decimal places quantity sold models IntegerField default def str self return self nameWe will also write a custom admin class for the Product model In the apps product admin py add the following content from django contrib import adminfrom import export import resourcesfrom import export admin import ImportMixinfrom apps product models import Productclass ProductResource resources ModelResource class Meta model Product fields id name price description created admin register Product class ProductAdmin ImportMixin admin ModelAdmin resource class ProductResource list display id name price description created updated list filter created search fields name Well with both product admin and user admin written we can now move to load the sample data in the database using the admin section import export feature Load Sample DataDjango provides an admin dashboard that you can use to manage resources models users groups from our Django project But before accessing the dashboard you need admin credentials In the shell enter the following command to create a new superuser django admin createsuperuserOnce the superuser is created we can access the admin section of our project localhost admin After you have successfully logged in you ll see a similar page Let s upload data for the users first Clicking on Add you ll be redirected to the following page You ll normally see the first user that is the superuser you ve just created Great now click on import You ll have to import a CSV file You can find an example of this file here Once the file is imported click on Confirm Import Your database is now filled with some users data The next step is to load the products data using the same import feature over the Products using the sample data Writing serializersSerializer allows us to convert Django data structures such as query sets or model instances in Python native objects that can be easily converted to JSON XML format Let s start by writing a serializer for the User model User serializerInside the apps user create a file called serializers py This file will contain a class called UserSerializer from rest framework import serializersfrom apps user models import Userclass UserSerializer serializers ModelSerializer class Meta model User fields id username email has purchased The ModelSerializer helps write serializers based on models very easier It automatically matches the fields and their types and even adds some automatic validations Product serializerInside the apps product directory create a file called serializers py This file will contain a model serializer called ProductSerializer from rest framework import serializersfrom apps product models import Product class ProductSerializer serializers ModelSerializer class Meta model Product fields id name price description created updated Great Now that we have serializers we can write viewsets Writing viewsetsA viewset is a class based view able to handle all of the basic HTTP requests GET POST PUT DELETE without hard coding any of the logic We are using viewsets here to configure the routing for the API easily The user viewset should allow the following structure And the product resource will have the following structure Writing User viewsetInside the apps user directory create a file called viewsets py The file will contain a class called UserViewSet import calendarfrom rest framework import viewsetsfrom rest framework response import Responsefrom rest framework import statusfrom rest framework decorators import actionfrom apps user models import Userfrom apps user serializers import UserSerializerclass UserViewSet viewsets ModelViewSet http method names get queryset User objects all serializer class UserSerializer action detail False methods get url path stats purchased def purchase stats self request args kwargs users User objects filter has purchased True return Response total users User objects count total purchased users count purchased percentage round users count User objects count status status HTTP OK action detail False methods get url path stats users created def user created per month self request args kwargs users User objects all months for user in users months append user created date month months list set months months sort data for month in months data append month calendar month name month count User objects filter created month month count return Response data status status HTTP OK In this viewset we are allowing only GET requests And we are also adding custom actions to the viewset such as purchase stats and user created per month These actions compute and return some useful stats Let s do the same for the ProductViewSet Writing Products viewsetInside the apps product directory create a file called viewsets py This file will contain the ProductViewSet class import calendarfrom rest framework import viewsetsfrom rest framework response import Responsefrom rest framework import statusfrom rest framework decorators import actionfrom apps product models import Productfrom apps product serializers import ProductSerializerclass ProductViewSet viewsets ModelViewSet http method names get queryset Product objects all serializer class ProductSerializer action detail False methods get url path sales def sales over month self request args kwargs products Product objects all months for product in products months append product created date month months list set months months sort data for month in months data append month calendar month name month count Product objects filter created month month count return Response data status status HTTP OK Great With the view sets ready we can register these view sets to create endpoints and start making requests Writing API EndpointsAs we are working with viewsets we can automatically register the API endpoints using routers Inside the apps directory create a file called routers py from rest framework import routersfrom apps user viewsets import UserViewSetfrom apps product viewsets import ProductViewSetrouter routers SimpleRouter router register user UserViewSet router register product ProductViewSet urlpatterns router urls We need then to register this file in the urls py file of the project And then these endpoints will be accessible even via the browser from django contrib import adminfrom django urls import path includeurlpatterns path admin admin site urls path api include apps routers api namespace api Great After that make sure the server is running because we will start making some requests Integrating Chart JSChart js is a JavaScript library that makes working and building charts easier In this project we ll use this library to display line bar and pie charts The data displayed on the charts will come from the REST API we ve just built and we ll be using Axios to fetch data from the server But first let s make some configurations for the Django templating system and the static file such as the JavaScript file that will contain the logic for data fetching and charts configuration ConfigurationFirst of all make sure you have the following configuration for TEMPLATES in the settings py file TEMPLATES BACKEND django template backends django DjangoTemplates DIRS os path join BASE DIR apps templates APP DIRS True OPTIONS context processors django template context processors debug django template context processors request django contrib auth context processors auth django contrib messages context processors messages The templates will be created in the apps template directory Also we need the following configuration for static files STATIC URL static STATICFILES DIRS os path join BASE DIR static Index html Product HOMEpageIn the apps templates create a file called index html We ll just add basic imports for bootstrap axios and chartjs lt html lang en gt lt head gt lt meta charset utf gt lt Chart JS gt lt link href dist css bootstrap min css gt lt Chart JS gt lt script src gt lt script gt lt Axios gt lt script src gt lt script gt lt title gt Stats lt title gt lt head gt lt body gt lt h class text center gt Product Stats lt h gt lt div class row gt lt LINE Chart gt lt div class col mr gt lt h class text center gt User created over months lt h gt lt canvas id user created gt lt canvas gt lt div gt lt Bar Chart gt lt div class col ml gt lt h class text center gt Product sales over months lt h gt lt canvas id product sales gt lt canvas gt lt div gt lt PIE Chart gt lt div class col mx auto gt lt h class text center gt Percentage of users who bought a product lt h gt lt canvas id user purchased gt lt canvas gt lt div gt lt div gt Once we have a minimum HTML file we need to code the JS code that consumes the API and injects the data into the charts Index JS Charts and APIAt the root of the project create a directory called static Inside this directory create another directory called js This directory will contain the static JavaScript files And finally create a index js file in the newly created directory Let s write the steps needed for fetching and configuring charts Adding a function to fetch data and return a responseRetrieve data from each endpointInitialize the data with labelsInitialize the chart configurationAnd finally create a chart in the DOM Let s break down each step and visualize the necessary code to properly render our beautiful charts Adding a function to fetch data and return a responseasync function getData url const res await axios get url return await res data Retrieve data from each endpointlet userPurchased let productSales let userCreated Fetching data for users that have purchased productsuserPurchased getData api user stats purchased Fetching data for users created over monthuserCreated getData api user stats users created Fetching data for products sold over monthproductSales getData api product sales Inject the data into ChartsLet s initialize the data with labels initialize the chart configuration and finally create a chart in the DOM for the userCreate for example userCreated then response gt const dataUserCreated labels response map data gt data month datasets label Users that have purchased products backgroundColor rgb borderColor rgb data response map data gt data count const configUserCreated type line data dataUserCreated options Creating new chart new Chart document getElementById user created configUserCreated And let s do the same for userPurchased and the productSales productSales then response gt const dataProductSales labels response map data gt data month datasets label Products sold data response map data gt data count borderWidth backgroundColor rgb const configProductSales type bar data dataProductSales options scales y beginAtZero true new Chart document getElementById product sales configProductSales userPurchased then response gt const dataUserPurchased labels Total Users Total Purchased Purchased percentage datasets label Users created data Object values response backgroundColor rgb rgb rgb hoverOffset const configUserPurchased type pie data dataUserPurchased new Chart document getElementById user purchased configUserPurchased Once the JS part is fully coded the last step is to update the product routing and start using the project In the apps directory create a views py file and add the following content from django template import loaderfrom django shortcuts import renderdef index request context segment index return render request index html context And add the urls py to the apps directory with the following content from django urls import pathfrom import viewsurlpatterns The home page path views index name home And register the apps urls py in the project urls py file urlpatterns path admin admin site urls path include apps urls path api include apps routers api namespace api Make sure the server is running then and visit the app in the browser At this point we should see the three charts beautifully rendered on the home page ConclusionIn this article we ve learned to build an API that serves statistics using Django and Django REST Framework DRF We ve also created an HTML template to display data served by the REST API using Chart js and Axios Thanks for reading For more resources feel free to access More Free Dashboards crafted in Django Flask and ReactMore Admin Dashboards a huge index with products 2022-05-01 07:04:00
海外ニュース Japan Times latest articles Questions grow over communications system used by Hokkaido tour operator https://www.japantimes.co.jp/news/2022/05/01/national/sunken-boat-exposes-flaw-communications-system-tour-operator/ Questions grow over communications system used by Hokkaido tour operatorThe mobile phone belonging to the tour boat s captain was unreachable during most of the vessel s fateful final voyage sources have said 2022-05-01 16:26:25
海外ニュース Japan Times latest articles Japan and Vietnam underscore opposition to use of force amid Ukraine war https://www.japantimes.co.jp/news/2022/05/01/national/kishida-vietnam-visit-ukraine-war/ Japan and Vietnam underscore opposition to use of force amid Ukraine warVietnamese leader Pham Minh Chinh announced Vietnam s first aid package for Ukraine during a visit by Kishida a move the prime minister hailed as a 2022-05-01 16:45:38
海外ニュース Japan Times latest articles Japan eyes classifying defense guidelines amid China and Russia threats https://www.japantimes.co.jp/news/2022/05/01/national/japan-eyes-classifying-defense-guidelines-amid-china-russia-threats/ Japan eyes classifying defense guidelines amid China and Russia threatsMaking the National Defense Program Guidelines confidential would enable Japan to be more specific in its strategy toward contingencies involving Taiwan and North Korea 2022-05-01 16:22:11
ニュース BBC News - Home Westminster reform: Lindsay Hoyle and Andrea Leadsom call for urgent changes https://www.bbc.co.uk/news/uk-politics-61287794?at_medium=RSS&at_campaign=KARANGA parish 2022-05-01 07:31:58
ニュース BBC News - Home Ukraine war: British ambassador 'comfortable' to be back in Kyiv https://www.bbc.co.uk/news/uk-61289547?at_medium=RSS&at_campaign=KARANGA melinda 2022-05-01 07:24:05
北海道 北海道新聞 タイトルホルダーが優勝 競馬の天皇賞・春 https://www.hokkaido-np.co.jp/article/676268/ 阪神 2022-05-01 16:32:00
北海道 北海道新聞 楽2―1ソ(1日) 楽天が4連勝 https://www.hokkaido-np.co.jp/article/676267/ 降雨 2022-05-01 16:32:00
北海道 北海道新聞 道南で86人感染 新型コロナ https://www.hokkaido-np.co.jp/article/676266/ 道南 2022-05-01 16:25:00
北海道 北海道新聞 車衝突で児童1人が重体、福岡 計8人を搬送 https://www.hokkaido-np.co.jp/article/676226/ 福岡県小郡市希みが丘 2022-05-01 16:22:05
北海道 北海道新聞 高病原性鳥インフル 様似と紋別で検出 https://www.hokkaido-np.co.jp/article/676265/ 日高管内 2022-05-01 16:17:00
北海道 北海道新聞 北京ユニバーサル休園 コロナ対策で、再開未定 https://www.hokkaido-np.co.jp/article/676263/ 未定 2022-05-01 16:13:00
北海道 北海道新聞 前大統領出席なら「政変」 バイデン氏、夕食会でやゆ https://www.hokkaido-np.co.jp/article/676262/ 前大統領 2022-05-01 16:12:00
北海道 北海道新聞 北海道内1854人感染 6日ぶり2千人下回る 死亡なし 新型コロナ https://www.hokkaido-np.co.jp/article/676258/ 北海道内 2022-05-01 16:08:09
ビジネス 東洋経済オンライン 3年前のウクライナの記憶に辿る戦時対応の背景 オックスフォードのディベートの観点から考える | ウクライナ侵攻、危機の本質 | 東洋経済オンライン https://toyokeizai.net/articles/-/584287?utm_source=rss&utm_medium=http&utm_campaign=link_back 日本のメディア 2022-05-01 16:17:00
ビジネス 東洋経済オンライン 「わずかな報酬」「生還保証なし」で成功の求人広告 非日常性を与えて「ひらめき」を生む戦略質問 | リーダーシップ・教養・資格・スキル | 東洋経済オンライン https://toyokeizai.net/articles/-/583985?utm_source=rss&utm_medium=http&utm_campaign=link_back 取りまとめ 2022-05-01 16:03:00
IT 週刊アスキー セブンイレブンの「おにぎり」具材増量中! GW期間中限定、定番人気が具たっぷりに https://weekly.ascii.jp/elem/000/004/090/4090701/ 販売開始 2022-05-01 16:15:00

コメント

このブログの人気の投稿

投稿時間:2021-06-17 05:05:34 RSSフィード2021-06-17 05:00 分まとめ(1274件)

投稿時間:2021-06-20 02:06:12 RSSフィード2021-06-20 02:00 分まとめ(3871件)

投稿時間:2020-12-01 09:41:49 RSSフィード2020-12-01 09:00 分まとめ(69件)