This document summarizes advanced views and URL configurations in Django. It discusses streamlining function imports by importing the views module instead of individual functions. It also describes using strings to specify view functions in URL patterns instead of importing functions. Finally, it covers using multiple view prefixes, special casing URLs in debug mode, and using named groups to pass arguments to views.
This document provides information about Javier Eguiluz, a programmer and trainer from Spain who specializes in Symfony and Twig. It outlines his experience with Symfony and as the author of a popular Symfony book. The agenda covers tips, tricks, advanced features, best practices and new noteworthy features of the Twig templating engine.
The document discusses jQuery, a JavaScript library that simplifies HTML and JavaScript interactions. It allows selecting elements, handling events, animating elements, and making AJAX calls. Some key points covered include:
- jQuery simplifies DOM manipulation and event handling across browsers.
- Common tasks like selecting elements, handling events, and animating elements are simplified.
- jQuery supports AJAX and makes asynchronous requests easily.
- Plugins can be created using jQuery's plugin authoring features like $.fn.extend().
- The $.ajax() method forms the basis of all AJAX calls in jQuery and has many options to customize requests.
Object Oriented programming in Python.
Originally part 3 of a 4 lectures seminar for the Networking class of the Computer Science course at the University of Parma
Decorators in Python allow functions and methods to be modified by wrapping them in another callable object. Decorators provide a lightweight way to add reusable behavior to code. However, decorators can make functions difficult to test and introduce tight coupling. Alternatives like inheritance and mixins may provide a cleaner approach in some cases.
Python decorators allow functions and classes to be augmented or modified by wrapper objects. Decorators take the form of callable objects that process other callable objects like functions and classes. Decorators are applied once when a function or class is defined, making augmentation logic explicit and avoiding the need to modify call sites. Decorators can manage state information, handle multiple instances, and take arguments to customize behavior. However, decorators also introduce type changes and extra function calls that incur performance costs.
Swift 4 introduced KeyPaths, a literal syntax that allows developers to reference a property, in order to evaluate it later. Yet, for some reason, their addition went quite under the radar, and as of today they remain something of a hidden gem within the language.
In this talk, I aim to show you how KeyPaths can be used to implement simple yet useful patterns, like the Builder, but also how they can be the building foundation for more complex pieces of code, like a library to manipulate data in a very declarative SQL-like manner.
This document provides information about Javier Eguiluz, a programmer and trainer from Spain who specializes in Symfony and Twig. It outlines his experience with Symfony and as the author of a popular Symfony book. The agenda covers tips, tricks, advanced features, best practices and new noteworthy features of the Twig templating engine.
The document discusses jQuery, a JavaScript library that simplifies HTML and JavaScript interactions. It allows selecting elements, handling events, animating elements, and making AJAX calls. Some key points covered include:
- jQuery simplifies DOM manipulation and event handling across browsers.
- Common tasks like selecting elements, handling events, and animating elements are simplified.
- jQuery supports AJAX and makes asynchronous requests easily.
- Plugins can be created using jQuery's plugin authoring features like $.fn.extend().
- The $.ajax() method forms the basis of all AJAX calls in jQuery and has many options to customize requests.
Object Oriented programming in Python.
Originally part 3 of a 4 lectures seminar for the Networking class of the Computer Science course at the University of Parma
Decorators in Python allow functions and methods to be modified by wrapping them in another callable object. Decorators provide a lightweight way to add reusable behavior to code. However, decorators can make functions difficult to test and introduce tight coupling. Alternatives like inheritance and mixins may provide a cleaner approach in some cases.
Python decorators allow functions and classes to be augmented or modified by wrapper objects. Decorators take the form of callable objects that process other callable objects like functions and classes. Decorators are applied once when a function or class is defined, making augmentation logic explicit and avoiding the need to modify call sites. Decorators can manage state information, handle multiple instances, and take arguments to customize behavior. However, decorators also introduce type changes and extra function calls that incur performance costs.
Swift 4 introduced KeyPaths, a literal syntax that allows developers to reference a property, in order to evaluate it later. Yet, for some reason, their addition went quite under the radar, and as of today they remain something of a hidden gem within the language.
In this talk, I aim to show you how KeyPaths can be used to implement simple yet useful patterns, like the Builder, but also how they can be the building foundation for more complex pieces of code, like a library to manipulate data in a very declarative SQL-like manner.
This document discusses data validation models and different approaches to validation. It covers syntactic validation to check data type and format, as well as semantic validation to check if data makes sense. Various PHP libraries and frameworks are benchmarked for validation performance. Deferred validation using argument resolvers is recommended to ensure objects are always valid. Domain models should encapsulate semantic validation rules. Validation should occur as early as possible to catch errors quickly.
This document discusses how Vim can improve productivity for Perl coding. It provides examples of using Vim motions and modes like Normal mode, Insert mode, and Visual mode to efficiently edit code. It also covers Vim features like syntax highlighting, custom syntax files, key mappings, and text objects that are useful for Perl. The document advocates that Vim is a powerful editor rather than an IDE and highlights how it can save significant time compared to less efficient editing methods.
A lot of people using PHPunit for testing their source code. While I was observing my team
I recognized most of them are only using the standard ssertions like 'assertEquals()' or
'assertTrue()' and are complaining about how hard it is to test the code even when the tests are written first. This talk is about all the stuff not used on a daily basis. It shows you some nice features of PHPUnit and how to use them for your benefit.
Entities lifecycle is usually something more than create and delete. Models with which we are working on day to day basis change their state under some business circumstances. State machine patterns can be a powerful allay when solving this kind of problem. How does it look like? What are the pros and cons of state machine usage? What are the things that we should be beware of? I will answer these questions during my talk, together with practical differences between the most popular implementation.
This document discusses various PHP functions categorized into different groups like:
- Date Functions: date, getdate, setdate, Checkdate, time, mktime
- String Functions: strtolower, strtoupper, strlen, trim, substr, strcmp etc.
- Math Functions: abs, ceil, floor, round, pow, sqrt, rand
- User Defined Functions: functions with arguments, default arguments, returning values
- File Handling Functions: fopen, fread, fwrite, fclose to handle files
- Miscellaneous Functions: define, constant, include, require, header to define constants, include files etc.
The document discusses iterators in PHP. It begins by explaining what an iterator is and provides examples of using iterators to loop through arrays and files. It then discusses the benefits of using iterators over plain arrays, such as improved readability, ability to enforce structure, and better memory efficiency. The document also covers implementing iterators by having classes implement the Iterator interface and explains the different types of iterables in PHP like arrays, iterators, generators, and iterator aggregates.
This document discusses JavaScript functions and closures. It covers function syntax, arguments, context, and closures. Functions are the building blocks of JavaScript and can be declared in multiple ways. Functions are first-class objects that can be passed as arguments, assigned to variables, and returned from other functions. Closures allow functions to access variables from the scope in which they were declared even after that scope has closed. The most common misunderstanding with closures is that they store references to variables rather than copies.
If you thought Monads are a mystery, then this demonstration would show you how to evolve your code towards a Monad without knowing about it. This demo will neither go into any Category Theory nor begin with monadic laws. Instead, we will start with typical code that you see in your daily life as a developer, attempt to DRY (Don't Repeat Yourself) it up and eventually use Monad to remove duplication and verbosity. You'll also see how Monads make your code more declarative and succinct by sequencing the steps in your domain logic.
Also, we know in Java8 Checked Exceptions + λ == Pain! To be more precise, we will evolve a Try<t> (exception handling monad) which is missing in Java8, similar to one found in Scala.
New Symfony Tips & Tricks (SymfonyCon Paris 2015)Javier Eguiluz
This talk included tens of tips and tricks, new features and rarely used options for Symfony and its ecosystem. Besides the full-stack Symfony framework, other related technologies were mentioned, like Doctrine, Composer, Twig, PHPUnit and Monolog.
You’ve built a WordPress site or two (or 10), your installed plugins and themes to MOSTLY get what you want. Now you’re ready to learn the inner workings of WordPress and take your development to the next level. Jump into WordPress development and PHP by building a Plugin and learn to speak WordPress’ language: PHP.
The document discusses the keyword "this" in JavaScript and how its context depends on how functions are called. It provides various ways to avoid using "this", such as binding functions, using closures to access outer variables, and defining objects without "this". Avoiding "this" can make code clearer but uses more memory, while using "this" carefully enables features like inheritance. The overall message is to understand how "this" works and avoid it when possible or bind it when needed.
The document discusses FuseJS, a JavaScript framework that aims to improve performance and compatibility across browsers. It includes sandboxed native objects to prevent namespace pollution, modular builds, and various selector engines. It also details optimizations for quirks mode, events, caching, and performance benchmarks showing FuseJS has lower execution times than other frameworks.
The document discusses PHP regular expression functions including preg_filter(), preg_grep(), preg_last_error(), preg_match(), preg_match_all(), preg_replace(), preg_replace_callback(), preg_replace_callback_array(), preg_split(), and preg_quote(). It provides examples of how to use each function, describing what each returns or does. It also covers regular expression modifiers, patterns, and metacharacters.
This document provides an overview of functional programming using Underscore.js and Lo-Dash. It discusses key concepts of functional programming like pure functions, first class functions, and higher order functions. It then explains how Underscore.js and Lo-Dash support functional programming in JavaScript with functions like compose, map, reduce, filter, and utilities to work with functions as first class citizens. The document compares Underscore.js and Lo-Dash, noting Lo-Dash's better performance, larger feature set, and utilities like partial and result. It emphasizes applying functional concepts judiciously for benefits while avoiding rewriting all code to be purely functional.
Perl provides many powerful features and modules that allow developers to customize and extend the language. Some popular modules include Moose for object-oriented programming, TryCatch for exception handling inspired by Perl 6, and P5.10 features that backport Perl 6 functionality. While useful, some features like autoboxing and state variables could introduce subtle bugs if misused. Overall, Perl's extensibility makes it a very flexible language that can be adapted to many different use cases.
The document contains code snippets demonstrating various JavaScript language features, including: loops, closures, const, let, arrow functions, classes, modules, maps, sets, structs, and more. It is a reference guide for Eyal Vardi covering JavaScript syntax and semantics from ES5 through ES6/ES2015 standards. Each code block is preceded and followed by copyright and contact information for Eyal Vardi.
Functional programming languages promise to be easier to test and easier to debug. However, when learning the functional way we often try to translate our current techniques to another language. This is usually not easy and the end result is far from those promises we've heard. Early frustrations might even discourage from further learning.
In this talk I will show you two very simple patterns:
- Designing code around single data structure
- Dealing with impure parts of program like DBs, external services or IO
This should give beginners jump start for their first toy projects and further exploration.
The document discusses several ways to write recursive functions in Swift, including functions to calculate the factorial of a number, find the nth Fibonacci number, and determine if a number contains the digit 7. It also provides examples of using tail recursion to iterate over an array and reduce it to a single value, as well as using tail recursion with custom functions.
This document discusses forms in Django, including:
- Getting data from the request object and information about submitted data via request.GET and request.POST.
- Creating a ContactForm class with CharField and EmailField to represent the form fields.
- Validating form data and accessing cleaned data via the is_valid() and cleaned_data attributes.
- Rendering form fields and the entire form in different formats like HTML tables and lists.
- Improving the ContactForm by setting initial values, maximum lengths, and using Textarea for multi-line fields.
The document discusses Django's database API and how it improves upon directly writing SQL queries in views. It introduces Django models and shows how to define models for a book publishing example with books, authors, and publishers. Code examples are provided for defining the models, inserting data into the database, retrieving and filtering objects, and adding human-readable representations for models. The database API handles common boilerplate, abstracts away the database backend, and provides a Pythonic interface for working with data.
This document discusses data validation models and different approaches to validation. It covers syntactic validation to check data type and format, as well as semantic validation to check if data makes sense. Various PHP libraries and frameworks are benchmarked for validation performance. Deferred validation using argument resolvers is recommended to ensure objects are always valid. Domain models should encapsulate semantic validation rules. Validation should occur as early as possible to catch errors quickly.
This document discusses how Vim can improve productivity for Perl coding. It provides examples of using Vim motions and modes like Normal mode, Insert mode, and Visual mode to efficiently edit code. It also covers Vim features like syntax highlighting, custom syntax files, key mappings, and text objects that are useful for Perl. The document advocates that Vim is a powerful editor rather than an IDE and highlights how it can save significant time compared to less efficient editing methods.
A lot of people using PHPunit for testing their source code. While I was observing my team
I recognized most of them are only using the standard ssertions like 'assertEquals()' or
'assertTrue()' and are complaining about how hard it is to test the code even when the tests are written first. This talk is about all the stuff not used on a daily basis. It shows you some nice features of PHPUnit and how to use them for your benefit.
Entities lifecycle is usually something more than create and delete. Models with which we are working on day to day basis change their state under some business circumstances. State machine patterns can be a powerful allay when solving this kind of problem. How does it look like? What are the pros and cons of state machine usage? What are the things that we should be beware of? I will answer these questions during my talk, together with practical differences between the most popular implementation.
This document discusses various PHP functions categorized into different groups like:
- Date Functions: date, getdate, setdate, Checkdate, time, mktime
- String Functions: strtolower, strtoupper, strlen, trim, substr, strcmp etc.
- Math Functions: abs, ceil, floor, round, pow, sqrt, rand
- User Defined Functions: functions with arguments, default arguments, returning values
- File Handling Functions: fopen, fread, fwrite, fclose to handle files
- Miscellaneous Functions: define, constant, include, require, header to define constants, include files etc.
The document discusses iterators in PHP. It begins by explaining what an iterator is and provides examples of using iterators to loop through arrays and files. It then discusses the benefits of using iterators over plain arrays, such as improved readability, ability to enforce structure, and better memory efficiency. The document also covers implementing iterators by having classes implement the Iterator interface and explains the different types of iterables in PHP like arrays, iterators, generators, and iterator aggregates.
This document discusses JavaScript functions and closures. It covers function syntax, arguments, context, and closures. Functions are the building blocks of JavaScript and can be declared in multiple ways. Functions are first-class objects that can be passed as arguments, assigned to variables, and returned from other functions. Closures allow functions to access variables from the scope in which they were declared even after that scope has closed. The most common misunderstanding with closures is that they store references to variables rather than copies.
If you thought Monads are a mystery, then this demonstration would show you how to evolve your code towards a Monad without knowing about it. This demo will neither go into any Category Theory nor begin with monadic laws. Instead, we will start with typical code that you see in your daily life as a developer, attempt to DRY (Don't Repeat Yourself) it up and eventually use Monad to remove duplication and verbosity. You'll also see how Monads make your code more declarative and succinct by sequencing the steps in your domain logic.
Also, we know in Java8 Checked Exceptions + λ == Pain! To be more precise, we will evolve a Try<t> (exception handling monad) which is missing in Java8, similar to one found in Scala.
New Symfony Tips & Tricks (SymfonyCon Paris 2015)Javier Eguiluz
This talk included tens of tips and tricks, new features and rarely used options for Symfony and its ecosystem. Besides the full-stack Symfony framework, other related technologies were mentioned, like Doctrine, Composer, Twig, PHPUnit and Monolog.
You’ve built a WordPress site or two (or 10), your installed plugins and themes to MOSTLY get what you want. Now you’re ready to learn the inner workings of WordPress and take your development to the next level. Jump into WordPress development and PHP by building a Plugin and learn to speak WordPress’ language: PHP.
The document discusses the keyword "this" in JavaScript and how its context depends on how functions are called. It provides various ways to avoid using "this", such as binding functions, using closures to access outer variables, and defining objects without "this". Avoiding "this" can make code clearer but uses more memory, while using "this" carefully enables features like inheritance. The overall message is to understand how "this" works and avoid it when possible or bind it when needed.
The document discusses FuseJS, a JavaScript framework that aims to improve performance and compatibility across browsers. It includes sandboxed native objects to prevent namespace pollution, modular builds, and various selector engines. It also details optimizations for quirks mode, events, caching, and performance benchmarks showing FuseJS has lower execution times than other frameworks.
The document discusses PHP regular expression functions including preg_filter(), preg_grep(), preg_last_error(), preg_match(), preg_match_all(), preg_replace(), preg_replace_callback(), preg_replace_callback_array(), preg_split(), and preg_quote(). It provides examples of how to use each function, describing what each returns or does. It also covers regular expression modifiers, patterns, and metacharacters.
This document provides an overview of functional programming using Underscore.js and Lo-Dash. It discusses key concepts of functional programming like pure functions, first class functions, and higher order functions. It then explains how Underscore.js and Lo-Dash support functional programming in JavaScript with functions like compose, map, reduce, filter, and utilities to work with functions as first class citizens. The document compares Underscore.js and Lo-Dash, noting Lo-Dash's better performance, larger feature set, and utilities like partial and result. It emphasizes applying functional concepts judiciously for benefits while avoiding rewriting all code to be purely functional.
Perl provides many powerful features and modules that allow developers to customize and extend the language. Some popular modules include Moose for object-oriented programming, TryCatch for exception handling inspired by Perl 6, and P5.10 features that backport Perl 6 functionality. While useful, some features like autoboxing and state variables could introduce subtle bugs if misused. Overall, Perl's extensibility makes it a very flexible language that can be adapted to many different use cases.
The document contains code snippets demonstrating various JavaScript language features, including: loops, closures, const, let, arrow functions, classes, modules, maps, sets, structs, and more. It is a reference guide for Eyal Vardi covering JavaScript syntax and semantics from ES5 through ES6/ES2015 standards. Each code block is preceded and followed by copyright and contact information for Eyal Vardi.
Functional programming languages promise to be easier to test and easier to debug. However, when learning the functional way we often try to translate our current techniques to another language. This is usually not easy and the end result is far from those promises we've heard. Early frustrations might even discourage from further learning.
In this talk I will show you two very simple patterns:
- Designing code around single data structure
- Dealing with impure parts of program like DBs, external services or IO
This should give beginners jump start for their first toy projects and further exploration.
The document discusses several ways to write recursive functions in Swift, including functions to calculate the factorial of a number, find the nth Fibonacci number, and determine if a number contains the digit 7. It also provides examples of using tail recursion to iterate over an array and reduce it to a single value, as well as using tail recursion with custom functions.
This document discusses forms in Django, including:
- Getting data from the request object and information about submitted data via request.GET and request.POST.
- Creating a ContactForm class with CharField and EmailField to represent the form fields.
- Validating form data and accessing cleaned data via the is_valid() and cleaned_data attributes.
- Rendering form fields and the entire form in different formats like HTML tables and lists.
- Improving the ContactForm by setting initial values, maximum lengths, and using Textarea for multi-line fields.
The document discusses Django's database API and how it improves upon directly writing SQL queries in views. It introduces Django models and shows how to define models for a book publishing example with books, authors, and publishers. Code examples are provided for defining the models, inserting data into the database, retrieving and filtering objects, and adding human-readable representations for models. The database API handles common boilerplate, abstracts away the database backend, and provides a Pythonic interface for working with data.
The Django Book / Chapter 3: Views and URLconfsVincent Chien
This document summarizes key points from Chapter 3 of the Django Book about views and URLconfs in Django. It discusses that views are Python functions that take a request object and return an HttpResponse, and URLconfs are used to map URLs to their corresponding views. It provides an example of a basic "Hello World" view and URLconf configuration. It also explains how Django processes requests by matching the URL to patterns in the URLconf and calling the associated view function.
The Django Book chapter 4 templates (supplement)Vincent Chien
The document discusses Django's template inheritance system. It introduces a base template that defines common elements like the page header and footer. This base template uses block tags to denote sections that child templates can override. Two child templates are shown that extend the base template and override its title and content blocks to customize each page while maintaining a common layout. Template inheritance allows avoiding redundancy and making site-wide changes by modifying only the base template.
The Django Book - Chapter 6 the django admin siteVincent Chien
The document discusses customizing the Django admin site. It describes how to register models with the admin to make them editable, how to make fields optional by adding blank and null attributes, and how to customize field labels by adding a verbose_name. It also mentions customizing the display of objects on the admin change list by defining a custom ModelAdmin class and customizing the list_display attribute.
The document summarizes research into tractors as a product category and their target demographic market. Key insights include that John Deere is seen as an iconic American brand among older, white males aged 55-64 who value strength, practicality and self-reliance. The creative brief positions John Deere tractors as embodying American ideals and calls for increasing brand loyalty among this target group by emphasizing patriotism.
This document summarizes key concepts in behavioral ecology from a biology textbook chapter. It discusses innate behaviors like fixed action patterns, kinesis, taxis, migration, circadian rhythms, and signals. It also discusses learning and how it establishes links between experience and behavior, including examples like imprinting, habituation, and classical/operant conditioning. The overall focus is on analyzing animal behaviors from both proximate and ultimate perspectives to understand their evolution and importance for survival.
Invertebrates are animals that lack backbones and make up the majority of animal species. They exhibit a wide range of characteristics depending on the phylum. Key characteristics of early invertebrate phyla include radial symmetry (Cnidaria), a gastrovascular cavity (Cnidaria, Platyhelminthes), and lack of true tissues (Porifera). More complex bilaterian invertebrates show bilateral symmetry, complete digestive systems, nervous systems, and some have segmented bodies (Annelida) or shells (Mollusca). Invertebrates transition from simple single or few celled organisms to more complex forms with organ systems and tissues.
Behavioral ecology studies how animals respond to each other and their environment. There are innate behaviors that are genetically determined and do not require learning, such as kinesis, taxis, migration, hibernation, estivation, and circadian rhythms. These behaviors increase an animal's chances of survival and reproduction through directed movement toward resources or away from threats.
In this reality of the shows are given and also included details about shows in world and also in the india.
also the benifits and effects on students or youngsters also given
The document discusses functions in PHP, including defining functions, passing arguments to functions, returning values from functions, and using global variables. Some key points covered include:
- Functions allow code to be reused and separated into logical subsections, making code more modular, readable, and maintainable.
- Arguments passed to functions can make functions more flexible by allowing different inputs to produce different outputs each time they are called.
- Functions can return values to the calling code using the return statement. Returned values can be variables, arrays, or results of calculations.
- The order arguments are passed to a function matters, as arguments are assigned to placeholder variables in the defined order. Default values can be specified for arguments.
The document discusses techniques for writing clean JavaScript code. It provides examples of code smells and improvements to address issues like attaching events from the outside, separating selection from logic, shallow scope, overwriting default behavior, and separating logic from views. The document advocates for practices like modularizing functions, separating DOM manipulation from models, and creating model objects to represent DOM elements rather than directly manipulating the DOM. It encourages learning clean JavaScript techniques to write better structured and more maintainable code.
This document discusses dependency injection (DI) in AngularJS. It explains that DI allows high-level modules to depend on low-level abstractions rather than implementations. It then covers the different ways to define providers in AngularJS, including using the $provide service, as well as factories, services, values, and constants. It also discusses decorators as another way to modify existing services. The document provides recipes for when to use each provider type and concludes with some additional facts about injectors and ensuring scripts are in the proper order.
The document discusses how Symfony 1.2 supports RESTful routes out of the box. It provides examples of how to configure routes to support different HTTP methods like GET, POST, PUT, DELETE. It also describes how to create custom route classes to support additional route matching and generation behaviors, like domain routing based on subdomains. Overall, the document shows how Symfony 1.2 allows developers to easily create RESTful applications by mapping URLs to controller actions and resources in a RESTful way.
"Angular.js Concepts in Depth" by Aleksandar SimovićJS Belgrade
Angular.js concepts are organized into modules, controllers, scopes, views, directives, filters, and providers. Core concepts include dependency injection which allows components to request services from Angular's injector, and change detection which checks data for changes by running equality checks over dependent data. Modules contain related code and are made up of controllers, filters, directives, services and other components.
This document summarizes the Aura Project for PHP 5.4. The Aura Project provides independent library packages that can be used individually or together to build applications. It includes components like autoloading, routing, database abstraction, and more. Each component is built as a separate package that can be included as needed for applications.
AngularJS training provides an overview of key AngularJS concepts and best practices for building Angular applications. The document introduces the trainer, Lauri Svan, and discusses AngularJS fundamentals like two-way data binding, dependency injection, templates, controllers and directives. It also outlines the typical structure of an Angular app, including modules, services and routing. Form validation, custom directives and asynchronous validation with ngModelOptions are also covered to demonstrate common Angular patterns and techniques.
The document discusses best practices for building robust jQuery plugins, including testing plugins with QUnit, implementing plugins by extending jQuery's prototype, releasing plugins with documentation and examples, and maintaining plugins over time by tracking issues and communicating with users.
A quick run through explaining actions and filters that are used throughout WordPress (with useful metaphors) and some examples. It is intended to demonstrate that actions and filters are not as scary as people might think and that they can very easily make significant changes with only a few lines of code.
Php my sql - functions - arrays - tutorial - programmerblog.netProgrammer Blog
In this ppt you will learn about functions and array in php. What are functions, how to declare and use. built in functions. include and required keywords. how are arguments used. how to create functions inside functions.
What are php arrays, how to create an array and use them. Built in array functions. What are super globals?
WordPress allows plugins and themes to modify its core functionality through hooks called actions and filters. Actions allow plugins to specify functions that are executed at certain points, like before or after specific events. Filters allow functions to modify content, like text, before it is saved or output. The document discusses how a basic widget can be modified to use actions and filters to allow other code to add puppy images and warnings. This allows expanding the widget's capabilities without directly editing its code.
The document discusses the components and utilities of the Backbone.js framework. It describes the key components of Backbone - Models, Collections, Views - and how they work together. Models contain interactive data and bind attributes to the DOM. Collections provide methods to manage ordered sets of models. Views handle templating and user interactions. The document also covers utilities like routing and events that help connect components.
This document provides instructions for creating a simple blog using Django. It includes steps to:
1) Set up the Django project and install necessary apps like the admin interface.
2) Create a blog application with a Post model to store blog posts and configure the admin interface to manage posts.
3) Add templates to display list and detail views of posts and enable pagination for post lists.
4) Create a form to allow adding and editing blog posts from the admin and templates.
5) Provide instructions for deleting posts and include a link to download the full code files.
The document discusses best practices and anti-patterns for Django projects. It recommends keeping projects simple by avoiding over-engineering, using application-based modular design, and properly structuring settings files across multiple environments rather than relying on local_settings.py files. It also addresses common issues like import errors caused by PYTHONPATH configuration.
Filters in AngularJS allow formatting of data for display to users. There are built-in filters like currency and date that format numbers and dates, and filters can be used in templates, controllers, or services. Custom filters can also be created and defined as Angular modules to transform input data in a specified way.
Zepto.js, a jQuery-compatible mobile JavaScript framework in 2KThomas Fuchs
The document discusses the goals and design of Zepto.js, a JavaScript framework for mobile web applications. It aims to have a very small codebase that is easy to use, extends native browser APIs, and avoids non-essential browser implementations. It provides a jQuery-like API but takes advantage of mobile features for better performance on small screens and devices with limited bandwidth.
Django is a high-level Python web framework that allows developers to build web applications quickly by automating common tasks and following best practices. It provides features like an object-relational mapper, form validation, security, internationalization, and more out of the box. The document then outlines how to install, configure, and build basic applications with Django.
MyApp provides JavaScript best practices including:
1) Using namespaces to avoid naming collisions and define packages like MyApp.string.utils for reusable functions.
2) Branching code during initialization or lazily on first use to handle browser differences efficiently.
3) Passing configuration as an object instead of many parameters to simplify function calls.
4) Defining private methods and properties using closures to encapsulate code.
5) Employing self-executing functions for one-time initialization tasks.
6) Allowing method chaining for readability when calling several related methods.
Go beyond the documentation and explore some of what's possible if you stretch symfony to its limits. We will look at a number of aspects of symfony 1.4 and Doctrine 1.2 and tease out some powerful functionality you may not have expected to find, but will doubtless be able to use. Topics covered will include routing, forms, the config cache and record listeners. If you're comfortable in symfony and wondering what's next, this session is for you.
Similar to Chapter 8- Advanced Views and URLconfs (20)
UI5con 2024 - Boost Your Development Experience with UI5 Tooling ExtensionsPeter Muessig
The UI5 tooling is the development and build tooling of UI5. It is built in a modular and extensible way so that it can be easily extended by your needs. This session will showcase various tooling extensions which can boost your development experience by far so that you can really work offline, transpile your code in your project to use even newer versions of EcmaScript (than 2022 which is supported right now by the UI5 tooling), consume any npm package of your choice in your project, using different kind of proxies, and even stitching UI5 projects during development together to mimic your target environment.
E-commerce Application Development Company.pdfHornet Dynamics
Your business can reach new heights with our assistance as we design solutions that are specifically appropriate for your goals and vision. Our eCommerce application solutions can digitally coordinate all retail operations processes to meet the demands of the marketplace while maintaining business continuity.
Mobile App Development Company In Noida | Drona InfotechDrona Infotech
Looking for a reliable mobile app development company in Noida? Look no further than Drona Infotech. We specialize in creating customized apps for your business needs.
Visit Us For : https://www.dronainfotech.com/mobile-application-development/
May Marketo Masterclass, London MUG May 22 2024.pdfAdele Miller
Can't make Adobe Summit in Vegas? No sweat because the EMEA Marketo Engage Champions are coming to London to share their Summit sessions, insights and more!
This is a MUG with a twist you don't want to miss.
Graspan: A Big Data System for Big Code AnalysisAftab Hussain
We built a disk-based parallel graph system, Graspan, that uses a novel edge-pair centric computation model to compute dynamic transitive closures on very large program graphs.
We implement context-sensitive pointer/alias and dataflow analyses on Graspan. An evaluation of these analyses on large codebases such as Linux shows that their Graspan implementations scale to millions of lines of code and are much simpler than their original implementations.
These analyses were used to augment the existing checkers; these augmented checkers found 132 new NULL pointer bugs and 1308 unnecessary NULL tests in Linux 4.4.0-rc5, PostgreSQL 8.3.9, and Apache httpd 2.2.18.
- Accepted in ASPLOS ‘17, Xi’an, China.
- Featured in the tutorial, Systemized Program Analyses: A Big Data Perspective on Static Analysis Scalability, ASPLOS ‘17.
- Invited for presentation at SoCal PLS ‘16.
- Invited for poster presentation at PLDI SRC ‘16.
OpenMetadata Community Meeting - 5th June 2024OpenMetadata
The OpenMetadata Community Meeting was held on June 5th, 2024. In this meeting, we discussed about the data quality capabilities that are integrated with the Incident Manager, providing a complete solution to handle your data observability needs. Watch the end-to-end demo of the data quality features.
* How to run your own data quality framework
* What is the performance impact of running data quality frameworks
* How to run the test cases in your own ETL pipelines
* How the Incident Manager is integrated
* Get notified with alerts when test cases fail
Watch the meeting recording here - https://www.youtube.com/watch?v=UbNOje0kf6E
Microservice Teams - How the cloud changes the way we workSven Peters
A lot of technical challenges and complexity come with building a cloud-native and distributed architecture. The way we develop backend software has fundamentally changed in the last ten years. Managing a microservices architecture demands a lot of us to ensure observability and operational resiliency. But did you also change the way you run your development teams?
Sven will talk about Atlassian’s journey from a monolith to a multi-tenanted architecture and how it affected the way the engineering teams work. You will learn how we shifted to service ownership, moved to more autonomous teams (and its challenges), and established platform and enablement teams.
A Study of Variable-Role-based Feature Enrichment in Neural Models of CodeAftab Hussain
Understanding variable roles in code has been found to be helpful by students
in learning programming -- could variable roles help deep neural models in
performing coding tasks? We do an exploratory study.
- These are slides of the talk given at InteNSE'23: The 1st International Workshop on Interpretability and Robustness in Neural Software Engineering, co-located with the 45th International Conference on Software Engineering, ICSE 2023, Melbourne Australia
Enterprise Resource Planning System includes various modules that reduce any business's workload. Additionally, it organizes the workflows, which drives towards enhancing productivity. Here are a detailed explanation of the ERP modules. Going through the points will help you understand how the software is changing the work dynamics.
To know more details here: https://blogs.nyggs.com/nyggs/enterprise-resource-planning-erp-system-modules/
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI AppGoogle
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
👉👉 Click Here To Get More Info 👇👇
https://sumonreview.com/ai-fusion-buddy-review
AI Fusion Buddy Review: Key Features
✅Create Stunning AI App Suite Fully Powered By Google's Latest AI technology, Gemini
✅Use Gemini to Build high-converting Converting Sales Video Scripts, ad copies, Trending Articles, blogs, etc.100% unique!
✅Create Ultra-HD graphics with a single keyword or phrase that commands 10x eyeballs!
✅Fully automated AI articles bulk generation!
✅Auto-post or schedule stunning AI content across all your accounts at once—WordPress, Facebook, LinkedIn, Blogger, and more.
✅With one keyword or URL, generate complete websites, landing pages, and more…
✅Automatically create & sell AI content, graphics, websites, landing pages, & all that gets you paid non-stop 24*7.
✅Pre-built High-Converting 100+ website Templates and 2000+ graphic templates logos, banners, and thumbnail images in Trending Niches.
✅Say goodbye to wasting time logging into multiple Chat GPT & AI Apps once & for all!
✅Save over $5000 per year and kick out dependency on third parties completely!
✅Brand New App: Not available anywhere else!
✅ Beginner-friendly!
✅ZERO upfront cost or any extra expenses
✅Risk-Free: 30-Day Money-Back Guarantee!
✅Commercial License included!
See My Other Reviews Article:
(1) AI Genie Review: https://sumonreview.com/ai-genie-review
(2) SocioWave Review: https://sumonreview.com/sociowave-review
(3) AI Partner & Profit Review: https://sumonreview.com/ai-partner-profit-review
(4) AI Ebook Suite Review: https://sumonreview.com/ai-ebook-suite-review
#AIFusionBuddyReview,
#AIFusionBuddyFeatures,
#AIFusionBuddyPricing,
#AIFusionBuddyProsandCons,
#AIFusionBuddyTutorial,
#AIFusionBuddyUserExperience
#AIFusionBuddyforBeginners,
#AIFusionBuddyBenefits,
#AIFusionBuddyComparison,
#AIFusionBuddyInstallation,
#AIFusionBuddyRefundPolicy,
#AIFusionBuddyDemo,
#AIFusionBuddyMaintenanceFees,
#AIFusionBuddyNewbieFriendly,
#WhatIsAIFusionBuddy?,
#HowDoesAIFusionBuddyWorks
Do you want Software for your Business? Visit Deuglo
Deuglo has top Software Developers in India. They are experts in software development and help design and create custom Software solutions.
Deuglo follows seven steps methods for delivering their services to their customers. They called it the Software development life cycle process (SDLC).
Requirement — Collecting the Requirements is the first Phase in the SSLC process.
Feasibility Study — after completing the requirement process they move to the design phase.
Design — in this phase, they start designing the software.
Coding — when designing is completed, the developers start coding for the software.
Testing — in this phase when the coding of the software is done the testing team will start testing.
Installation — after completion of testing, the application opens to the live server and launches!
Maintenance — after completing the software development, customers start using the software.
WhatsApp offers simple, reliable, and private messaging and calling services for free worldwide. With end-to-end encryption, your personal messages and calls are secure, ensuring only you and the recipient can access them. Enjoy voice and video calls to stay connected with loved ones or colleagues. Express yourself using stickers, GIFs, or by sharing moments on Status. WhatsApp Business enables global customer outreach, facilitating sales growth and relationship building through showcasing products and services. Stay connected effortlessly with group chats for planning outings with friends or staying updated on family conversations.
SOCRadar's Aviation Industry Q1 Incident Report is out now!
The aviation industry has always been a prime target for cybercriminals due to its critical infrastructure and high stakes. In the first quarter of 2024, the sector faced an alarming surge in cybersecurity threats, revealing its vulnerabilities and the relentless sophistication of cyber attackers.
SOCRadar’s Aviation Industry, Quarterly Incident Report, provides an in-depth analysis of these threats, detected and examined through our extensive monitoring of hacker forums, Telegram channels, and dark web platforms.
Why Mobile App Regression Testing is Critical for Sustained Success_ A Detail...kalichargn70th171
A dynamic process unfolds in the intricate realm of software development, dedicated to crafting and sustaining products that effortlessly address user needs. Amidst vital stages like market analysis and requirement assessments, the heart of software development lies in the meticulous creation and upkeep of source code. Code alterations are inherent, challenging code quality, particularly under stringent deadlines.
Odoo ERP software
Odoo ERP software, a leading open-source software for Enterprise Resource Planning (ERP) and business management, has recently launched its latest version, Odoo 17 Community Edition. This update introduces a range of new features and enhancements designed to streamline business operations and support growth.
The Odoo Community serves as a cost-free edition within the Odoo suite of ERP systems. Tailored to accommodate the standard needs of business operations, it provides a robust platform suitable for organisations of different sizes and business sectors. Within the Odoo Community Edition, users can access a variety of essential features and services essential for managing day-to-day tasks efficiently.
This blog presents a detailed overview of the features available within the Odoo 17 Community edition, and the differences between Odoo 17 community and enterprise editions, aiming to equip you with the necessary information to make an informed decision about its suitability for your business.
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
Chapter 8- Advanced Views and URLconfs
1. The
Django
Book
Chapter
8:
Advanced
Views
and
URLconfs
Speaker:
Vincent
Chien
2. advantage of this in several ways, as described in the sections that follow.
from django.conf.urls.defaults import *
from mysite.views import hello, current_datetime, hours_ahead
Streamlining
Function
Imports
9.1.1 Streamlining Function Imports
Consider this URLconf, which builds on the example in Chapter 3:
from django.conf.urls.defaults import *
from mysite.views import hello, current_datetime, hours_ahead
urlpatterns = patterns(’’,
(r’^hello/$’, hello),
(r’^time/$’, current_datetime),
(r’^time/plus/(d{1,2})/$’, hours_ahead),
)
As urlpatterns explained in = Chapter patterns(’’,
3, each entry in the URLconf includes its associated view function, function (r’^object. hello/$’, This means hello),
it’s necessary to import the view functions at the top of the module.
But as (a r’^Django time/$’, application current_datetime),
(r’^time/plus/(d{grows 1,2})/$’, in complexity, hours_its ahead),
URLconf grows, too, and keeping those imports manage. (For each new view function, you have to remember to import it, and the import statement long if you use this approach.) It’s possible to avoid that tedium by importing the views module URLconf is equivalent to the previous one:
from django.conf.urls.defaults import *
from mysite import views
)
As explained in Chapter 3, each entry in the URLconf includes its associated view function, function object. This means it’s necessary to import the view functions at the top of the module.
But as a Django application grows in complexity, its URLconf grows, too, and keeping those imports manage. (For each new view function, you have to remember to import it, and the import statement long if you use this approach.) It’s possible to avoid that tedium by importing the views module URLconf is equivalent to the previous one:
from django.conf.urls.defaults import *
from mysite import views
urlpatterns = patterns(‘’,
(r’^hello/$’, views.hello),
(r’^time/$’, views.current_datetime),
(r’^time/plus/(d{1,2})/$’, views.hours_ahead),
)
urlpatterns = patterns(‘’,
3. string containing the module name and function name rather than the function object itself. Continuing example:
from django.conf.urls.defaults import *
DSjantgro Beooak Dmocumlienntatiionn, Rgel
eaFseu0.1nction
Imports
urlpatterns = patterns(‘’,
(r’^hello/$’, ‘mysite.views.hello’),
(r’^time/$’, ‘mysite.views.current_datetime’),
(r’^time/plus/(d{1,2})/$’, ‘mysite.views.hours_ahead’),
Django
offers
another
way
of
specifying
the
view
funcAon
for
a
parAcular
)
Note that you don’t put a trailing dot (".") in the prefix, nor do you put a leading dot in the view strings. Django paCern
offers in
the
another URLconf:
way of you
specifying can
pass
the a
view string
function containing
for a particular the
module
pattern name
in the URLconf: you can string and
funccontaining Aon
name
the module rather
name than
and the
function funcAon
name object
rather itself.
than the function object itself. Continuing the ongoing
example:
from django.conf.urls.defaults import *
)
(Note the quotes around the view names. We’re using ’mysite.views.current_datetime’ instead of mysite.views.current_datetime.)
Using urlpatterns this technique, = patterns(‘’,
it’s no longer necessary to import the view functions; Django automatically (r’^hello/$’, ‘mysite.views.hello’),
(r’^view time/$’, function ‘the mysite.first time views.it’s needed, current_according datetime’),
to the string describing the name and path function.
(r’^time/plus/(d{1,2})/$’, ‘mysite.views.hours_ahead’),
A further shortcut you can take when using the string technique is to factor out a common “view URLconf example, each of the view strings starts with ’mysite.views’, which is redundant to factor out that common prefix and pass it as the first argument to patterns(), like this:
from django.conf.urls.defaults import *
)
(Note the quotes around the view names. We’re using ’mysite.views.current_datetime’ – with quotes instead factor
of out
mysite.a
common
views.“view
current_prefix.”
datetime.)
Using this technique, it’s no longer necessary to import the view functions; Django automatically imports view function the first time it’s needed, according to the string describing the name and path of the function.
A further shortcut you can take when using the string technique is to factor out a common “view prefix.” URLconf example, each of the view strings starts with ’mysite.views’, which is redundant to type. We factor out that common prefix and pass it as the first argument to patterns(), like this:
from django.conf.urls.defaults import *
urlpatterns = patterns(‘mysite.views’,
(r’^hello/$’, ‘hello’),
(r’^time/$’, ‘current_datetime’),
(r’^time/plus/(d{1,2})/$’, ‘hours_ahead’),
5. 9.1.3 Special-Casing URLs in Debug Mode
Special-‐Casing
URLs
in
Debug
Speaking of constructing urlpatterns dynamically, you might want to take advantage your runtime, Mode
URLconf’s behavior while in Django’s debug mode. To do this, just check the like so:
from django.conf import settings
from django.conf.urls.defaults import *
from mysite import views
urlpatterns = patterns(’’,
(r’^$’, views.homepage),
(r’^(d{4})/([a-z]{3})/$’, views.archive_month),
)
if settings.DEBUG:
urlpatterns += patterns(’’,
(r’^debuginfo/$’, views.debug),
)
In this example, the URL /debuginfo/ will only be available if your DEBUG setting 9.1.4 Using Named Groups
6. Keyword Arguments vs. Positional Arguments
A Python function can be called using keyword arguments or positional arguments – and, in some cases, both at same time. In a keyword argument call, you specify the names of the arguments along with the values you’re passing.
In a positional argument call, you simply pass the arguments without explicitly specifying which argument matches
which value; the association is implicit in the arguments’ order.
For example, consider this simple function:
def sell(item, price, quantity):
A Python function can be called using keyword arguments or positional arguments – and, in some cases, same time. In a keyword argument call, you specify the names of the arguments along with the values In a positional argument call, you simply pass the arguments without explicitly specifying which argument which value; the association is implicit in the arguments’ order.
For example, consider this simple function:
def sell(item, price, quantity):
same In a positional time. In a argument keyword argument call, you simply call, you pass specify the arguments the names without of the arguments explicitly specifying along with which the values argument In which a positional value; the argument association call, is you implicit simply in the pass arguments’ the arguments order.
without explicitly specifying which argument which For example, value; the consider association this simple is implicit function:
in the arguments’ order.
For example, consider this simple function:
def sell(item, price, quantity):
def sell(item, price, quantity):
Using
Named
Groups
print "Selling %s unit(s) of %s at %s" % (quantity, item, price)
print "Selling %s unit(s) of %s at %s" % (quantity, item, price)
To call it with positional arguments, you specify the arguments in the order in which they’re listed definition:
sell(’Socks’, ’$2.50’, 6)
To call it with keyword arguments, you specify the names of the arguments along with the values. statements are equivalent:
sell(item=’Socks’, price=’$2.50’, quantity=6)
sell(item=’Socks’, quantity=6, price=’$2.50’)
sell(price=’$2.50’, item=’Socks’, quantity=6)
sell(price=’$2.50’, quantity=6, item=’Socks’)
sell(quantity=6, item=’Socks’, price=’$2.50’)
sell(quantity=6, price=’$2.50’, item=’Socks’)
Finally, you can mix keyword and positional arguments, as long as all positional arguments are listed arguments. The following statements are equivalent to the previous examples:
sell(’Socks’, ’$2.50’, quantity=6)
sell(’Socks’, price=’$2.50’, quantity=6)
sell(’Socks’, quantity=6, price=’$2.50’)
print print "Selling "Selling %s %unit(s unit(s) of s) %s of at %s %s" at % %(s" quantity, % (quantity, item, price)
item, price)
call it with positional arguments, you specify the arguments in the order in which they’re listed definition:
sell(’Socks’, ’$2.50’, 6)
To call it with keyword arguments, you specify the names of the arguments along with the values. statements are equivalent:
To call it with positional arguments, you specify the arguments in the order in which they’re listed definition:
sell(’Socks’, ’$2.50’, 6)
To call it with keyword arguments, you specify the names of the arguments along with the values. statements are equivalent:
sell(item=’Socks’, price=’$2.50’, quantity=6)
sell(item=’Socks’, quantity=6, price=’$2.50’)
sell(price=’$2.50’, item=’Socks’, quantity=6)
sell(price=’$2.50’, quantity=6, item=’Socks’)
sell(quantity=6, item=’Socks’, price=’$2.50’)
sell(quantity=6, price=’$2.50’, item=’Socks’)
Finally, you can mix keyword and positional arguments, as long as all positional arguments are listed arguments. The following statements are equivalent to the previous examples:
sell(’Socks’, ’$2.50’, quantity=6)
sell(’Socks’, price=’$2.50’, quantity=6)
sell(’Socks’, quantity=6, price=’$2.50’)
To call it with positional arguments, you specify the arguments in the order in which they’re listed in the function
definition:
sell(’Socks’, ’$2.50’, 6)
To call it with keyword arguments, you specify the names of the arguments along with the values. The following
PosiAonal
Arguments
Keyword
Arguements
are equivalent:
sell(item=’Socks’, price=’$2.50’, quantity=6)
sell(item=’item=’Socks’, Socks’, quantity=price=’$6, 2.50’, price=’$quantity=2.50’)
6)
sell(price=’$2.50’, item=’Socks’, quantity=6)
sell(price=’$2.50’, quantity=6, item=’Socks’)
sell(quantity=6, item=’Socks’, price=’$2.50’)
sell(quantity=6, price=’$2.50’, item=’Socks’)
Finally, you can mix keyword and positional arguments, as long as all positional arguments are listed before keyword
arguments. The following statements are equivalent to the previous examples:
sell(’Socks’, ’$2.50’, quantity=6)
sell(’Socks’, price=’$2.50’, quantity=6)
sell(’Socks’, quantity=6, price=’$2.50’)
sell(item=’Socks’, quantity=6, price=’$2.50’)
sell(price=’$2.50’, item=’Socks’, quantity=6)
sell(price=’$2.50’, quantity=6, item=’Socks’)
sell(quantity=6, item=’Socks’, price=’$2.50’)
sell(quantity=6, price=’$2.50’, item=’Socks’)
Finally, you can mix keyword and positional arguments, as long as all positional arguments are listed arguments. The following statements are equivalent to the previous examples:
sell(’Socks’, ’$2.50’, quantity=6)
sell(’Socks’, price=’$2.50’, quantity=6)
sell(’Socks’, quantity=6, price=’$2.50’)
Mix
In Python regular expressions, the syntax for named regular expression groups is (?P<name>pattern), where
In Python regular expressions, the syntax for named regular expression groups is (?P<name>pattern),
7. sell(’Socks’, ’$2.50’, quantity=6)
Socks’, quantity=6, price=’$2.50’)
sell(’Socks’, price=’$2.50’, quantity=6)
sell(’Socks’, quantity=6, price=’$2.50’)
Using
Named
Groups
In Python regular expressions, the syntax for named regular expression groups is (?P<name>name is the name of the group and pattern is some pattern to match.
In Python regular expressions, the syntax for named regular expression groups is (?P<name>pattern), name is the name of the group and pattern is some pattern to match.
Here’s an example URLconf that uses non-named groups:
from django.conf.urls.defaults import *
from mysite import views
Here’s an example URLconf that uses non-named groups:
from django.conf.urls.defaults import *
from mysite import views
urlpatterns = patterns(’’,
urlpatterns = patterns(’’,
(r’^articles/(d{4})/$’, views.year_archive),
(r’^articles/(d{4})/(d{2})/$’, views.month_archive),
(r’^articles/(d{4})/$’, views.year_archive),
(r’^articles/(d{4})/(d{2})/$’, views.month_archive),
)
Here’s the same URLconf, rewritten to use named groups:
from django.conf.urls.defaults import *
from mysite import views
)
Here’s the same URLconf, rewritten to use named groups:
from django.conf.urls.defaults import *
from mysite import views
urlpatterns = patterns(’’,
urlpatterns = patterns(’’,
(r’^articles/(?P<year>d{4})/$’, views.year_archive),
(r’^articles/(?P<year>d{4})/(?P<month>d{2})/$’, views.month_archive),
(r’^articles/(?P<year>d{4})/$’, views.year_archive),
(r’^articles/(?P<year>d{4})/(?P<month>d{2})/$’, views.month_archive),
)
This accomplishes exactly the same thing as the previous example, with one subtle difference: the captured passed to view functions as keyword arguments rather than positional arguments.
)
This accomplishes exactly the same thing as the previous example, with one subtle difference: passed to view functions as keyword arguments rather than positional arguments.
8. Using
Named
Groups
• For
example,
with
non-‐named
groups,
a
request
to
/arAcles/
2006/03/
would
result
in
a
funcAon
call
equivalent
to
this:
month_archive(request,
'2006',
'03')
• With
named
groups,
though,
the
same
request
would
result
in
this
funcAon
call:
month_archive(request,
year='2006',
month='03')
9. Understanding
the
Matching/
Grouping
Algorithm
• If
there
are
any
named
arguments,
it
will
use
those,
ignoring
non-‐named
arguments.
• Otherwise,
it
will
pass
all
non-‐named
arguments
as
posiAonal
arguments.
• In
both
cases,
it
will
pass
any
extra
opAons
as
keyword
arguments.
See
the
next
secAon
for
more
informaAon.
10. • Otherwise, it will pass all non-named arguments as positional arguments.
• In both cases, it will pass any extra options as keyword arguments. See the next section for more information.
Passing
Extra
Options
to
View
Functions
9.1.6 Passing Extra Options to View Functions
Sometimes you’ll find yourself writing view functions that are quite similar, with only a few small differences. example, say you have two views whose contents are identical except for the template they use:
# urls.py
from django.conf.urls.defaults import *
from mysite import views
urlpatterns = patterns(’’,
(r’^foo/$’, views.foo_view),
(r’^bar/$’, views.bar_view),
)
# views.py
from django.shortcuts import render
from mysite.models import MyModel
9.1. URLconf Tricks Django Book Documentation, Release 0.1
def foo_view(request):
m_list = MyModel.objects.filter(is_new=True)
return render(request, ’template1.html’, {’m_list’: m_list})
def bar_view(request):
m_list = MyModel.objects.filter(is_new=True)
return render(request, ’template2.html’, {’m_list’: m_list})
We’re repeating ourselves in this code, and that’s inelegant. At first, you may think to remove the redundancy by the same view for both URLs, putting parentheses around the URL to capture it, and checking the URL within
11. def bar_view(request):
m_list = MyModel.objects.filter(is_new=True)
return render(request, ’template2.html’, {’m_list’: m_list})
Passing
Extra
Options
to
View
Functions
We’re repeating ourselves in this code, and that’s inelegant. At first, you may think to remove the redundancy by using
the same view for both URLs, putting parentheses around the URL to capture it, and checking the URL within the
view to determine the template, like so:
# urls.py
from django.conf.urls.defaults import *
from mysite import views
urlpatterns = patterns(’’,
(r’^(foo)/$’, views.foobar_view),
(r’^(bar)/$’, views.foobar_view),
)
# views.py
from django.shortcuts import render
from mysite.models import MyModel
def foobar_view(request, url):
m_list = MyModel.objects.filter(is_new=True)
if url == ’foo’:
template_name = ’template1.html’
elif url == ’bar’:
template_name = ’template2.html’
return render(request, template_name, {’m_list’: m_list})
The problem with that solution, though, is that it couples your URLs to your code. If you decide to rename /foo/ to
/fooey/, you’ll have to remember to change the view code.
The elegant solution involves an optional URLconf parameter. Each pattern in a URLconf may include a third item: a
dictionary of keyword arguments to pass to the view function.
With this in mind, we can rewrite our ongoing example like this:
The
problem
with
that
soluAon,
though,
is
that
it
couples
your
URLs
to
your
code.
If
you
decide
to
rename
/foo/
to
/fooey/,
you’ll
have
to
remember
to
change
the
view
code.
12. The /Passing
problem with that solution, though, is that it couples your URLs to your code. If you decide to rename /fooey/, you’ll have to Extra
remember to change Options
the view code.
to
View
The elegant solution involves an optional URLconf parameter. Each pattern in a URLconf may include a third dictionary Functions
of keyword arguments to pass to the view function.
With this in mind, we can rewrite our ongoing example like this:
# urls.py
from django.conf.urls.defaults import *
from mysite import views
urlpatterns = patterns(’’,
(r’^foo/$’, views.foobar_view, {’template_name’: ’template1.html’}),
(r’^bar/$’, views.foobar_view, {’template_name’: ’template2.html’}),
)
# views.py
from django.shortcuts import render
from mysite.models import MyModel
def foobar_view(request, template_name):
m_list = MyModel.objects.filter(is_new=True)
return render(request, template_name, {’m_list’: m_list})
As you can see, the URLconf in this example specifies template_name in the URLconf. The view function 128 Chapter 9. Chapter 8: Advanced Views and URLconfs
13. )
And the view function signature would look like this:
def my_view(request, month, day):
Faking
Captured
URLconf
Values
# ....
This approach is straightforward – it’s nothing you haven’t seen before. The trick comes in when you want another URL that uses my_view but whose URL doesn’t include a month and/or day.
For example, you might want to add another URL, /mydata/birthday/, which would be equivalent /mydata/jan/06/. You can take advantage of extra URLconf options like so:
urlpatterns = patterns(’’,
(r’^mydata/birthday/$’, views.my_view, {’month’: ’jan’, ’day’: ’06’}),
(r’^mydata/(?P<month>w{3})/(?P<day>dd)/$’, views.my_view),
)
The cool thing here is that you don’t have to change your view function at all. The view function only cares that month and day parameters – it doesn’t matter whether they come from the URL capturing itself or extra parameters.
Making a View Generic
It’s good programming practice to “factor out” commonalities in code. For example, with these two Python functions:
def say_hello(person_name):
print ’Hello, %s’ % person_name
def say_goodbye(person_name):
print ’Goodbye, %s’ % person_name
14. def greet(person_name, greeting):
print ’%s, %s’ % (greeting, person_name)
Making
a
View
Generic
You can apply this same philosophy to your Django views by using extra URLconf parameters.
With this in mind, you can start making higher-level abstractions of your views. Instead of thinking to yourself, “This
view displays a list of Event objects,” and “That view displays a list of BlogEntry objects,” realize they’re both
specific cases of “A view that displays a list of objects, where the type of object is variable.”
Take Original
this code, for example:
# urls.py
from django.conf.urls.defaults import *
from mysite import views
urlpatterns = patterns(’’,
(r’^events/$’, views.event_list),
(r’^blog/entries/$’, views.entry_list),
)
# views.py
from django.shortcuts import render
from mysite.models import Event, BlogEntry
def event_list(request):
obj_list = Event.objects.all()
return render(request, ’mysite/event_list.html’, {’event_list’: obj_list})
def entry_list(request):
obj_list = BlogEntry.objects.all()
return render(request, ’mysite/blogentry_list.html’, {’entry_list’: obj_list})
The two views do essentially the same thing: they display a list of objects. So let’s factor out the type of object they’re
displaying:
15. obj_list = Event.objects.all()
return render(request, ’mysite/event_list.html’, {’event_list’: obj_list})
def entry_list(request):
Making
a
View
Generic
obj_list = BlogEntry.objects.all()
return render(request, ’mysite/blogentry_list.html’, {’entry_list’: obj_list})
The two views do essentially the same thing: they display a list of objects. So let’s factor out the type of object displaying:
# urls.py
BeCer
from django.conf.urls.defaults import *
from mysite import models, views
urlpatterns = patterns(’’,
(r’^events/$’, views.object_list, {’model’: models.Event}),
(r’^blog/entries/$’, views.object_list, {’model’: models.BlogEntry}),
)
# views.py
from django.shortcuts import render
def object_list(request, model):
obj_list = model.objects.all()
template_name = ’mysite/%s_list.html’ % model.__name__.lower()
return render(request, template_name, {’object_list’: obj_list})
With those small changes, we suddenly have a reusable, model-agnostic view! From now on, anytime we need that Every
lists Python
a set of class
objects, has
we a
can __name__
simply reuse aCribute
this object_that
returns
list the
view class
rather name.
than writing view code. Here
16. var = do_something()
return render(request, template_name, {’var’: var})
Understanding
Precedence
of
Captured
Values
vs.
Extra
Options
Understanding Precedence of Captured Values vs. Extra Options
When there’s a conflict, extra URLconf parameters get precedence over captured parameters. URLconf if
your
URLconf
captures captures
a named-a
named-‐group group
variable variable
and an and
extra an
extra
URLconf URLconf
parameter includes a variable the parameter
extra URLconf includes
parameter a
variable
value with
the
will same
be used.
name,
the
extra
URLconf
parameter
value
will
be
used.
For example, consider this URLconf:
from django.conf.urls.defaults import *
from mysite import views
urlpatterns = patterns(’’,
(r’^mydata/(?P<id>d+)/$’, views.my_view, {’id’: 3}),
)
Here, both the regular expression and the extra dictionary include an id. The hard-coded means any request (e.g., /mydata/2/ or /mydata/432432/) will be treated as if id value id
captured will
be
3.
in the URL.
Astute readers will note that in this case, it’s a waste of time and typing to capture the id because its value will always be overridden by the dictionary’s value. That’s correct; we bring avoid making the mistake.
17. 9.1.7 Using Default View Arguments
Another convenient trick is to specify default parameters use Using
for a parameter Default
by default if none is View
specified.
Arguments
for a view’s arguments. This tells the view An example:
# urls.py
from django.conf.urls.defaults import *
from mysite import views
urlpatterns = patterns(’’,
(r’^blog/$’, views.page),
(r’^blog/page(?P<num>d+)/$’, views.page),
)
# views.py
def page(request, num=’1’):
# Output the appropriate page of blog entries, according to num.
# ...
Here, both URL patterns point to the same view – views.page – but the first pattern doesn’t capture the URL. If the first pattern matches, the page() function will use its default argument for num, ’1’. pattern matches, page() will use whatever num value was captured by the regular expression.
(Note that we’ve been careful to set the default argument’s value to the string ’1’, not the integer consistency, because any captured value for num will always be a string.)
It’s common to use this technique in conjunction with configuration options, as explained earlier. This example
18. Special-‐Casing
Views
Django Book else:
SomeAmes
you’ll
have
a
paCern
in
your
URLconf
that
handles
a
large
set
of
URLs,
but
you’ll
need
to
special-‐case
one
of
them.
In
this
case,
take
advantage
of
the
linear
way
a
# URLconf
do normal is
processed
code
and
put
the
special
case
first.
but that’s inelegant for a reason we’ve touched on multiple times in this chapter: it more elegant solution, we can take advantage of the fact that URLconfs are processed urlpatterns = patterns(’’,
# ...
(’^auth/user/add/$’, views.user_add_stage),
(’^([^/]+)/([^/]+)/add/$’, views.add_stage),
# ...
)
With this in place, a request to /auth/user/add/ will be handled by the user_add_URL matches the second pattern, it matches the top one first. (This is short-circuit logic.)
9.1.9 Capturing Text in URLs
19. so) about accepting only objects of a certain type. A common error is to attempt to create a datetime.date
object with string values instead of integer values:
>>> import datetime
>>> datetime.date(’1993’, ’7’, ’9’)
Traceback (most recent call last):
Capturing
Text
in
URLs
...
Each
captured
argument
is
sent
to
the
view
as
a
plain
Python
Unicode
string,
regardless
of
what
sort
of
match
the
regular
expression
makes.
TypeError: an integer is required
>>> datetime.date(1993, 7, 9)
datetime.date(1993, 7, 9)
Translated Wrong
to a URLconf and view, the error looks like this:
# urls.py
from django.conf.urls.defaults import *
from mysite import views
urlpatterns = patterns(’’,
(r’^articles/(d{4})/(d{2})/(d{2})/$’, views.day_archive),
)
# views.py
import datetime
def day_archive(request, year, month, day):
# The following statement raises a TypeError!
date = datetime.date(year, month, day)
Django Book Documentation, Release 0.1
Instead, Correct
day_archive() can be written correctly like this:
def day_archive(request, year, month, day):
date = datetime.date(int(year), int(month), int(day))
9.1. URLconf Tricks 133
Note that int() itself raises a ValueError when you pass it a string that is not composed solely of digits, but
20. 9.1.11 Higher-Level Abstractions of View Functions
And speaking of branching based on request method, let’s take a look at how we might build a nice way of doing Consider this URLconf/view layout:
# urls.py
Higher-‐level
Abstractions
of
View
Functions(Original)
from django.conf.urls.defaults import *
from mysite import views
urlpatterns = patterns(’’,
# ...
(r’^somepage/$’, views.some_page),
# ...
)
# views.py
from django.http import Http404, HttpResponseRedirect
from django.shortcuts import render
def some_page(request):
if request.method == ’POST’:
do_something_for_post()
return HttpResponseRedirect(’/someurl/’)
elif request.method == ’GET’:
do_something_for_get()
return render(request, ’page.html’)
else:
raise Http404()
In this example, the some_page() view’s handling of POST vs. GET requests is quite different. The only thing
21. Higher-‐level
Abstractions
of
View
Functions(no
args
and
kwargs)
Django Book Documentation, Release 0.1
We can do that by writing a view function that delegates to other views, either before or after executing some custom
logic. Here’s an example of how this technique could help simplify our some_page() view:
# views.py
from django.http import Http404, HttpResponseRedirect
from django.shortcuts import render
def method_splitter(request, GET=None, POST=None):
if request.method == ’GET’ and GET is not None:
return GET(request)
elif request.method == ’POST’ and POST is not None:
return POST(request)
raise Http404
def some_page_get(request):
assert request.method == ’GET’
do_something_for_get()
return render(request, ’page.html’)
def some_page_post(request):
assert request.method == ’POST’
do_something_for_post()
return HttpResponseRedirect(’/someurl/’)
# urls.py
from django.conf.urls.defaults import *
from mysite import views
urlpatterns = patterns(’’,
# ...
(r’^somepage/$’, views.method_splitter, {’GET’: views.some_page_get, ’POST’: views.some_page_post}),
# ...
22. Django Book Documentation, Release 0.1
Higher-‐level
Abstractions
of
View
Functions(args
and
kwargs)
GET and POST views take no arguments other than request. What if we wanted to use method_with views that, for example, capture text from URLs, or take optional keyword arguments themselves?
To do that, we can use a nice Python feature: variable arguments with asterisks. We’ll show the example explain it:
def method_splitter(request, *args, **kwargs):
get_view = kwargs.pop(’GET’, None)
post_view = kwargs.pop(’POST’, None)
if request.method == ’GET’ and get_view is not None:
return get_view(request, *args, **kwargs)
elif request.method == ’POST’ and post_view is not None:
return post_view(request, *args, **kwargs)
raise Http404
Here, we’ve refactored method_splitter() to remove the GET and POST keyword arguments, in and **kwargs (note the asterisks). This is a Python feature that allows a function to accept a dynamic, number of arguments whose names aren’t known until runtime. If you put a single asterisk in front of a function definition, any positional arguments to that function will be rolled up into a single tuple. asterisks in front of a parameter in a function definition, any keyword arguments to that function will a single dictionary.
For example, with this function:
def foo(*args, **kwargs):
23. Wrapping
View
Functions
(Original)
Django Book Documentation, def my_view2(request):
if not request.user.is_authenticated():
return HttpResponseRedirect(’/accounts/login/’)
# ...
return render(request, ’template2.html’)
def my_view3(request):
if not request.user.is_authenticated():
return HttpResponseRedirect(’/accounts/login/’)
# ...
return render(request, ’template3.html’)
Here, each view starts by checking that request.user is authenticated – that is, the logged into the site – and redirects to /accounts/login/ if not. (Note that request.user – Chapter 14 does – but, as you might imagine, request.user either logged-in or anonymous.)
It would be nice if we could remove that bit of repetitive code from each of these views and
24. request.user – Chapter 14 does – but, as you might imagine, request.user represents the current either logged-in or anonymous.)
It would be nice if we could remove that bit of repetitive code from each of these views and just mark them as requiring
authentication. We can do that by making a view wrapper. Take a moment to study this:
def requires_login(view):
logged into the site – and redirects to /accounts/login/ if not. (Note that we request.user – Chapter 14 does – but, as you might imagine, request.user represents either Wrapping
logged-in or anonymous.)
View
Functions
(elegant)
It would be nice if we could remove that bit of repetitive code from each of these views and just authentication. def new_view(We request, can do that *args, by making **kwargs):
a view wrapper. Take a moment to study this:
if not request.user.is_authenticated():
def requires_login(view):
return HttpResponseRedirect(’/accounts/login/’)
def return new_view(view(request, request, *args, *args, **kwargs)
**kwargs):
return new_view
if not request.user.is_authenticated():
return HttpResponseRedirect(’/accounts/login/’)
This function, return requires_login, takes a view function (view) and returns a new view function (The new function, view(request, args, kwargs)
new_new_view is defined *within requires_**login and handles the logic of checking
request.return user.new_is_authenticated() view
and delegating to the original view (view).
Now, we can remove the if not request.user.is_authenticated() checks from our views and wrap them with requires_login in our URLconf:
from django.conf.urls.defaults import *
from mysite.views import requires_login, my_view1, my_view2, my_view3
This function, requires_login, takes a view function (view) and returns a new view The new function, new_view is defined within requires_login and handles request.user.is_authenticated() and delegating to the original view (view).
Now, we can remove the if not request.user.is_authenticated() checks from wrap them with requires_login in our URLconf:
from django.conf.urls.defaults import *
from mysite.views import requires_login, my_view1, my_view2, my_view3
urlpatterns = patterns(’’,
(r’^view1/$’, requires_login(my_view1)),
(r’^view2/$’, requires_login(my_view2)),
(r’^view3/$’, requires_login(my_view3)),
)
This urlpatterns has the same effect = patterns(’’,
as before, but with less code redundancy. Now we’ve created a nice, generic function requires_login() that we can wrap around any view in order to make it require login.
(r’^view1/$’, requires_login(my_view1)),
(r’^view2/$’, requires_login(my_view2)),
(r’^view3/$’, requires_login(my_view3)),
25. If you intend your code to be used on multiple Django-based sites, you should consider arranging such At Including
a way that allows for “including.”
any point, your URLconf Other
can “include” URLconfs
other URLconf modules. This essentially “roots” other ones. For example, this URLconf includes other URLconfs:
from django.conf.urls.defaults import *
9.2. Including Other URLconfs Django Book Documentation, Release 0.1
urlpatterns = patterns(’’,
(r’^weblog/’, include(’mysite.blog.urls’)),
(r’^photos/’, include(’mysite.photos.urls’)),
(r’^about/$’, ’mysite.views.about’),
)
(We saw this before in Chapter 6, when we introduced the Django admin site. The admin site that you merely include() within yours.)
There’s an important gotcha here: the regular expressions in this example that point to an include() $ (end-of-string match character) but do include a trailing slash. Whenever Django encounters off whatever part of the URL matched up to that point and sends the remaining string to the further processing.
Continuing this example, here’s the URLconf mysite.blog.urls:
from django.conf.urls.defaults import *
urlpatterns = patterns(’’,
(r’^(dddd)/$’, ’mysite.blog.views.year_detail’),
26. • /about/: This matches the view mysite.views.about in the first URLconf, demonstrating mix include() patterns with non-include() patterns.
How
Captured
Parameters
Work
with
include()
9.2.1 How Captured Parameters Work with include()
An included URLconf receives any captured parameters from parent URLconfs, for example:
# root urls.py
from django.conf.urls.defaults import *
urlpatterns = patterns(’’,
(r’^(?P<username>w+)/blog/’, include(’foo.urls.blog’)),
)
# foo/urls/blog.py
from django.conf.urls.defaults import *
urlpatterns = patterns(’’,
(r’^$’, ’foo.views.blog_index’),
(r’^archive/$’, ’foo.views.blog_archive’),
)
In this example, the captured username variable is passed to the included URLconf and, function within that URLconf.
27. 9.2.2 How Extra URLconf Options Work with include()
Similarly, you can pass extra URLconf options to include(), just as you can pass extra normal view – as a dictionary. When you do this, each line in the included URLconf will be For example, the following two URLconf sets are functionally identical.
Set one:
# urls.py
How
Extra
URLconf
Options
Work
with
include()
from django.conf.urls.defaults import *
urlpatterns = patterns(’’,
(r’^blog/’, include(’inner’), {’blogid’: 3}),
)
# inner.py
from django.conf.urls.defaults import *
urlpatterns = patterns(’’,
(r’^archive/$’, ’mysite.views.archive’),
(r’^about/$’, ’mysite.views.about’),
(r’^rss/$’, ’mysite.views.rss’),
)
Set two: