Important Announcement
PubHTML5 Scheduled Server Maintenance on (GMT) Sunday, June 26th, 2:00 am - 8:00 am.
PubHTML5 site will be inoperative during the times indicated!

Home Explore revision-bds

revision-bds

Published by ditnepalpvt, 2021-08-22 13:15:32

Description: revision-bds

Search

Read the Text Version

Going Live This is your enroll_reminder command. The preceding code is as follows: • The Command class inherits from BaseCommand. • You include a help attribute. This attribute provides a short description of the command that is printed if you run the command python manage.py help enroll_reminder. • You use the add_arguments() method to add the --days named argument. This argument is used to specify the minimum number of days a user has to be registered, without having enrolled on any course, in order to receive the reminder. • The handle() command contains the actual command. You get the days attribute parsed from the command line. You use the timezone utility provided by Django to retrieve the current timezone-aware date with timezone.now().date(). (You can set the timezone for your project with the TIME_ZONE setting.) You retrieve the users who have been registered for more than the specified days and are not enrolled on any courses yet. You achieve this by annotating the QuerySet with the total number of courses each user is enrolled on. You generate the reminder email for each user and append it to the emails list. Finally, you send the emails using the send_ mass_mail() function, which is optimized to open a single SMTP connection for sending all emails, instead of opening one connection per email sent. You have created your first management command. Open the shell and run your command: python manage.py enroll_reminder --days=20 If you don't have a local SMTP server running, you can take a look at Chapter 2, Enhancing Your Blog with Advanced Features, where you configured SMTP settings for your first Django project. Alternatively, you can add the following setting to the settings.py file to make Django output emails to the standard output during development: EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' Let's schedule your management command so that the server runs it every day at 8 a.m. If you are using a UNIX-based system such as Linux or macOS, open the shell and run crontab -e to edit your crontab. Add the following line to it: 0 8 * * * python /path/to/educa/manage.py enroll_reminder --days=20 --settings=educa.settings.pro If you are not familiar with cron, you can find an introduction to cron at http:// www.unixgeeks.org/security/newbie/unix/cron-1.html. [ 526 ]

Chapter 14 If you are using Windows, you can schedule tasks using the Task Scheduler. You can find more information about it at https://docs.microsoft.com/en-us/ windows/win32/taskschd/task-scheduler-start-page. Another option for executing actions periodically is to create tasks and schedule them with Celery. Remember that you used Celery in Chapter 7, Building an Online Shop, to execute asynchronous tasks. Instead of creating management commands and scheduling them with cron, you can create asynchronous tasks and execute them with the Celery beat scheduler. You can learn more about scheduling periodic tasks with Celery at https://celery.readthedocs.io/en/latest/userguide/ periodic-tasks.html. Use management commands for standalone scripts that you want to schedule with cron or the Windows scheduler control panel. Django also includes a utility to call management commands using Python. You can run management commands from your code as follows: from django.core import management management.call_command('enroll_reminder', days=20) Congratulations! You can now create custom management commands for your applications and schedule them when needed. Summary In this chapter, you configured a production environment using NGINX, uWSGI, and Daphne. You secured your environment through SSL/TLS. You also implemented a custom middleware and you learned how to create custom management commands. You have reached the end of this book. Congratulations! You have learned the skills required to build successful web applications with Django. This book has guided you through the process of developing real-life projects and integrating Django with other technologies. Now you are ready to create your own Django project, whether it is a simple prototype or a large-scale web application. Good luck with your next Django adventure! [ 527 ]



Other Books You May Enjoy If you enjoyed this book, you may be interested in these other books by Packt: Pandas 1.x Cookbook - Second Edition Matt Harrison, Theodore Petrou ISBN: 978-1-83921-310-6 ● Master data exploration in pandas through dozens of practice problems ● Group, aggregate, transform, reshape, and filter data ● Merge data from different sources through pandas SQL-like operations ● Create visualizations via pandas hooks to matplotlib and seaborn ● Use pandas, time series functionality to perform powerful analyses ● Create workflows for processing big data that doesn't fit in memory [ 529 ]

Other Books You May Enjoy Advanced Deep Learning with TensorFlow 2 and Keras - Second Edition Rowel Atienza ISBN: 978-1-83882-165-4 ● Use mutual information maximization techniques to perform unsupervised learning ● Use segmentation to identify the pixel-wise class of each object in an image ● Identify both the bounding box and class of objects in an image using object detection ● Learn the building blocks for advanced techniques - MLPss, CNN, and RNNs ● Understand deep neural networks - including ResNet and DenseNet ● Understand and build autoregressive models – autoencoders, VAEs, and GANs ● Discover and implement deep reinforcement learning methods [ 530 ]

Other Books You May Enjoy Leave a review - let other readers know what you think Please share your thoughts on this book with others by leaving a review on the site that you bought it from. If you purchased the book from Amazon, please leave us an honest review on this book's Amazon page. This is vital so that other potential readers can see and use your unbiased opinion to make purchasing decisions, we can understand what our customers think about our products, and our authors can see your feedback on the title that they have worked with Packt to create. It will only take a few minutes of your time, but is valuable to other potential customers, our authors, and Packt. Thank you! [ 531 ]



Index Symbols AJAX pagination adding, to list view 181-185 __str__() method 12 __unicode__() method 13 AJAX requests performing, with jQuery 176-179 A with cross-site request forgery (CSRF) 174, 175 abstract model 366 activity stream AJAX view building, to follow users 196-198 displaying 206, 207 add() method, parameters ALLOWED_HOSTS setting reference link 132, 508 override_quantity 242 product 242 application 9 quantity 242 application configuration classes administration site creating, for models 15 about 213-215 custom actions, adding 284-286 reference link 213 Django administration site 16 asynchronous applications extending, with custom views 287, 290 ASGI, using 471 models, adding 17, 18 asynchronous consumer models, customizing 19, 21 modifying 494, 495 superuser, creating 15 Asynchronous Server Gateway Interface administration templates reference link 290 (ASGI) 2, 516 aggregation asynchronous tasks reference link 64 aggregation functions adding, to application 265-267 average value (Avg) 64 launching, with Celery 263 count value (Count) 64 authentication backend, methods maximum value (Max) 64 authenticate() 129 minimum value (Min) 64 get_user() 129 reference link 72 AJAX actions B adding, with jQuery 172, 173 AJAX GET request, scenario base classes, Django response, with data 184 Form 40 response, with no content 184 Model Form 40 blog data schema application, activating 13 designing 10, 11 migrations, applying 13, 14 migrations, creating 13, 14 [ 533 ]

blog data schema, fields per-site cache 436 author 12 per-view cache 436 body 12 template cache 436 created 12 cache settings 434 publish 12 canonical URL slug 11 for models 29 status 12 CartAddProductForm class, fields title 11 override 245 updated 12 quantity 245 cart detail page 347 blog posts catalog templates used, for creating feeds 80, 81 creating 233-237 Celery bookmarklet adding, to project 264, 265 building, with jQuery 160-167 asynchronous tasks, launching 263 installing 263 Braintree monitoring 267, 268 integrating, with Hosted Fields 274-280 reference link 263 URL 270 certification authority (CA) 513 channel layer Braintree account consumer, updating to broadcast creating 283 reference link 283 messages 486-490 context, adding to messages 490-493 Braintree Python module enabling 484 installing 271, 272 setting up, with Redis 484, 486 channel layer, abstractions Braintree sandbox account channel 484 creating 270, 271 group 484 reference link 271 Channels installing 473-475 built-in authentication views using, in Real-time Django 471 reference link 102 using, in request/response cycle 472, 473 chat application built-in signals creating 467, 468 reference link 211 chat room view implementing 468-470 built-in template, tags and filters chat server reference link 31 implementing 475 integrating, with existing views 495 C class-based views access, restricting 385-391 cache backends 432, 433 features 36 cache framework reference link 37 using 36-38 cache backends 432, 433 comma-separated values (CSV) 284 cache levels 436 comment system cache settings 434 comments, adding to post detail low-level cache API, using 436-438 Memcached backend, adding to project 434 Memcached backend, installing 433 template fragments, caching 440 using 432 views, caching 441 cache levels about 436 low-level cache API 436 [ 534 ]

template 54-57 OrderField class, adding to module 372-377 creating 50 registering, in administration site 361 forms, creating from models 52 course modules model, building 50-52 content, adding 396-402 ModelForms, handling in views 53, 54 content, managing 391-406 consumer content, reordering 407 writing 476, 477 formsets, using 391-396 content managing 391-406 posting, from other websites 153, 154 reordering 407 content management system (CMS) courses authentication system, adding 377 displaying 414-419 authentication templates, creating 378-380 enrolling 422-425 class-based views, creating 381 credit cards, testing creating 377 reference link 282 groups, working with 383, 384 cron mixins, using for class-based views 381-383 about 526 permissions, working with 384, 385 reference link 526 contents of directory cross-site request forgery (CSRF) reference link 162 about 46 contenttypes framework in AJAX requests 174, 175 reference link 201 reference link 46 using 200, 201 CSRF protection context processor reference link 175 about 252 CSV files creating 252 orders, exporting to 284 reference link 253 CSV files, generating with Django shopping cart, setting into request reference link 287 curl context 253, 254 download link 449 coupon custom actions adding, to administration site 284-286 applying, to orders 312, 313 custom authentication backend applying, to shopping cart 304-311 building 128-130 coupon model custom decorators building 302-304 creating, for views 179, 180 coupon system customer orders creating 301 creating 258-263 course contents order models, creating 255, 256 accessing 425-429 order models, in administration site 257, 258 course models registering 255 building 359, 360 customizing authentication content model, creating 368, 369 reference link 129 creating, for diverse content 365 custom management commands custom model fields, creating 370, 372 reference link 524 fixtures, used for providing initial custom model fields, writing reference link 372 data 362, 364 custom template filters model inheritance, using 366 OrderField class, adding to content objects 373-377 [ 535 ]

about 73-75 login view, creating 96-101 creating 68 login views 103-107 reference link 76 logout views 102-107 custom template tags password views, changing 108-110 about 68-73 password views, resetting 110-114 creating 68 using 95 reference link 73 Django authentication framework, models custom user model group model 96 reference link 125, 190 permission 96 using 125 user model 96 custom views django-braces used, for extending administration mixins, using 407-410 reference link 407 site 287, 290 Django, deploying with web servers Cygwin reference link 7 Django, developing with ASGI URL 502 reference link 472 django-embed-video application's D documentation database, executing with Django reference link 431 reference link 2 Django, field types reference link 12 database indexes django-localflavor reference link 151 using, to validate form fields 345, 346 django-parler decorators, concept installing 336 reference link 179 translations, integrating into administration detail view site 339 building 26 used, for translating models 336 canonical URL, for models 29 django-parler module's compatibility, with creating 26, 27 creating, for user profiles 191-194 Django URL patterns, adding 28, 29 reference link 339 Django project directory's contents about 9 reference link 31 check management command 501 connections, securing with SSL/TLS dispatch() method 398 Django certificate 511 creating 4-6 installation link 4 custom management commands, installing 2 installing, with pip package 3, 4 implementing 524-527 language, determining 316, 317 Daphne, executing in NGINX translations, adding 316 used, for creating forms 40, 41 configuration 518-520 used, for sending emails 43-45 Daphne, using for Django Channels 516, 517 used, in internationalization 315 development server, executing 6, 7 Django application middleware, creating 520, 521 about 9 multiple environments settings, creating 10 Django authentication framework managing 498-500 authentication views, using 101, 102 [ 536 ]

NGINX, configuring 506-508 dynamic data NGINX, installing 505 caching 438, 439 PostgreSQL, using 500, 501 production environment, creating 497, 506 E secure connections, using for easy-thumbnails WebSockets 517 reference link 172 serving, through WSGI 501, 502 used, for creating image thumbnails 170, 171 static and media assets, serving 509-511 uWSGI, configuring 502-505 e-learning project uWSGI, installing 502 setting up 358 Django project, settings about 8 emails ALLOWED_HOSTS 8 sending, with Django 43-45 DATABASES 8 DEBUG 8 F INSTALLED_APPS 8 LANGUAGE_CODE 9 Facebook developer account MIDDLEWARE 8 reference link 134 reference link 8 ROOT_URLCONF 8 features, URL patterns USE_TZ 9 language prefix 332 Django REST framework translated 332 reference link 444 Django REST framework, features feeds reference link 461 creating, for blog posts 80, 81 Django REST framework, settings reference link 445 fields, Action model Django's built-in template filters creating 199 reference link 73 target 202 Django's cache system target_ct 202 reference link 432 target_id 202 Django sessions user 199 expiration 240 verb 199 settings 239 used, for storing shopping carts 240-44 fields, ContentType model using 238 app_label 200 Django syndication feed framework model 200 reference link 82 name 200 Django, tagging reference link 58 fields, generic relations in model django-taggit managers ForeignKey field 201 reference link 66 GenericForeignKey field 201 Django template language PositiveIntegerField 201 reference link 30 Document Object Model (DOM) 174 fixtures 362 duplicate actions fixtures usage, for testing avoiding, in activity stream 204, 205 reference link 364 Flower dashboard reference link 268 follow system AJAX view, building to follow users 196-198 building 187 detail views, creating for user profiles 191-195 list views, creating for user profiles 191-195 [ 537 ]

many-to-many relationships, creating with H intermediary model 188-191 Haystack ForeignKey reference link 91 reference link 12 Homebrew format localization download link 433 about 344, 345 reference link 345 I form fields image bookmarking website cleaning 154, 155 creating 150 reference link 41 image model, building 150, 151 image model, registering in administration forms site 153 creating, with Django 40, 41 many-to-many relationships, creating 152 handling, in views 41, 42 rendering, in templates 45-49 image model building 150, 151 formsets registering, in administration site 153 reference link 392 image ranking full-text search storing, in Redis 220, 222 adding, to blog 82 reference link 90 images detail view, creating 168, 170 full-text search engine 91 Fuzzy translations 331 image thumbnails creating, with easy-thumbnails 170, 171 G internationalization generic activity stream application about 314 activity stream, displaying 206, 207 adding 314 building 198, 199 management commands 316 contenttypes framework, using 200, 201 project, preparing 317, 318 duplicate actions, avoiding in activity settings 315, 316 stream 204, 205 with Django 315 generic relations, adding to model 201-204 QuerySets, optimizing 207 item views templates, creating for actions 208-210 storing, with Redis 215, 218, 219 user actions, adding to activity stream 205, 206 J generic mixins and views jQuery reference link 447 download link 174 loading 173 generic relations reference link 160 adding, to model 201-204 used, for adding AJAX actions 172, 173 used, for building bookmarklet 160-167 get_form() method 398 used, for performing AJAX requests 176-179 get() method 398 get_model() method 397 jQuery selectors Gmail captcha, disabling reference link 164 reference link 44 JS Cookie Google's OAuth2 implementation reference link 175 reference link 142 [ 538 ]

L creating, for model translations 340, 341 mixins language code 315 language name 315 reference link 381 less secured applications, access enabling using, from django-braces 407-410 model API reference link 44 reference link 21 Lightweight Directory Access Protocol model fields translating 337, 338, 339 (LDAP) 128 model formsets list view reference link 392 model inheritance AJAX pagination, adding 181-185 abstract model 366 building 26 multi-table model inheritance 367 canonical URL, for models 29 proxy model 367 creating 26, 27 using 366 creating, for user profiles 191-195 model managers URL patterns, adding 28, 29 creating 25, 26 localization models about 314 translating, with django-parler 336 adding 314 multiple fields settings 315, 316 searching 84 low-level cache API multiple subdomains using 436-438 serving, with NGINX 523, 524 multi-table model inheritance 366 M N managers working with 21 NGINX binaries, for Windows reference link 505 many-to-many relationships creating 152 NGINX documentation creating, with intermediary model 188-191 reference link 507 reference link 61, 152 O many-to-one relationships reference link 51 object-relational mapper (ORM) 21 online shop project markdown format reference link 74 catalog templates, creating 233-237 creating 226 Memcached backend functionalities 226 adding, to project 434 product catalog models, creating 227-229 download link 433 product catalog models, registering on installing 433 monitoring 435 administration site 229 product catalog views, building 230-232 message file 315 orders messages framework exporting, to CSV files 284 reference link 128 using 125-128 middleware about 96 reference link 521 migrate management command 6 migrations [ 539 ]

P reference link 82 Postman pagination adding 34, 35 reference link 449 working 34 post() method 399 posts by similarity parsers reference link 447 retrieving 64-66 posts, via email path converters reference link 28 emails, sending with Django 43-45 forms, creating with Django 40, 41 payment authorization forms, handling in views 41, 42 reference link 283 forms, rendering in templates 45-49 sharing 40 Payment Card Industry (PCI) 270 prefetch_related() payment gateway using 208 product catalog models Braintree, integrating with Hosted creating 227-229 Fields 274-280 registering, on administration site 229 product catalog views Braintree Python module, installing 271, 272 building 230-232 Braintree sandbox account, product detail page 347 product recommendation 347-356 creating 270, 271 project 9 integrating 269-274 proxy model 366 payments Python testing 280-283 Redis, using 217, 218 PDF files Python 3.8.0 rendering 294-297 download link 2 sending, by email 297-300 Python code PDF invoices code translation 320-324 generating 292 lazy translation 319 PDFs, outputting with Django plural forms translation 319, 320 reference link 292 standard translation 319 PDF template translating 318 creating 292, 293 variable translation 319 permissions Python environment reference link 455 creating 3 per-site cache Python installer deactivating 471 download link 2 using 441, 442 Python Social Auth pip installation reference link 131 reference link 3 pip package Q used, for installing Django 3, 4 Poedit QuerySet download link 323 about 21 post detail template evaluating 25 comments, adding 54-57 exclude(), using 24 PostgreSQL download link 83 installing 83, 84 PostgreSQL full-text search [ 540 ]

filter() method, using 23 renderers objects, creating 21, 22 reference link 447 objects, deleting 24 objects, retrieving 23 Representational State Transfer (REST) 444 objects, updating 23 RequestContext order_by(), using 24 working with 21 reference link 254 QuerySets request cycle optimizing 207 prefetch_related(), using 208 Channels, using 472, 473 select_related(), using 207 request method R GET request 260 POST request 260 RabbitMQ Requests library documentation installing 264 reference link 462 response cycle RabbitMQ, installing on macOS/Windows Channels, using 472, 473 reference link 264 REST API consuming 461-464 ranking results 88 REST framework Real-time Django authentication backends 453 RESTful API with Channels 471 actions, adding to viewsets 457, 458 recommendation engine authentication, handling 453, 454 building 444 building 347 course contents, serializing 459-461 Redis custom API views, building 452, 453 custom permissions, creating 458, 459 about 223 Django REST framework, installing 444, 445 download link 215 list and detail views, building 447-450 image ranking, storing 220, 222 nested serializers, creating 450-452 installing 215-217 parsers 446, 447 item views, storing 218, 219 renderers 446, 447 used, for storing item views 215 routers, creating 456, 457 using, with Python 217, 218 serializers, defining 445, 446 Redis commands viewsets, creating 456, 457 reference link 217 views permissions, adding 454, 455 Redis, installing on Windows 10 Rosetta's documentation reference link 216 reference link 331 redis-py documentation Rosetta translation interface reference link 217 using 328-331 Redis, scenarios routers caching 223 reference link 457 counting 223 routing 477, 478 latest items, storing 223 pub/sub 223 S queues 223 rankings and leaderboards 223 save() method real-time tracking 223 overriding, of ModelForm 155-159 regular expressions reference link 29 SearchVectorField field [ 541 ]

reference link 85 creating 94 search view implementing 94, 95 Spanish formatting configuration building 85-87 reference link 344 Secure Sockets Layer (SSL) 133, 511 SSL/TLS certificate select_related() connections, securing with 511 creating 511, 512 using 207 Django project, configuring 514, 515 serializers HTTP traffic, redirecting to HTTPS 515, 516 used, for configuring NGINX 512-514 reference link 452 stemming 88 session data, options student registration adding 419 cached database sessions 239 view, creating 419-422 cached sessions 239 subdomain middleware cookie-based sessions 239 creating 522, 523 database sessions 239 file-based sessions 239 T settings, Django sessions reference link 240 tagging functionality shopping cart adding 58-63 building 237 context processor, creating 252 template filters 31 Django sessions, expiration 240 template fragments Django sessions, settings 239 Django sessions, using 238 caching 440 items, adding 245-247 templates products, adding 249, 250 products quantities, updating 251 {% blocktrans %} template tag 324, 325 storing, in Django sessions 240-244 creating, for actions 208-210 template, building to display items and creating, for views 30-33 forms, rendering 45-49 total 247, 249 shop templates, translating 325-328 views, creating 245 translating 324 signals {% trans %} template tag 324 application configuration classes 213-215 template tags 31 used, for denormalizing counts 210 template variables 31 working with 211-213 Transport Layer Security (TLS) 43, 132, 511 Simple Mail Transfer Protocol (SMTP) 43 trigram similarity simple search lookups 84 searching with 90 sitemap framework Twitter account adding 76-79 reference link 140 reference link 77 type of content social authentication rendering 429-431 adding 130-132 development server, executing through HTTPS U 132-134 URL namespaces Facebook, using 134-140 reference link 29 Google, using 142-147 reference link 131 URL patterns Twitter, using 140-142 for internationalization 332 social website project [ 542 ]

language prefix, adding 332, 333 reference link 115 translating 333, 334 URL patterns, with regular expressions reference link 29 URLs utility functions reference link 30 user actions adding, to activity stream 205, 206 user model extending 119-125 user profiles about 115 detail view, creating 191-195 list view, creating 191-195 user registration 115-119 users access, to switch language 334, 335 uWSGI options reference link 505 uWSGI's documentation reference link 502 V views adapting, for translations 341-344 caching 441 forms, handling 41, 42 templates, creating 30-33 viewsets reference link 457 virtual environment (venv) reference link 3 W WeasyPrint installing 292 reference link 292 Web Server Gateway Interface (WSGI) about 5,471 about 501 reference link 502 WebSocket client implementing 478-484 weighting queries 89 Windows Subsystem for Linux (WSL) 216 [ 543 ]


Like this book? You can publish your book online for free in a few minutes!
Create your own flipbook