An advanced forms presentation given with Miguel Araujo (marajop) at DjangoCon 2011. The transcript and slides is aimed at getting into Django Core, and Jacob Kaplan-Moss has stated this is his plan.
This document outlines a workshop on crafting monitoring and evaluation plans. It discusses that the workshop aims to teach participants how to formulate an M&E plan. It explains that an M&E plan is a process of developing a clear plan to monitor and evaluate a project's goals and objectives. Developing an M&E plan is important as it ensures results are achieved, generates shared understanding, supports learning, improves focus on priorities, and helps determine and manage success. The document provides instructions on the 8 steps to formulate an M&E plan which includes developing a project framework, SMART indicators, identifying data needs, responsible parties and timelines. It concludes with an exercise where participants will practice formulating their own M&
Exploratory testing is a form of functional testing that relies on the tester's domain knowledge, experience with similar products, and intuition to test an application. The tester uses their expertise to identify potential soft spots or errors with minimal effort by assuming special values and conditions. While exploratory testing can find issues, it requires domain knowledge and there is no collaboration with developers.
2.1 Data Mining-classification Basic conceptsKrish_ver2
This document discusses classification and decision trees. It defines classification as predicting categorical class labels using a model constructed from a training set. Decision trees are a popular classification method that operate in a top-down recursive manner, splitting the data into purer subsets based on attribute values. The algorithm selects the optimal splitting attribute using an evaluation metric like information gain at each step until it reaches a leaf node containing only one class.
CMMI (Capability Maturity Model Integration) is a proven industry framework to improve product quality and development efficiency for both hardware and software
This program is designed for those involved in drilling and service contracts from both the operator and contractor perspective. Attendees will actively participate in discussions pertaining to contracting philosophy and terms as well as industry custom and practice.
The program will cover all aspects of contracts including the tender process, letters of intent, contract negotiation, contract administration, ethics considerations and dispute resolution. Special emphasis will be placed on the most controversial and highly negotiated provisions of drilling and service contracts, the impact of decisions in the pending Macondo litigation and contract administration in the event of a crisis.
While the program will focus on offshore and land daywork drilling contracts, incentive contracts (footage, turnkey and performance bonus) and variable day rate drilling contracts will also be reviewed and analyzed along with oil service contracts.
Planning for software quality assurance lecture 6Abdul Basit
The document discusses planning for software quality assurance (SQA) and outlines the key elements of a software quality assurance plan (SQAP). It notes that an SQAP provides a roadmap for SQA activities and defines techniques, procedures, and methodologies that will be used to ensure timely delivery of software that meets requirements. The document then describes various sections that should be included in an SQAP, such as goals, tasks, standards, reviews, testing, problem reporting, tools, code control, and training. It also discusses the IEEE standard for SQAPs and provides examples of what types of information should be included in each SQAP section.
EVALUATING SOFTWAREQUALITY : A QUANTITATIVEAPPROACHPriyanka Karancy
The document discusses quality assurance and control in software development. It states that quality assurance ensures software meets requirements, while quality control evaluates products against standards. It also discusses operational profiles, usability testing, and selecting a team with various qualifications to develop an operational profile/usage model for an automated airline reservation system.
The document discusses various software metrics that can be used to measure attributes of software products and processes. It describes metrics for size (e.g. lines of code), complexity (e.g. cyclomatic complexity), quality (e.g. defects per KLOC), design (e.g. coupling and cohesion), and object-oriented software (e.g. weighted methods per class). The goals of metrics include estimating costs, evaluating quality, and improving processes and products.
This document discusses contract reviews in software engineering projects. It describes stages of contract review including reviewing proposals before submission and reviewing contracts before signing. It outlines objectives of these reviews such as clarifying requirements, examining risks, and ensuring all agreements are documented correctly. Factors that impact the extent of review include project magnitude, complexity, and experience level. Reviewers can include proposal team members, outside experts, or a separate professional. Checklists are provided for reviewing proposals and contracts. Internal projects within an organization are also discussed as sometimes lacking a full customer-supplier relationship.
Term weighting assigns a weight to terms in documents to quantify their importance in describing the document's contents. Weights are higher for terms that occur frequently in a document but rarely in other documents. Term frequency in a document and inverse document frequency are used to calculate TF-IDF weights. Term occurrences may be correlated, so term weights should reflect their correlation. For example, terms like "computer" and "network" often appear together in documents about computer networks.
I apologize, upon reviewing the document I do not feel comfortable rating or assessing any organization's software processes without their consent or more detailed information.
The document provides information on various quality models and standards including Six Sigma, Total Quality Management (TQM), ISO 9001. It discusses the goals, methodology, and evolution of Six Sigma. It explains the key principles and structure of TQM and ISO 9001. It also provides a case study on how Toyota has implemented TQM based on principles of customer focus, continuous improvement, and total participation.
During the 2015 American Evaluation Association's Annual Conference in Chicago, Katherine Haugh and Deborah Grodzicki conducted a real time data mini-study to see which evaluation approaches evaluators at #eval15 use most frequently in their work. Basing their mini-study off of Marvin C. Alkin's "Evaluation Roots: A Wider Perspective of Theorists’ Views and Influences," they asked evaluators to vote for the top two approaches they used most often. This handout accompanied the real time data mini-study to provide more information about the formation of the evaluation theory tree, it's three branches, and definitions of the evaluation approaches associated with each branch.
Function of software quality assurance lecture 2Abdul Basit
The document discusses the function of software quality assurance (SQA). It outlines that SQA includes auditing, reviews, and process checks to enable independent reviews of work. It also requires knowledge of statistics, quality control principles, software processes, and dealing with people. Establishing an SQA function first requires deciding how important quality is versus schedules. It then ensures standards, procedures, reviews, documentation, change control, testing high-risk areas, and satisfying tasks before starting new ones. SQA enforces project and development standards, improving quality and cost-effectiveness. Its objectives are to improve quality through monitoring software and processes, ensuring compliance, and identifying inadequacies.
Create & Execute First Hadoop MapReduce Project in.pptxvishal choudhary
The document provides a 12 step guide to create and execute a first Hadoop MapReduce project in Eclipse. The steps include installing prerequisites like Hadoop, Eclipse, and Java, creating a project in Eclipse, adding required Hadoop jar files, creating Mapper, Reducer and Driver classes, compiling the code into a jar file, and executing the MapReduce job on Hadoop by running the jar file.
The document outlines elements of a development plan and quality assurance plan for a software project. The development plan covers deliverables, interfaces, methodology, standards, milestones, organization, facilities, risks, and costs. The quality assurance plan defines quality goals, review activities, tests, and configuration management. It also discusses classes of development risks like scheduling and requirements, and provides examples of top risks. Finally, it describes a risk management process and potential actions to prevent and resolve risks through prevention, identification, and resolution. The overall objectives are to plan adequately for successful and timely project completion through scheduling, resource allocation, risk resolution, quality activities, and management control.
The document discusses the usage of articles in the English language. It notes that there are two types of articles: definite ("the") and indefinite ("a"/"an"). It then examines the rules for using definite and indefinite articles based on whether the noun is generic, indefinite, or definite, and whether it is singular, plural, or non-count. The document provides examples and explanations for when to use "a/an", "the", or no article with different types of nouns.
The document discusses the changes that are made when converting direct speech to indirect speech in English. It notes that quotation marks and speech markers are removed in indirect speech. Pronouns may change based on the speaker, and verb tenses typically change from present to past. Other changes can include references to time and place. The document provides examples of direct and indirect speech to demonstrate these common changes.
The document discusses the rules for changing direct speech into indirect or reported speech in English. It covers changes to pronouns, adverbs of time and place, verb tenses, modal verbs, types of sentences including questions, commands and requests. Examples are provided to illustrate each rule with the direct speech changing to the appropriate reported version.
This document discusses the rules for reported speech or indirect speech. It explains that reported speech is used to tell someone what another person said without using their exact words. Key changes that can occur in reported speech include changing verb tenses, pronouns, words referring to time and place, and dropping quotation marks. The rules for changing direct to reported speech are provided for verbs, pronouns, time words, place words, questions, requests and more.
in this ppt we discuss about article topic which is aimportant topic of english grammmer and manish kumar created this presentation,who is owner of http://exclusivestoke.com
This document explains the differences between the articles "a", "an", and "the" in English. The definite article "the" refers to specific or particular nouns, while the indefinite articles "a" and "an" refer to non-specific nouns. The article "an" is used before words beginning with vowel sounds, while "a" is used before consonant sounds. Some exceptions are provided. A quiz with examples tests the reader on proper article usage.
This document discusses definite and indefinite articles in English. It provides examples of using "a/an" versus "one" when referring to singular countable nouns like bicycle and elephant. It also shows how to use "the" when something has already been mentioned or is unique in the context.
The document discusses the differences between direct and indirect speech. It provides examples of how to change direct speech into indirect speech, including changing pronouns, tenses, adverbs of time and place, interrogative sentences, imperative sentences, and exclamatory sentences. The key differences covered are using "that" instead of commas, changing pronouns according to the SON formula, changing present and past tense verbs, changing adverbs of time and place, changing interrogative sentences into statements, using "to" after imperative verbs, and using "that" after reporting verbs for exclamatory sentences.
This document provides instruction on using the articles "a", "an", and "the" in English. It explains that "a" and "an" are used before singular nouns to refer to one unspecified person or thing, with "an" used before words beginning with a vowel sound. "The" is used to refer to a specific or defined noun. It gives examples of when to use definite ("the") vs indefinite ("a"/"an") articles. It also discusses cases where no article is used, like with names or plural nouns. Exercises are included to help readers identify the correct article in different contexts.
1) Reported speech involves changing verbs, pronouns, possessive adjectives, and some adverbs when reporting what someone else has said. This is done to report the statement in the past tense.
2) Verb tenses change in reported speech, such as present simple becoming past simple. Pronouns and adjectives change depending on who the message is being referred to. Some adverbs like "now" and "there" also change.
3) There are different rules for reporting statements, questions, and commands in sentences. For statements, verbs, pronouns, and adverbs change and the sentence is introduced with "say" or "tell". For questions, word
The document discusses the use of articles 'a', 'an', and 'the' in English. It explains that 'a' is used before consonant sounds and 'an' is used before vowel sounds. It also notes exceptions like 'university' and 'hour'. The document also compares the use of 'a/an' with nouns introduced for the first time versus 'the' which refers back to something already mentioned. It provides examples of special uses of 'a/an' with prices, frequencies, speeds, and jobs. Finally, it discusses uses of 'the' when there is only one of an item or with musical instruments.
This document discusses contract reviews in software engineering projects. It describes stages of contract review including reviewing proposals before submission and reviewing contracts before signing. It outlines objectives of these reviews such as clarifying requirements, examining risks, and ensuring all agreements are documented correctly. Factors that impact the extent of review include project magnitude, complexity, and experience level. Reviewers can include proposal team members, outside experts, or a separate professional. Checklists are provided for reviewing proposals and contracts. Internal projects within an organization are also discussed as sometimes lacking a full customer-supplier relationship.
Term weighting assigns a weight to terms in documents to quantify their importance in describing the document's contents. Weights are higher for terms that occur frequently in a document but rarely in other documents. Term frequency in a document and inverse document frequency are used to calculate TF-IDF weights. Term occurrences may be correlated, so term weights should reflect their correlation. For example, terms like "computer" and "network" often appear together in documents about computer networks.
I apologize, upon reviewing the document I do not feel comfortable rating or assessing any organization's software processes without their consent or more detailed information.
The document provides information on various quality models and standards including Six Sigma, Total Quality Management (TQM), ISO 9001. It discusses the goals, methodology, and evolution of Six Sigma. It explains the key principles and structure of TQM and ISO 9001. It also provides a case study on how Toyota has implemented TQM based on principles of customer focus, continuous improvement, and total participation.
During the 2015 American Evaluation Association's Annual Conference in Chicago, Katherine Haugh and Deborah Grodzicki conducted a real time data mini-study to see which evaluation approaches evaluators at #eval15 use most frequently in their work. Basing their mini-study off of Marvin C. Alkin's "Evaluation Roots: A Wider Perspective of Theorists’ Views and Influences," they asked evaluators to vote for the top two approaches they used most often. This handout accompanied the real time data mini-study to provide more information about the formation of the evaluation theory tree, it's three branches, and definitions of the evaluation approaches associated with each branch.
Function of software quality assurance lecture 2Abdul Basit
The document discusses the function of software quality assurance (SQA). It outlines that SQA includes auditing, reviews, and process checks to enable independent reviews of work. It also requires knowledge of statistics, quality control principles, software processes, and dealing with people. Establishing an SQA function first requires deciding how important quality is versus schedules. It then ensures standards, procedures, reviews, documentation, change control, testing high-risk areas, and satisfying tasks before starting new ones. SQA enforces project and development standards, improving quality and cost-effectiveness. Its objectives are to improve quality through monitoring software and processes, ensuring compliance, and identifying inadequacies.
Create & Execute First Hadoop MapReduce Project in.pptxvishal choudhary
The document provides a 12 step guide to create and execute a first Hadoop MapReduce project in Eclipse. The steps include installing prerequisites like Hadoop, Eclipse, and Java, creating a project in Eclipse, adding required Hadoop jar files, creating Mapper, Reducer and Driver classes, compiling the code into a jar file, and executing the MapReduce job on Hadoop by running the jar file.
The document outlines elements of a development plan and quality assurance plan for a software project. The development plan covers deliverables, interfaces, methodology, standards, milestones, organization, facilities, risks, and costs. The quality assurance plan defines quality goals, review activities, tests, and configuration management. It also discusses classes of development risks like scheduling and requirements, and provides examples of top risks. Finally, it describes a risk management process and potential actions to prevent and resolve risks through prevention, identification, and resolution. The overall objectives are to plan adequately for successful and timely project completion through scheduling, resource allocation, risk resolution, quality activities, and management control.
The document discusses the usage of articles in the English language. It notes that there are two types of articles: definite ("the") and indefinite ("a"/"an"). It then examines the rules for using definite and indefinite articles based on whether the noun is generic, indefinite, or definite, and whether it is singular, plural, or non-count. The document provides examples and explanations for when to use "a/an", "the", or no article with different types of nouns.
The document discusses the changes that are made when converting direct speech to indirect speech in English. It notes that quotation marks and speech markers are removed in indirect speech. Pronouns may change based on the speaker, and verb tenses typically change from present to past. Other changes can include references to time and place. The document provides examples of direct and indirect speech to demonstrate these common changes.
The document discusses the rules for changing direct speech into indirect or reported speech in English. It covers changes to pronouns, adverbs of time and place, verb tenses, modal verbs, types of sentences including questions, commands and requests. Examples are provided to illustrate each rule with the direct speech changing to the appropriate reported version.
This document discusses the rules for reported speech or indirect speech. It explains that reported speech is used to tell someone what another person said without using their exact words. Key changes that can occur in reported speech include changing verb tenses, pronouns, words referring to time and place, and dropping quotation marks. The rules for changing direct to reported speech are provided for verbs, pronouns, time words, place words, questions, requests and more.
in this ppt we discuss about article topic which is aimportant topic of english grammmer and manish kumar created this presentation,who is owner of http://exclusivestoke.com
This document explains the differences between the articles "a", "an", and "the" in English. The definite article "the" refers to specific or particular nouns, while the indefinite articles "a" and "an" refer to non-specific nouns. The article "an" is used before words beginning with vowel sounds, while "a" is used before consonant sounds. Some exceptions are provided. A quiz with examples tests the reader on proper article usage.
This document discusses definite and indefinite articles in English. It provides examples of using "a/an" versus "one" when referring to singular countable nouns like bicycle and elephant. It also shows how to use "the" when something has already been mentioned or is unique in the context.
The document discusses the differences between direct and indirect speech. It provides examples of how to change direct speech into indirect speech, including changing pronouns, tenses, adverbs of time and place, interrogative sentences, imperative sentences, and exclamatory sentences. The key differences covered are using "that" instead of commas, changing pronouns according to the SON formula, changing present and past tense verbs, changing adverbs of time and place, changing interrogative sentences into statements, using "to" after imperative verbs, and using "that" after reporting verbs for exclamatory sentences.
This document provides instruction on using the articles "a", "an", and "the" in English. It explains that "a" and "an" are used before singular nouns to refer to one unspecified person or thing, with "an" used before words beginning with a vowel sound. "The" is used to refer to a specific or defined noun. It gives examples of when to use definite ("the") vs indefinite ("a"/"an") articles. It also discusses cases where no article is used, like with names or plural nouns. Exercises are included to help readers identify the correct article in different contexts.
1) Reported speech involves changing verbs, pronouns, possessive adjectives, and some adverbs when reporting what someone else has said. This is done to report the statement in the past tense.
2) Verb tenses change in reported speech, such as present simple becoming past simple. Pronouns and adjectives change depending on who the message is being referred to. Some adverbs like "now" and "there" also change.
3) There are different rules for reporting statements, questions, and commands in sentences. For statements, verbs, pronouns, and adverbs change and the sentence is introduced with "say" or "tell". For questions, word
The document discusses the use of articles 'a', 'an', and 'the' in English. It explains that 'a' is used before consonant sounds and 'an' is used before vowel sounds. It also notes exceptions like 'university' and 'hour'. The document also compares the use of 'a/an' with nouns introduced for the first time versus 'the' which refers back to something already mentioned. It provides examples of special uses of 'a/an' with prices, frequencies, speeds, and jobs. Finally, it discusses uses of 'the' when there is only one of an item or with musical instruments.
This document defines and provides examples of different types of verbs including action verbs, linking verbs, and helping/main verbs. It explains that action verbs show action by the subject, linking verbs connect the subject to the predicate, and helping verbs assist the main verb. Several sentences are then provided and the reader is asked to identify the verb and its type in each sentence.
This document discusses Python and the Django web framework. It introduces Python and its uses at companies like Google. It then discusses installing and using Django, including using PyPI to install Django with easy_install, Django's model-view-controller architecture and features like object-relational mapping, templates and RSS/Atom feeds. It demonstrates starting a Django project and app and running initial migrations.
Pharo4: Plans and Dreams.
Talk from Fosdem 2014
On Youtube: http://www.youtube.com/watch?v=mUV9E03u52g
More about Pharo at: http://pharo.org
Pharo4: Plans and Dreams.
Talk from Fosdem 2014
On Youtube: http://www.youtube.com/watch?v=mUV9E03u52g
More about Pharo at: http://pharo.org
Django Package Thunderdome by Audrey Roy & Daniel GreenfeldAudrey Roy
What makes a package useful? What is it about certain packages that makes them must-haves for any project?
We’ll go over topics like: purpose, structure, docs, tests, availability on PyPI and Github/Bitbucket, activity, and more.
We will visit some of the most useful grid categories on djangopackages.com and highlight our top package picks, showing examples of what makes the top packages so great and what could use improvement.
Exploring push server options for Django. My presentation for Python User Group meetup, March 2018.
Some images borrowed from https://blog.heroku.com/in_deep_with_django_channels_the_future_of_real_time_apps_in_django.
This document discusses common Go programming mistakes and how to avoid them. It addresses issues with pointers like nil pointer dereferences and using optional types instead. Goroutines in loops are also covered, emphasizing the need to cancel contexts to avoid leaks. Other topics include differences between nil and typed nil, avoiding the default HTTP client, and establishing patterns through research to prevent implicit behavior from causing errors.
The document discusses developing with the Django web framework. It covers installing Django, creating projects and apps, defining models, views, templates, and urls. It also describes Django's MTV pattern, generic views, built-in template tags and filters, contrib modules, and resources for learning more about Django.
Drupal 8: Huge wins, a Bigger Community, and why you (and I) will Love itRyan Weaver
The document discusses the benefits of Drupal 8 over Drupal 7. Drupal 8 embraces modern PHP standards and libraries, allowing for easier code sharing, improved quality, and new possibilities. Key benefits include leveraging libraries like Symfony, Twig and others with no development effort, improved developer experience through object oriented code and standards, and the ability to more easily create new types of applications and distributions. Drupal 8 innovates away from outdated Drupal 7 technologies and practices to build a stronger, more interoperable community.
We Want YOU! Contributing to the Django CommunityMarcel Chastain
Contribute to the communities surrounding Open Source software like Django, Python, Github libraries easily - we need all the help we can get! In person, over the internet - it's easy!
This document discusses Perl 5 meta programming and provides examples of how to implement meta programming in Perl 5. It describes techniques like string eval, modifying the symbol table and typeglobs, using AUTOLOAD, Package::Stash, B:: modules, Class::Inspector, Class::Method::Modifiers, and Moo to get and set information about classes and define/modify methods and packages at runtime. It emphasizes writing tests and solving problems with existing modules when possible.
Presenting at the Microsoft Devs HK Meetup on 13 June, 2018
Code for presentation: https://github.com/sadukie/IntroToPyForCSharpDevs
Azure Notebook for presentation:
https://notebooks.azure.com/cletechconsulting/libraries/introtopyforcsharpdevs
This document summarizes the history and future plans for optimizations to the Pharo virtual machine (VM). It discusses past improvements like Spur in Pharo 5 that provided 1.8x faster performance. Pharo 6 focused on compaction and minor optimizations. Future work in Pharo 7 could include an incremental garbage collector and optimizations from the Sista just-in-time compiler that aim to provide 1.5-5x faster performance. The goals are to balance program readability and performance.
Why you should use Django in your next project.Eyad Toma
The document promotes using Django, an open-source web framework, for upcoming projects. It highlights that Django includes common components like object-relational mapping, user authentication and caching out of the box, but these features are optional and can be replaced. The document also notes that Django can be easily extended through thousands of third-party plug-ins and has a large global user base, including in the MENA region. In summary, it pitches Django as the best Python web framework that is fully-featured yet flexible.
This document provides an introduction to the Padrino web framework. It begins with an overview of the speaker and background on various web frameworks like Rails, Sinatra, and Padrino. It then discusses features of Sinatra like being a microframework and how Padrino combines aspects of both Sinatra and Rails by providing a full-stack solution with components like generators and a project structure similar to Rails. Sample code demonstrations compare starting a new Rails and Padrino project.
python full stack course in hyderabad...sowmyavibhin
Empower your career with our Python Full Stack Course in Hyderabad. Gain hands-on experience, industry recognition, and job placement assistance for a thriving journey in full-stack development.
python full stack course in hyderabad...sowmyavibhin
Empower your career with our Python Full Stack Course in Hyderabad. Gain hands-on experience, industry recognition, and job placement assistance for a thriving journey in full-stack development.
python full stack course in madhapur, hyderabadneeraja0480
Empower your career with our Python Full Stack Course in Hyderabad. Gain hands-on experience, industry recognition, and job placement assistance for a thriving journey in full-stack development.
How to Write a Popular Python Library by AccidentDaniel Greenfeld
We gave this talk as the opening keynote speech at PyCon Singapore. The theme of the talk is that most complex projects begin from humble origins. That you should create your own projects, sharing your knowledge and expertise.
10 more things you can do with the Python programming language. Python is used in science, engineer, and forward thinking entrepreneurial projects like Instagram and Pinterest.
The document provides tips for building maintainable and scalable projects. It discusses the importance of following best practices like writing tests, using version control, and avoiding premature optimization. It also warns against technical debt and recommends focusing on simplicity over complexity when starting a new project.
My keynote speech from EuroPython, this talk explores what it is like being a developer in a community filled with experts from around the world. The goal of the talk is to provide useful content for beginners and topics of discussion for more advanced developers, while also focusing on Python’s strengths. Video of this talk is at http://www.youtube.com/watch?v=7TImWbnUDeI
This document provides an overview and introduction to different tools for data visualization, including Many Eyes, Google Charts, and D3.js. Many Eyes is described as a free and easy to use tool from IBM that allows rapid visualization without coding. Google Charts requires some coding but has good documentation and customization options. D3.js is a JavaScript library that has powerful capabilities but a steep learning curve and requires coding skills. Examples are provided for visualizing different types of data with Many Eyes and key concepts are demonstrated for D3.js.
In the Python community we are taught from the outset of learning the language that the Zen of Python serves as a guide for how we should construct our codebases and projects. Rather than go into the zen-like meanings of each statement, this talk will explore how individual koans are implemented via detailed displays of sophisticated code examples.
This document discusses different options for using MongoDB with Django, including pymongo, MongoEngine, MongoKit, and Django-nonrel. PyMongo is the lowest-level but fastest option, while MongoEngine provides Django-like models for MongoDB. MongoKit offers more structure than PyMongo but similar querying. Django-nonrel integrates MongoDB support directly into Django but requires maintaining a fork. The authors debate the benefits of schemaless versus structured models for MongoDB and how to improve integration between Django and MongoDB.
Daniel Greenfeld gave a presentation titled "Intro to Python" where he demonstrated 21 cool things that can be done with Python. These included running Python anywhere, learning it quickly, introspecting objects to see their attributes and methods, performing string operations, formatting strings, basic math operations, and working with lists. The presentation emphasized Python's simplicity, readability, and extensive standard library and ecosystem.
Daniel Greenfeld gave a presentation titled "Intro to Python". The presentation introduced Python and covered 21 cool things that can be done with Python, including running Python anywhere, learning Python quickly, introspecting Python objects, working with strings, lists, generators, sets and dictionaries. The presentation emphasized Python's simplicity, readability, extensibility and how it can be used for a wide variety of tasks.
This document summarizes Daniel Greenfeld's presentation on using OAuth for user registration and authentication in Django projects. It discusses how OAuth can allow users to register and login using existing social media accounts like Twitter or Facebook, avoiding the need for separate usernames and passwords. It recommends using the django-social-auth package, which supports OAuth authentication across multiple providers while addressing issues like varying implementation details and a lack of documentation in other packages. The presentation provides instructions for installing django-social-auth and configuring OAuth settings and signal receivers.
The document discusses the Python principle "There should be one--and preferably only one--obvious way to do it" from PEP 20. It questions how far this principle extends in different domains like web frameworks, desktop GUIs, and image processing libraries. While the core language aims for a single obvious way, larger problem spaces may have valid tradeoffs requiring multiple approaches or libraries.
Admitting my flaws and turning them into virtues! This is a full length talk given it at DjangoCon US 2011, PyCon Australia 2011, and LA Django. The earliest version was a lightning talk given at the 2011 Hollywood hackathon.
This document summarizes Daniel Greenfeld's presentation on Python worst practices and fixed practices. The presentation covers various topics like fundamentals, classes, and presentation styles. For each worst practice, there is a corresponding fixed practice shown side by side. Some examples of worst practices discussed include using single-letter variable names, not using enumerate, and implementing Java-style getters and setters in Python classes. The fixed practices demonstrate more readable Python code that follows PEP 8 style guidelines and leverages Python features like properties.
Just to be clear, all of these things suck. Please DO NOT use these techniques! It was a joke, and if you attempt any of these things you are making a big mistake.
The document discusses various questions and strategies for selling Django as a web development framework. It addresses how to find and hire Django developers, fight FUD from competitors, sell Django to investors by emphasizing productivity gains, and shares a success story where a company used Django to build a project in 2 months with 4 developers compared to a previous estimate of 7 months with 30 developers and $300 million.
The slides printed for attendees of the Pycon 2010 Long Pinax Tutorial. James Tauber was the co-author and deserves tons of credit for his work. So does Brian Rosner and the rest of the Pinax team.
This document discusses the importance of testing in Django and provides examples of how to write tests. It describes how the Pinax project added tests after users were able to incorrectly edit ticket statuses. It recommends writing unit tests using the Django testing framework and provides a pattern for organizing and writing tests, including setting up test data and individual test methods. The document emphasizes that code without tests is "broken by design" and that writing tests improves code quality and avoids embarrassment.
Daniel Greenfeld introduces himself as a NASA geek, Pinax core developer, and Djangonaut. He then summarizes Section 508, rules enacted by the US government requiring websites and technology be accessible to individuals with disabilities. Greenfeld notes these rules are enforceable for government agencies and contractors but don't truly require accessibility. He advocates for Django Uni-Form, a custom filter and template tag that combines Django forms documentation and the Uni-Form CSS library to create accessible forms that comply with Section 508.
Explore the growing trend of payroll outsourcing in the UK with key 2025 statistics, market insights, and benefits for accounting firms. This infographic highlights why more firms are turning to outsourced payroll services for UK businesses to boost compliance, cut costs, and streamline operations. Discover how QXAS can help your firm stay ahead.
for more details visit:- https://qxaccounting.com/uk/service/payroll-outsourcing/
Alan Stalcup is the visionary leader and CEO of GVA Real Estate Investments. In 2015, Alan spearheaded the transformation of GVA into a dynamic real estate powerhouse. With a relentless commitment to community and investor value, he has grown the company from a modest 312 units to an impressive portfolio of over 29,500 units across nine states. He graduated from Washington University in St. Louis and has honed his knowledge and know-how for over 20 years.
The Mobile Hub Part II provides an extensive overview of the integration of glass technologies, cloud systems, and remote building frameworks across industries such as construction, automotive, and urban development.
The document emphasizes innovation in glass technologies, remote building systems, and cloud-based designs, with a focus on sustainability, scalability, and long-term vision.
V1 The European Portal Hub, centered in Oviedo, Spain, is significant as it serves as the central point for 11 European cities' glass industries. It is described as the first of its kind, marking a major milestone in the development and integration of glass technologies across Europe. This hub is expected to streamline communication, foster innovation, and enhance collaboration among cities, making it a pivotal element in advancing glass construction and remote building projects. BAKO INDUSTRIES supported by Magi & Marcus Eng will debut its European counterpart by 2038. https://www.slideshare.net/slideshow/comments-on-cloud-stream-part-ii-mobile-hub-v1-hub-agency-pdf/278633244
Brandon Flatley masterfully blends creativity and community impact. As a mixologist and small business owner, he delivers unforgettable cocktail experiences. A musician at heart, he excels in composition and recording.
Alec Lawler - A Passion For Building Brand AwarenessAlec Lawler
Alec Lawler is an accomplished show jumping athlete and entrepreneur with a passion for building brand awareness. He has competed at the highest level in show jumping throughout North America and Europe, winning numerous awards and accolades, including the National Grand Prix of the Desert in 2014. Alec founded Lawler Show Jumping LLC in 2019, where he creates strategic marketing plans to build brand awareness and competes at the highest international level in show jumping throughout North America.
Alaska Silver: Developing Critical Minerals & High-Grade Silver Resources
Alaska Silver is advancing a prolific 8-km mineral corridor hosting two significant deposits. Our flagship high-grade silver deposit at Waterpump Creek, which contains gallium (the U.S. #1 critical mineral), and the historic Illinois Creek mine anchor our 100% owned carbonate replacement system across an expansive, underexplored landscape.
Waterpump Creek: 75 Moz @ 980 g/t AgEq (Inferred), open for expansion north and south
Illinois Creek: 525 Koz AuEq - 373 Koz @ 1.3 g/t AuEq (Indicated), 152 Koz @ 1.44 g/t AuEq (Inferred)
2024 "Warm Springs" Discovery: First copper, gold, and Waterpump Creek-grade silver intercepts 0.8 miles from Illinois Creek
2025 Focus: Targeting additional high-grade silver discoveries at Waterpump Creek South and initiating studies on gallium recovery potential.
From Dreams to Threads: The Story Behind The ChhapaiThe Chhapai
Chhapai is a direct-to-consumer (D2C) lifestyle fashion brand founded by Akash Sharma. We believe in providing the best quality printed & graphic t-shirts & hoodies so you can express yourself through what you wear, because everything can’t be explained in words.
The Fascinating World of Hats: A Brief History of Hatsnimrabilal030
Hats have been integral to human culture for centuries, serving various purposes from protection against the elements to fashion statements. This article delves into hats' history, types, and cultural significance, exploring how they have evolved and their role in contemporary society.
Looking for Reliable BPO Project Providers?"anujascentbpo
"Looking for Reliable BPO Project Providers?" tailored for businesses potentially seeking outsourcing partners, especially those in or considering Noida and India.
Kiran Flemish is a dynamic musician, composer, and student leader pursuing a degree in music with a minor in film and media studies. As a talented tenor saxophonist and DJ, he blends jazz with modern digital production, creating original compositions using platforms like Logic Pro and Ableton Live. With nearly a decade of experience as a private instructor and youth music coach, Kiran is passionate about mentoring the next generation of musicians. He has hosted workshops, raised funds for causes like the Save the Music Foundation and Type I Diabetes research, and is eager to expand his career in music licensing and production.
Comments on Cloud Stream Part II Mobile Hub V1 Hub Agency.pdfBrij Consulting, LLC
The Mobile Hub Part II provides an extensive overview of the integration of glass technologies, cloud systems, and remote building frameworks across industries such as construction, automotive, and urban development.
The document emphasizes innovation in glass technologies, remote building systems, and cloud-based designs, with a focus on sustainability, scalability, and long-term vision.
V1 The European Portal Hub, centered in Oviedo, Spain, is significant as it serves as the central point for 11 European cities' glass industries. It is described as the first of its kind, marking a major milestone in the development and integration of glass technologies across Europe. This hub is expected to streamline communication, foster innovation, and enhance collaboration among cities, making it a pivotal element in advancing glass construction and remote building projects. BAKO INDUSTRIES supported by Magi & Marcus Eng will debut its European counterpart by 2038.
NewBase 28 April 2025 Energy News issue - 1783 by Khaled Al Awadi_compressed...Khaled Al Awadi
Greetings
Attached our latest energy news
NewBase 28 April 2025 Energy News issue - 1783 by Khaled Al AwadiGreetings
Attached our latest energy news
NewBase 28 April 2025 Energy News issue - 1783 by Khaled Al AwadiGreetings
Attached our latest energy news
NewBase 28 April 2025 Energy News issue - 1783 by Khaled Al Awadi
Attn: Team Loyalz and Guest Students.
To give Virtual Gifts/Tips,
please visit the Temple Office at:
https://ldmchapels.weebly.com
Optional and Any amount is appreciated.
Thanks for Being apart of the team and student readers.
1. Advanced Django
Form Usage
by Daniel Greenfeld and Miguel Araujo
2. Daniel Greenfeld
• pydanny
• Python & Django developer for
Cartwheel Web / RevSys
• Founded django-uni-form
• Does Capoeira
• Lives in Los Angeles with his
Advanced Django Form Usage
http://www.flickr.com/photos/pydanny/4442245488/
Fiancé, Audrey Roy (audreyr)
@pydanny / @maraujop
2
3. Miguel Araujo
• maraujop
• Freelance Python developer
• Co-lead of django-uni-form
• Does Muay Thai
• Lives in Madrid with his
amazing girlfiend who does
Advanced Django Form Usage
aerospace for a living
@pydanny / @maraujop
• http://maraujop.github.com/
3
5. Tons of technical content
• We probably won’t have time for questions
Advanced Django Form Usage
@pydanny / @maraujop
4
6. Tons of technical content
• We probably won’t have time for questions
• Slides will be posted right after the talk
Advanced Django Form Usage
@pydanny / @maraujop
4
7. Tons of technical content
• We probably won’t have time for questions
• Slides will be posted right after the talk
• Too much content in the abstract
Advanced Django Form Usage
@pydanny / @maraujop
4
8. Tons of technical content
• We probably won’t have time for questions
• Slides will be posted right after the talk
• Too much content in the abstract
• Special thanks to:
Advanced Django Form Usage
@pydanny / @maraujop
4
9. Tons of technical content
• We probably won’t have time for questions
• Slides will be posted right after the talk
• Too much content in the abstract
• Special thanks to:
• Brian Rosner
Advanced Django Form Usage
@pydanny / @maraujop
4
10. Tons of technical content
• We probably won’t have time for questions
• Slides will be posted right after the talk
• Too much content in the abstract
• Special thanks to:
• Brian Rosner
Advanced Django Form Usage
• James Tauber
@pydanny / @maraujop
4
11. Tons of technical content
• We probably won’t have time for questions
• Slides will be posted right after the talk
• Too much content in the abstract
• Special thanks to:
• Brian Rosner
Advanced Django Form Usage
• James Tauber
@pydanny / @maraujop
• Frank Wiles
4
12. Advanced Django Form Usage
@pydanny / @maraujop
Good Form Patterns
Fundamentals of
5
13. Fundamentals of
Good Form Patterns
• Zen of Python still applies
Advanced Django Form Usage
@pydanny / @maraujop
5
14. Fundamentals of
Good Form Patterns
• Zen of Python still applies
• import this
Advanced Django Form Usage
@pydanny / @maraujop
5
15. Fundamentals of
Good Form Patterns
• Zen of Python still applies
• import this
• Spartan programming als0 is important
Advanced Django Form Usage
@pydanny / @maraujop
5
20. Calling forms the easy way
• Smaller, cleaner code makes our lives better
Advanced Django Form Usage
@pydanny / @maraujop
9
21. Calling forms the easy way
• Smaller, cleaner code makes our lives better
• Line 5 of the Zen of Python
Advanced Django Form Usage
@pydanny / @maraujop
9
22. Calling forms the easy way
• Smaller, cleaner code makes our lives better
• Line 5 of the Zen of Python
• Flat is better than nested.
Advanced Django Form Usage
@pydanny / @maraujop
9
23. Calling forms the easy way
• Smaller, cleaner code makes our lives better
• Line 5 of the Zen of Python
• Flat is better than nested.
• Aim for minimal boilerplate
Advanced Django Form Usage
@pydanny / @maraujop
9
24. Calling forms the easy way
• Smaller, cleaner code makes our lives better
• Line 5 of the Zen of Python
• Flat is better than nested.
• Aim for minimal boilerplate
Advanced Django Form Usage
• So you can focus on your business logic
@pydanny / @maraujop
9
26. A Basic Django Form
class MyForm(forms.Form):
name = forms.CharField(_('Name'), required=True)
Advanced Django Form Usage
@pydanny / @maraujop
11
27. Standard views.py
def my_view(request, template_name='myapp/my_form.html'):
if request.method == 'POST':
form = MyForm(request.POST) # Form #1!
if form.is_valid(): # nested if!
do_x()
return redirect('/')
else:
form = MyForm() # Form #2!
return render(request, template_name, {'form': form})
Advanced Django Form Usage
@pydanny / @maraujop
12
28. Standard views.py
def my_view(request, template_name='myapp/my_form.html'):
if request.method == 'POST': Form #1
form = MyForm(request.POST) # Form #1!
if form.is_valid(): # nested if!
do_x()
return redirect('/')
else:
form = MyForm() # Form #2!
return render(request, template_name, {'form': form})
Advanced Django Form Usage
@pydanny / @maraujop
12
29. Standard views.py
def my_view(request, template_name='myapp/my_form.html'):
if request.method == 'POST': Form #1
form = MyForm(request.POST) # Form #1!
if form.is_valid(): # nested if!
do_x()
return redirect('/') Form #2
else:
form = MyForm() # Form #2!
return render(request, template_name, {'form': form})
Advanced Django Form Usage
@pydanny / @maraujop
12
30. Standard views.py
def my_view(request, template_name='myapp/my_form.html'):
if request.method == 'POST': Form #1
form = MyForm(request.POST) # Form #1!
if form.is_valid(): # nested if!
do_x()
return redirect('/') Form #2
else:
form = MyForm() # Form #2!
return render(request, template_name, {'form': form})
Advanced Django Form Usage
Only 1 nested if, but real code
@pydanny / @maraujop
gets much more complex
12
31. Standard views.py
def my_view(request, template_name='myapp/my_form.html'):
if request.method == 'POST': Form #1
form = MyForm(request.POST) # Form #1!
if form.is_valid(): # nested if!
do_x()
return redirect('/') Form #2
else:
form = MyForm() # Form #2!
return render(request, template_name, {'form': form})
Advanced Django Form Usage
Only 1 nested if, but real code
@pydanny / @maraujop
gets much more complex Custom business
goes here
12
32. Standard views.py
def my_view(request, template_name='myapp/my_form.html'):
if request.method == 'POST': Form #1
form = MyForm(request.POST) # Form #1!
if form.is_valid(): # nested if!
do_x()
return redirect('/') Form #2
else:
form = MyForm() # Form #2!
return render(request, template_name, {'form': form})
Advanced Django Form Usage
Only 1 nested if, but real code
@pydanny / @maraujop
gets much more complex Custom business
goes here
12
33. Easy views.py
def my_view(request, template_name='myapp/my_form.html'):
# sticks in a POST or renders empty form
form = MyForm(request.POST or None)
if form.is_valid():
do_x()
return redirect('home')
return render(request, template_name, {'form': form})
Advanced Django Form Usage
@pydanny / @maraujop
Custom business
goes here
13
34. Single form
Easy views.py
def my_view(request, template_name='myapp/my_form.html'):
# sticks in a POST or renders empty form
form = MyForm(request.POST or None)
if form.is_valid():
do_x()
return redirect('home')
return render(request, template_name, {'form': form})
Advanced Django Form Usage
@pydanny / @maraujop
Custom business
goes here
13
35. Single form
Easy views.py
def my_view(request, template_name='myapp/my_form.html'):
# sticks in a POST or renders empty form
form = MyForm(request.POST or None)
if form.is_valid():
do_x()
return redirect('home')
return render(request, template_name, {'form': form})
Advanced Django Form Usage
If no request.POST,
@pydanny / @maraujop
Custom business then instantiated with None
goes here
13
36. Easy views.py
def my_view(request, template_name='myapp/my_form.html'):
# sticks in a POST or renders empty form
form = MyForm(request.POST or None)
if form.is_valid():
do_x()
return redirect('home')
return render(request, template_name, {'form': form})
Advanced Django Form Usage
@pydanny / @maraujop
14
37. Easy views.py
def my_view(request, template_name='myapp/my_form.html'):
# sticks in a POST or renders empty form
form = MyForm(request.POST or None)
if form.is_valid():
do_x()
return redirect('home')
return render(request, template_name, {'form': form})
• 6 lines of code instead of 9
Advanced Django Form Usage
@pydanny / @maraujop
14
38. Easy views.py
def my_view(request, template_name='myapp/my_form.html'):
# sticks in a POST or renders empty form
form = MyForm(request.POST or None)
if form.is_valid():
do_x()
return redirect('home')
return render(request, template_name, {'form': form})
• 6 lines of code instead of 9
Advanced Django Form Usage
• 33.3333333333% less code to debug
@pydanny / @maraujop
14
39. Easy views.py
def my_view(request, template_name='myapp/my_form.html'):
# sticks in a POST or renders empty form
form = MyForm(request.POST or None)
if form.is_valid():
do_x()
return redirect('home')
return render(request, template_name, {'form': form})
• 6 lines of code instead of 9
Advanced Django Form Usage
• 33.3333333333% less code to debug
@pydanny / @maraujop
• One form instantiation
14
40. Easy views.py
def my_view(request, template_name='myapp/my_form.html'):
# sticks in a POST or renders empty form
form = MyForm(request.POST or None)
if form.is_valid():
do_x()
return redirect('home')
return render(request, template_name, {'form': form})
• 6 lines of code instead of 9
Advanced Django Form Usage
• 33.3333333333% less code to debug
@pydanny / @maraujop
• One form instantiation
• less conditionals == less edge case insanity
14
49. pydanny made
up statistics
• 91% of all Django projects use ModelForms
Advanced Django Form Usage
@pydanny / @maraujop
18
50. pydanny made
up statistics
• 91% of all Django projects use ModelForms
• 80% ModelForms require trivial logic
Advanced Django Form Usage
@pydanny / @maraujop
18
51. pydanny made
up statistics
• 91% of all Django projects use ModelForms
• 80% ModelForms require trivial logic
• 20% ModelForms require complicated logic
Advanced Django Form Usage
@pydanny / @maraujop
18
52. pydanny made
up statistics
• 91% of all Django projects use ModelForms
• 80% ModelForms require trivial logic
• 20% ModelForms require complicated logic
Advanced Django Form Usage
@pydanny / @maraujop
Let’s try and make that easy
18
53. A Basic ModelForm
class MyModelForm(forms.Form):
class Meta:
model = MyModel
fields = ['name']
Advanced Django Form Usage
@pydanny / @maraujop
19
54. Classic views.py for ModelForm
def my_model_edit(request, slug=slug, template_name='myapp/my_model_form.html'):
# I wouldn't call the variable model, because it's an instance of a model, it's confusing
mymodel = get_object_or_404(MyModel, slug=slug)
if request.method == 'POST':
form = MyForm(request, instance=mymodel)
if form.is_valid():
mymodel = form.save()
mymodel.day_shown = datetime.datetime.now() # Do any extra model stuff here
mymodel.save()
return redirect('home')
else:
form = MyForm(instance=mymodel)
return render(request, template_name, {'form': form, 'model': mymodel})
Advanced Django Form Usage
@pydanny / @maraujop
20
55. Classic views.py for ModelForm
def my_model_edit(request, slug=slug, template_name='myapp/my_model_form.html'):
# I wouldn't call the variable model, because it's an instance of a model, it's confusing
mymodel = get_object_or_404(MyModel, slug=slug)
if request.method == 'POST':
form = MyForm(request, instance=mymodel) Form #1
if form.is_valid():
mymodel = form.save()
mymodel.day_shown = datetime.datetime.now() # Do any extra model stuff here
mymodel.save()
return redirect('home')
else:
form = MyForm(instance=mymodel)
return render(request, template_name, {'form': form, 'model': mymodel})
Advanced Django Form Usage
@pydanny / @maraujop
20
56. Classic views.py for ModelForm
def my_model_edit(request, slug=slug, template_name='myapp/my_model_form.html'):
# I wouldn't call the variable model, because it's an instance of a model, it's confusing
mymodel = get_object_or_404(MyModel, slug=slug)
if request.method == 'POST':
form = MyForm(request, instance=mymodel) Form #1
if form.is_valid():
mymodel = form.save()
mymodel.day_shown = datetime.datetime.now() # Do any extra model stuff here
mymodel.save()
return redirect('home') Form #2
else:
form = MyForm(instance=mymodel)
return render(request, template_name, {'form': form, 'model': mymodel})
Advanced Django Form Usage
@pydanny / @maraujop
20
57. Classic views.py for ModelForm
def my_model_edit(request, slug=slug, template_name='myapp/my_model_form.html'):
# I wouldn't call the variable model, because it's an instance of a model, it's confusing
mymodel = get_object_or_404(MyModel, slug=slug)
if request.method == 'POST':
form = MyForm(request, instance=mymodel) Form #1
if form.is_valid():
mymodel = form.save()
mymodel.day_shown = datetime.datetime.now() # Do any extra model stuff here
mymodel.save()
return redirect('home') Form #2
else:
form = MyForm(instance=mymodel)
return render(request, template_name, {'form': form, 'model': mymodel})
Only 1 nested if, but real code
Advanced Django Form Usage
gets much more complex
@pydanny / @maraujop
20
58. Classic views.py for ModelForm
def my_model_edit(request, slug=slug, template_name='myapp/my_model_form.html'):
# I wouldn't call the variable model, because it's an instance of a model, it's confusing
mymodel = get_object_or_404(MyModel, slug=slug)
if request.method == 'POST':
form = MyForm(request, instance=mymodel) Form #1
if form.is_valid():
mymodel = form.save()
mymodel.day_shown = datetime.datetime.now() # Do any extra model stuff here
mymodel.save()
return redirect('home') Form #2
else:
form = MyForm(instance=mymodel)
return render(request, template_name, {'form': form, 'model': mymodel})
Only 1 nested if, but real code
Advanced Django Form Usage
gets much more complex
@pydanny / @maraujop
Custom business
goes here
20
59. Classic views.py for ModelForm
def my_model_edit(request, slug=slug, template_name='myapp/my_model_form.html'):
# I wouldn't call the variable model, because it's an instance of a model, it's confusing
mymodel = get_object_or_404(MyModel, slug=slug)
if request.method == 'POST':
form = MyForm(request, instance=mymodel) Form #1
if form.is_valid():
mymodel = form.save()
mymodel.day_shown = datetime.datetime.now() # Do any extra model stuff here
mymodel.save()
return redirect('home') Form #2
else:
form = MyForm(instance=mymodel)
return render(request, template_name, {'form': form, 'model': mymodel})
Only 1 nested if, but real code
Advanced Django Form Usage
gets much more complex
@pydanny / @maraujop
Custom business
goes here
20
60. Classic views.py for ModelForm
def my_model_edit(request, slug=slug, template_name='myapp/my_model_form.html'):
# I wouldn't call the variable model, because it's an instance of a model, it's confusing
mymodel = get_object_or_404(MyModel, slug=slug)
if request.method == 'POST':
form = MyForm(request, instance=mymodel)
if form.is_valid():
mymodel = form.save()
mymodel.day_shown = datetime.datetime.now() # Do any extra model stuff here
mymodel.save()
return redirect('home')
else:
form = MyForm(instance=mymodel)
return render(request, template_name, {'form': form, 'model': mymodel})
Advanced Django Form Usage
@pydanny / @maraujop
21
61. Classic views.py for ModelForm
def my_model_edit(request, slug=slug, template_name='myapp/my_model_form.html'):
# I wouldn't call the variable model, because it's an instance of a model, it's confusing
mymodel = get_object_or_404(MyModel, slug=slug)
if request.method == 'POST':
form = MyForm(request, instance=mymodel)
if form.is_valid():
mymodel = form.save()
mymodel.day_shown = datetime.datetime.now() # Do any extra model stuff here
mymodel.save()
return redirect('home')
else:
form = MyForm(instance=mymodel)
return render(request, template_name, {'form': form, 'model': mymodel})
• 12 lines of code
Advanced Django Form Usage
@pydanny / @maraujop
21
62. Classic views.py for ModelForm
def my_model_edit(request, slug=slug, template_name='myapp/my_model_form.html'):
# I wouldn't call the variable model, because it's an instance of a model, it's confusing
mymodel = get_object_or_404(MyModel, slug=slug)
if request.method == 'POST':
form = MyForm(request, instance=mymodel)
if form.is_valid():
mymodel = form.save()
mymodel.day_shown = datetime.datetime.now() # Do any extra model stuff here
mymodel.save()
return redirect('home')
else:
form = MyForm(instance=mymodel)
return render(request, template_name, {'form': form, 'model': mymodel})
• 12 lines of code
Advanced Django Form Usage
• Nested conditionals
@pydanny / @maraujop
21
63. Classic views.py for ModelForm
def my_model_edit(request, slug=slug, template_name='myapp/my_model_form.html'):
# I wouldn't call the variable model, because it's an instance of a model, it's confusing
mymodel = get_object_or_404(MyModel, slug=slug)
if request.method == 'POST':
form = MyForm(request, instance=mymodel)
if form.is_valid():
mymodel = form.save()
mymodel.day_shown = datetime.datetime.now() # Do any extra model stuff here
mymodel.save()
return redirect('home')
else:
form = MyForm(instance=mymodel)
return render(request, template_name, {'form': form, 'model': mymodel})
• 12 lines of code
Advanced Django Form Usage
• Nested conditionals
@pydanny / @maraujop
• What if we have to handle 3 different submit buttons?
21
64. Classic views.py for ModelForm
def my_model_edit(request, slug=slug, template_name='myapp/my_model_form.html'):
# I wouldn't call the variable model, because it's an instance of a model, it's confusing
mymodel = get_object_or_404(MyModel, slug=slug)
if request.method == 'POST':
form = MyForm(request, instance=mymodel)
if form.is_valid():
mymodel = form.save()
mymodel.day_shown = datetime.datetime.now() # Do any extra model stuff here
mymodel.save()
return redirect('home')
else:
form = MyForm(instance=mymodel)
return render(request, template_name, {'form': form, 'model': mymodel})
• 12 lines of code
Advanced Django Form Usage
• Nested conditionals
@pydanny / @maraujop
• What if we have to handle 3 different submit buttons?
• Watch out for edge case insanity!
21
66. easy views.py + ModelForm
def my_model_edit(request, slug=slug, template_name='myapp/
my_model_form.html'):
mymodel = get_object_or_404(MyModel, slug=slug)
form = MyModelForm(request.POST or None, instance=mymodel)
Single form
if form.is_valid():
mymodel = form.save()
mymodel.edited_at_djangocon = True
mymodel.save()
return redirect('home')
return render(request, template_name, {'form': form, 'mymodel': mymodel})
Advanced Django Form Usage
@pydanny / @maraujop
22
67. easy views.py + ModelForm
def my_model_edit(request, slug=slug, template_name='myapp/
my_model_form.html'):
mymodel = get_object_or_404(MyModel, slug=slug)
form = MyModelForm(request.POST or None, instance=mymodel)
Single form
if form.is_valid():
mymodel = form.save()
mymodel.edited_at_djangocon = True
mymodel.save()
return redirect('home')
return render(request, template_name, {'form': form, 'mymodel': mymodel})
Advanced Django Form Usage
Custom business
@pydanny / @maraujop
goes here
22
68. easy views.py + ModelForm
def my_model_edit(request, slug=slug, template_name='myapp/
my_model_form.html'):
mymodel = get_object_or_404(MyModel, slug=slug)
form = MyModelForm(request.POST or None, instance=mymodel)
Single form
if form.is_valid():
mymodel = form.save()
mymodel.edited_at_djangocon = True
mymodel.save()
return redirect('home')
return render(request, template_name, {'form': form, 'mymodel': mymodel})
If no request.POST,
then instantiated with None
Advanced Django Form Usage
Custom business
@pydanny / @maraujop
goes here So this will fail validation!
22
74. add views.py + ModelForm
def my_model_add(request, template_name='myapp/my_model_form.html'):
form = MyModelForm(request.POST or None)
if form.is_valid():
mymodel = form.save() No need for an
mymodel.added_at_djangocon = True
mymodel.save() instance here
return redirect('home')
return render(request,template_name,{'form': form,'mymodel':mymodel})
Advanced Django Form Usage
@pydanny / @maraujop
25
75. add views.py + ModelForm
def my_model_add(request, template_name='myapp/my_model_form.html'):
form = MyModelForm(request.POST or None)
if form.is_valid():
mymodel = form.save() No need for an
mymodel.added_at_djangocon = True
mymodel.save() instance here
return redirect('home')
return render(request,template_name,{'form': form,'mymodel':mymodel})
Advanced Django Form Usage
This creates the
@pydanny / @maraujop
model instance.
25
76. I can make it smaller!
def my_model_tiny_add(request,template_name='myapp/my_model_form.html'):
form = MyModelForm(request.POST or None)
if form.is_valid():
form.save() Not setting defaults here
return redirect('home')
return render(request,template_name,{'form':form,'mymodel':mymodel})
Advanced Django Form Usage
Good practice: Use model field defaults rather
@pydanny / @maraujop
than doing it in your views.
26
78. Advanced Django Form Usage
@pydanny / @maraujop
Please don’t manually
test your forms
28
79. Please don’t manually
test your forms
• This isn’t a testing talk but...
Advanced Django Form Usage
@pydanny / @maraujop
28
80. Please don’t manually
test your forms
• This isn’t a testing talk but...
• Forms are the number one thing to test
Advanced Django Form Usage
@pydanny / @maraujop
28
81. Please don’t manually
test your forms
• This isn’t a testing talk but...
• Forms are the number one thing to test
• Don’t skip on testing them
Advanced Django Form Usage
@pydanny / @maraujop
28
82. Please don’t manually
test your forms
• This isn’t a testing talk but...
• Forms are the number one thing to test
• Don’t skip on testing them
• Edge case insanity is the thing to fear
Advanced Django Form Usage
@pydanny / @maraujop
28
88. non-required to required
• Your model fields are non-required
• but you want the form fields to be required
Advanced Django Form Usage
@pydanny / @maraujop
31
89. A basic Django models.py
class MyModel(models.Model):
name = models.CharField(_('Name'), max_length=50, blank=True, null=True)
age = models.IntegerField(_('Age in years'), blank=True, null=True)
profession = models.CharField(_('Profession'),
max_length=100, blank=True, null=True)
bio = models.TextField(_('Bio'), blank=True, null=True)
Advanced Django Form Usage
@pydanny / @maraujop
32
90. Classic forms.py overload
class MyModelTooMuchTypingForm(forms.ModelForm):
""" I've done this and it sucks
hard to debug and too much duplication
"""
name = forms.CharField(_('Name'), max_length=50, required=True)
age = forms.IntegerField(_('Age in years'), required=True)
profession = forms.CharField(_('Profession'), required=True)
bio = forms.TextField(_('Bio'), required=True)
class Meta:
model = MyModel
Advanced Django Form Usage
@pydanny / @maraujop
33
91. Classic forms.py overload
class MyModelTooMuchTypingForm(forms.ModelForm):
""" I've done this and it sucks
hard to debug and too much duplication
"""
name = forms.CharField(_('Name'), max_length=50, required=True)
age = forms.IntegerField(_('Age in years'), required=True)
profession = forms.CharField(_('Profession'), required=True)
bio = forms.TextField(_('Bio'), required=True)
class Meta:
model = MyModel
Advanced Django Form Usage
@pydanny / @maraujop
class MyModel(models.Model):
name = models.CharField(_('Name'), max_length=50, blank=True, null=True)
age = models.IntegerField(_('Age in years'), blank=True, null=True)
profession = models.CharField(_('Profession'), max_length=100, blank=True, null=True)
bio = models.TextField(_('Bio'), blank=True, null=True)
33
92. Classic forms.py overload
class MyModelTooMuchTypingForm(forms.ModelForm):
""" I've done this and it sucks
hard to debug and too much duplication
"""
name = forms.CharField(_('Name'), max_length=50, required=True)
age = forms.IntegerField(_('Age in years'), required=True)
profession = forms.CharField(_('Profession'), required=True)
bio = forms.TextField(_('Bio'), required=True)
class Meta: Nearly duplicated code
model = MyModel
Advanced Django Form Usage
@pydanny / @maraujop
class MyModel(models.Model):
name = models.CharField(_('Name'), max_length=50, blank=True, null=True)
age = models.IntegerField(_('Age in years'), blank=True, null=True)
profession = models.CharField(_('Profession'), max_length=100, blank=True, null=True)
bio = models.TextField(_('Bio'), blank=True, null=True)
33
93. Classic forms.py overload
class MyModelTooMuchTypingForm(forms.ModelForm):
""" I've done this and it sucks
hard to debug and too much duplication
"""
name = forms.CharField(_('Name'), max_length=50, required=True)
age = forms.IntegerField(_('Age in years'), required=True)
profession = forms.CharField(_('Profession'), required=True)
bio = forms.TextField(_('Bio'), required=True)
class Meta: Nearly duplicated code
model = MyModel
Advanced Django Form Usage
@pydanny / @maraujop
class MyModel(models.Model):
name = models.CharField(_('Name'), max_length=50, blank=True, null=True)
age = models.IntegerField(_('Age in years'), blank=True, null=True)
profession = models.CharField(_('Profession'), max_length=100, blank=True, null=True)
bio = models.TextField(_('Bio'), blank=True, null=True)
33
94. Better forms.py overload
class MyModelForm(forms.ModelForm):
""" Much better and you are extending, not copy/pasting """
def __init__(self):
super(MyModelForm, self).__init__(*args, **kwargs)
self.fields['name'].required = True
self.fields['age'].required = True
self.fields['profession'].required = True
self.fields['profession'].help_text = _("Hi professor")
Advanced Django Form Usage
class Meta:
Fields are in a dict-like object
@pydanny / @maraujop
model = MyModel
34
95. Try it with inheritance!
class BaseEmailForm(forms.Form):
email = forms.EmailField(_('Email'))
confirm_email = forms.EmailField(_('Email 2'))
class ContactForm(BaseEmailForm):
message = forms.CharField(_('Message'))
def __init__(self):
super(ContactForm, self).__init__(*args, **kwargs)
self.fields['confirm_email'].label = _('Confirm your email')
self.fields['confirm_email'].description = _('We want to be absolutely
certain we have your correct email address.')
Advanced Django Form Usage
@pydanny / @maraujop
35
97. Dynamically adding fields
to a form
def my_view(request, template_name='myapp/my_model_form.html'):
form = MyModelForm(request.POST or None)
# Let's add a field on the go, needs to be done before validating it
form.fields['favorite_color'] = forms.ChoiceField(
label = "Which is your favorite color from these?",
choices = (('blue', 'blue'), ('red', 'red'), ('green', 'green')),
widget = forms.RadioSelect,
required = True,
)
if form.is_valid():
# Let's get user's favorite color,
# you can do whatever you want with it
favorite_color = form.cleaned_data['favorite_color']
Advanced Django Form Usage
form.save()
@pydanny / @maraujop
return redirect('home')
return render(request, template_name, {'form': form})
37
98. Dynamically adding fields
to a form
def my_view(request, template_name='myapp/my_model_form.html'): Form dictionary
form = MyModelForm(request.POST or None) of fields
# Let's add a field on the go, needs to be done before validating it
form.fields['favorite_color'] = forms.ChoiceField(
label = "Which is your favorite color from these?",
choices = (('blue', 'blue'), ('red', 'red'), ('green', 'green')),
widget = forms.RadioSelect,
required = True,
)
if form.is_valid():
# Let's get user's favorite color,
# you can do whatever you want with it
favorite_color = form.cleaned_data['favorite_color']
Advanced Django Form Usage
form.save()
@pydanny / @maraujop
return redirect('home')
return render(request, template_name, {'form': form})
37
99. Dynamically adding fields
to a form
def my_view(request, template_name='myapp/my_model_form.html'): Form dictionary
form = MyModelForm(request.POST or None) of fields
# Let's add a field on the go, needs to be done before validating it
form.fields['favorite_color'] = forms.ChoiceField(
label = "Which is your favorite color from these?",
choices = (('blue', 'blue'), ('red', 'red'), ('green', 'green')),
widget = forms.RadioSelect,
required = True,
)
Fields have to be added
before the form.is_valid
if form.is_valid():
# Let's get user's favorite color,
# you can do whatever you want with it
favorite_color = form.cleaned_data['favorite_color']
method is checked.
Advanced Django Form Usage
form.save()
@pydanny / @maraujop
return redirect('home')
return render(request, template_name, {'form': form})
37
100. Can’t we just pass in a
list of fields into a form
from a view?
101. Constructor overrides forms.py
class MyModelForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
extra = kwargs.pop('extra')
super(UserCreationForm, self).__init__(*args, **kwargs)
for i, question in enumerate(extra):
self.fields['custom_%s' % i] = forms.CharField(label=question)
def extra_fields(self): looping over
"""
Returns a tuple (question, answer)
‘extra’ iterable
Advanced Django Form Usage
"""
@pydanny / @maraujop
for name, value in self.cleaned_data.items():
if name.startswith('custom_'):
yield (self.fields[name].label, value)
39
102. Constructor overrides views.py
def my_view(request, template_name='myapp/my_model_form.html'):
form = MyModelForm(request.POST or None,
extra=["What's your pet's name?"])
Passing in a list
if form.is_valid():
# We can gather extra fields data doing
of form field
for (question, answer) in form.extra_fields(): titles
save_answer(request, question, answer)
form.save()
return redirect('home')
Advanced Django Form Usage
@pydanny / @maraujop
return render(request, template_name, {'form': form})
40
104. formsets.py
class ItemFormSet(BaseFormSet):
def __init__(self, numberItems, *args, **kwargs):
super(ItemFormSet, self).__init__(*args, **kwargs)
self.numberItems = numberItems
def clean(self):
# Don't bother validating the formset
# unless each form is valid on its own
if any(self.errors):
return
for form in self.forms:
Advanced Django Form Usage
if not form.cleaned_data['your_choice'] == 'mod_wsgi':
@pydanny / @maraujop
raise ValidationError(u'mod_wsgi is the way to go!')
42
105. formsets.py
class ItemFormSet(BaseFormSet):
def __init__(self, numberItems, *args, **kwargs):
super(ItemFormSet, self).__init__(*args, **kwargs)
self.numberItems = numberItems
def clean(self):
Forms must have
# Don't bother validating the formset
‘your_choice’ field that
# unless each form is valid on its own
if any(self.errors):
return only accepts “mod_wsgi”
for form in self.forms:
Advanced Django Form Usage
if not form.cleaned_data['your_choice'] == 'mod_wsgi':
@pydanny / @maraujop
raise ValidationError(u'mod_wsgi is the way to go!')
42
108. Things I want python
to describe in forms
• Different fieldsets within the same form
• Various buttons
• submit
• reset
Advanced Django Form Usage
@pydanny / @maraujop
45
110. Programmatic layouts
class ExampleForm(forms.Form):
def __init__(self, *args, **kwargs):
self.helper = FormHelper()
self.helper.layout = Layout(
Fieldset(
'first arg is the legend of the fieldset',
'like_website',
'favorite_number',
),
Fieldset(
'second arg is the legend of the fieldset',
'favorite_color',
'favorite_food',
Advanced Django Form Usage
)
@pydanny / @maraujop
ButtonHolder(
Submit('submit', 'Submit', css_class='button white')
)
)
return super(ExampleForm, 47
self).__init__(*args, **kwargs)
111. Programmatic layouts
from uni_form.helpers import FormHelper, Submit, Reset
from uni_form.helpers import Fieldset, ButtonHolder, Layout
class ExampleForm(forms.Form):
def __init__(self, *args, **kwargs):
self.helper = FormHelper()
self.helper.layout = Layout(
Fieldset(
'first arg is the legend of the fieldset',
'like_website',
'favorite_number',
),
Fieldset(
'second arg is the legend of the fieldset',
'favorite_color',
'favorite_food',
Advanced Django Form Usage
)
@pydanny / @maraujop
ButtonHolder(
Submit('submit', 'Submit', css_class='button white')
)
)
return super(ExampleForm, 47
self).__init__(*args, **kwargs)
112. Programmatic layouts
from uni_form.helpers import FormHelper, Submit, Reset
from uni_form.helpers import Fieldset, ButtonHolder, Layout
class ExampleForm(forms.Form): FormHelper
def __init__(self, *args, **kwargs):
self.helper = FormHelper()
self.helper.layout = Layout(
Fieldset(
'first arg is the legend of the fieldset',
'like_website',
'favorite_number',
),
Fieldset(
'second arg is the legend of the fieldset',
'favorite_color',
'favorite_food',
Advanced Django Form Usage
)
@pydanny / @maraujop
ButtonHolder(
Submit('submit', 'Submit', css_class='button white')
)
)
return super(ExampleForm, 47
self).__init__(*args, **kwargs)
113. Programmatic layouts
from uni_form.helpers import FormHelper, Submit, Reset
from uni_form.helpers import Fieldset, ButtonHolder, Layout
class ExampleForm(forms.Form): FormHelper
def __init__(self, *args, **kwargs):
self.helper = FormHelper()
self.helper.layout = Layout( Layout
Fieldset(
'first arg is the legend of the fieldset',
'like_website',
'favorite_number',
),
Fieldset(
'second arg is the legend of the fieldset',
'favorite_color',
'favorite_food',
Advanced Django Form Usage
)
@pydanny / @maraujop
ButtonHolder(
Submit('submit', 'Submit', css_class='button white')
)
)
return super(ExampleForm, 47
self).__init__(*args, **kwargs)
114. Programmatic layouts
from uni_form.helpers import FormHelper, Submit, Reset
from uni_form.helpers import Fieldset, ButtonHolder, Layout
class ExampleForm(forms.Form): FormHelper
def __init__(self, *args, **kwargs):
self.helper = FormHelper()
self.helper.layout = Layout( Layout
Fieldset(
'first arg is the legend of the fieldset',
Fieldset 'like_website',
'favorite_number',
),
Fieldset(
'second arg is the legend of the fieldset',
'favorite_color',
'favorite_food',
Advanced Django Form Usage
)
@pydanny / @maraujop
ButtonHolder(
Submit('submit', 'Submit', css_class='button white')
)
)
return super(ExampleForm, 47
self).__init__(*args, **kwargs)
115. Programmatic layouts
from uni_form.helpers import FormHelper, Submit, Reset
from uni_form.helpers import Fieldset, ButtonHolder, Layout
class ExampleForm(forms.Form): FormHelper
def __init__(self, *args, **kwargs):
self.helper = FormHelper()
self.helper.layout = Layout( Layout
Fieldset(
'first arg is the legend of the fieldset',
Fieldset 'like_website',
'favorite_number',
),
Fieldset(
'second arg is the legend of the fieldset',
'favorite_color', Button
'favorite_food',
Holder
Advanced Django Form Usage
)
@pydanny / @maraujop
ButtonHolder(
Submit('submit', 'Submit', css_class='button white')
)
)
return super(ExampleForm, 47
self).__init__(*args, **kwargs)
116. Programmatic layouts
from uni_form.helpers import FormHelper, Submit, Reset
from uni_form.helpers import Fieldset, ButtonHolder, Layout
class ExampleForm(forms.Form): FormHelper
def __init__(self, *args, **kwargs):
self.helper = FormHelper()
self.helper.layout = Layout( Layout
Fieldset(
'first arg is the legend of the fieldset',
Fieldset 'like_website',
'favorite_number',
),
Fieldset(
'second arg is the legend of the fieldset',
Button 'favorite_color', Button
'favorite_food',
Holder
Advanced Django Form Usage
)
@pydanny / @maraujop
ButtonHolder(
Submit('submit', 'Submit', css_class='button white')
)
)
return super(ExampleForm, 47
self).__init__(*args, **kwargs)
117. renders as divs
{% load uni_form_tags %}
{% uni_form my_form my_form.helper %}
Renders the HTML form
with buttons and everything
wrapped in a fieldset.
Advanced Django Form Usage
@pydanny / @maraujop
48
121. django-floppyforms
• by Bruno Renie @brutasse
• HTML5 Widgets
• Fully customizable templates
• Plays nice with django-uni-form
Advanced Django Form Usage
@pydanny / @maraujop
52
122. Easy to use!
import floppyforms as forms
class ExampleForm(forms.Form):
username = forms.CharField(
label='',
widget = forms.TextInput(
attrs={'placeholder': '@johndoe'},
),
)
• Django’s widget parameter attrs expects a dictionary
Advanced Django Form Usage
@pydanny / @maraujop
• Replaces the normal widgets with HTML5 ones
53
123. Customizable widgets
import floppyforms as forms
class OtherEmailInput(forms.EmailInput):
template_name = 'path/to/other_email.html'
forms.py
<input type="email"
name="{{ name }}"
id="{{ attrs.id }}"
Advanced Django Form Usage
placeholder="[email protected]"
@pydanny / @maraujop
{% if value %}value="{{ value }}"{% endif %}>
path/to/other_email.html
54
129. What we are getting in 1.4
• Form rendering will use templates instead
of HTML in Python
Advanced Django Form Usage
@pydanny / @maraujop
59
130. What we are getting in 1.4
• Form rendering will use templates instead
of HTML in Python
• Template based widgets
Advanced Django Form Usage
@pydanny / @maraujop
59
131. What we are getting in 1.4
• Form rendering will use templates instead
of HTML in Python
• Template based widgets
• Template based form layout
Advanced Django Form Usage
@pydanny / @maraujop
59
132. Advanced Django Form Usage
@pydanny / @maraujop
forms refactor and
django-uni-form
60
133. forms refactor and
django-uni-form
• forms refactor layout “lives” in templates
Advanced Django Form Usage
@pydanny / @maraujop
60
134. forms refactor and
django-uni-form
• forms refactor layout “lives” in templates
• django-uni-form layout “lives” in python
Advanced Django Form Usage
@pydanny / @maraujop
60
135. forms refactor and
django-uni-form
• forms refactor layout “lives” in templates
• django-uni-form layout “lives” in python
• Different approaches, same objective
Advanced Django Form Usage
@pydanny / @maraujop
60
137. The docs on custom fields
“Its only requirements are that it implement
a clean() method and that its __init__()
method accept the core arguments
mentioned above (required, label, initial,
widget, help_text).”
Advanced Django Form Usage
@pydanny / @maraujop
62
138. The docs on custom fields
“Its only requirements are that it implement
a clean() method and that its __init__()
method accept the core arguments
mentioned above (required, label, initial,
widget, help_text).”
Advanced Django Form Usage
The docs seem to be wrong
@pydanny / @maraujop
62
139. How it really works
You don’t need to implement “clean”
You do need to implement:
• required
• widget • error_messages
• label • show_hidden_initial
Advanced Django Form Usage
• help_text • validators
@pydanny / @maraujop
• initial • localize
63
140. How the heck then do I
actually add a custom
form field?!?
141. Advanced Django Form Usage
@pydanny / @maraujop
validation work?
How does form
65
142. fields.py
class AMarkField(forms.Field):
widget = TextInput
default_error_messages = {
'not_an_a': _(u'you can only input A here! damn!'),
}
def __init__(self, **kwargs):
super(AMarkField, self).__init__(**kwargs)
def to_python(self, value):
if value in validators.EMPTY_VALUES:
Only accepts upper
return None
case A as input
Advanced Django Form Usage
if value != 'A':
@pydanny / @maraujop
raise ValidationError(self.error_messages['not_an_a'])
return value
66
143. Not DRY
class MyModelForm(forms.ModelForm):
mark = CharField()
def clean_mark(self):
mark_value = self.cleaned_data['mark']
if mark_value is not None or mark_value.upper() != 'A':
raise ValidationError(_(u'Only input A here!'))
return mark_value
class ExampleForm(forms.Form):
mark = CharField()
def clean_mark(self):
Advanced Django Form Usage
mark_value = self.cleaned_data['mark']
@pydanny / @maraujop
if mark_value is not None or mark_value.upper() != 'A':
raise ValidationError(_(u'Only input A here!'))
return mark_value
67
145. The JSON field
class JSONField(forms.Field):
default_error_messages = {
'invalid': 'This is not valid JSON string'
}
def to_python(self, value):
if value in validators.EMPTY_VALUES:
return None
try:
json = simplejson.loads(value)
Advanced Django Form Usage
except ValueError:
@pydanny / @maraujop
raise ValidationError(self.error_messages['invalid'])
return json
69
146. I want a custom
widget that handles
multiple widgets
147. widgets.py
from django.forms.extras.widgets import MultiWidget
class AddressWidget(MultiWidget):
def __init__(self, attrs=None):
widgets = (TextInput, TextInput)
super(AddressWidget, self).__init__(widgets, attrs)
def decompress(self, value):
"""
If called, value is a string should return a list
"""
Advanced Django Form Usage
if value:
# parse stuff and return a list
@pydanny / @maraujop
return value.split()
return [None, None]
71
148. widgets.py
from django.forms.extras.widgets import MultiWidget
class AddressWidget(MultiWidget): Two TextInput
def __init__(self, attrs=None): widgets!!!
widgets = (TextInput, TextInput)
super(AddressWidget, self).__init__(widgets, attrs)
def decompress(self, value):
"""
If called, value is a string should return a list
"""
Advanced Django Form Usage
if value:
# parse stuff and return a list
@pydanny / @maraujop
return value.split()
return [None, None]
71
149. widgets.py
from django.forms.extras.widgets import MultiWidget
class AddressWidget(MultiWidget): Two TextInput
def __init__(self, attrs=None): widgets!!!
widgets = (TextInput, TextInput)
super(AddressWidget, self).__init__(widgets, attrs)
def decompress(self, value):
"""
If called, value is a string should return a list
"""
Advanced Django Form Usage
if value:
# parse stuff and return a list
@pydanny / @maraujop
return value.split()
Called when a form with
return [None, None] MultiWidget is passed initial
or instance values
71
150. fields.py
class AddressField(forms.Field):
self.widget = AddressWidget
def to_python(self, value):
# Already gets a Python list
return value
isinstance(["921 SW Sixth Avenue", "Portland"], list)
Advanced Django Form Usage
@pydanny / @maraujop
72
151. fields.py
class AddressField(forms.Field):
self.widget = AddressWidget
def to_python(self, value):
# Already gets a Python list
return value
isinstance(["921 SW Sixth Avenue", "Portland"], list)
class ExampleForm(object):
forms.CharField(widget=AddressWidget)
Advanced Django Form Usage
isinstance("921 SW Sixth Avenue, Portland", str)
@pydanny / @maraujop
72
154. MultiValue, MultiWidget Field
class AlternativeAddressField(forms.MultiValueField):
widget = AddressWidget
def __init__(self, *args, **kwargs):
fields = (forms.CharField(), forms.CharField())
super(AlternativeAddressField, self).__init__(fields,
*args, **kwargs)
def compress(self, data_list):
return data_list
• Clean does not work in the standard way
Advanced Django Form Usage
@pydanny / @maraujop
74
155. MultiValue, MultiWidget Field
class AlternativeAddressField(forms.MultiValueField):
widget = AddressWidget
def __init__(self, *args, **kwargs):
fields = (forms.CharField(), forms.CharField())
super(AlternativeAddressField, self).__init__(fields,
*args, **kwargs)
def compress(self, data_list):
return data_list
• Clean does not work in the standard way
• Every field validated with its corresponding widget value
Advanced Django Form Usage
@pydanny / @maraujop
74
156. MultiValue, MultiWidget Field
class AlternativeAddressField(forms.MultiValueField):
widget = AddressWidget
def __init__(self, *args, **kwargs):
fields = (forms.CharField(), forms.CharField())
super(AlternativeAddressField, self).__init__(fields,
*args, **kwargs)
def compress(self, data_list):
return data_list
• Clean does not work in the standard way
• Every field validated with its corresponding widget value
Advanced Django Form Usage
•
@pydanny / @maraujop
Beware! run_validator does run but validate is called
74
157. MultiValue, MultiWidget Field
class AlternativeAddressField(forms.MultiValueField):
widget = AddressWidget
def __init__(self, *args, **kwargs):
fields = (forms.CharField(), forms.CharField())
super(AlternativeAddressField, self).__init__(fields,
*args, **kwargs)
def compress(self, data_list):
return data_list
• Clean does not work in the standard way
• Every field validated with its corresponding widget value
Advanced Django Form Usage
•
@pydanny / @maraujop
Beware! run_validator does run but validate is called
Django Ticket #14184
74
160. Advanced Django Form Usage
@pydanny / @maraujop
Custom Widget Output
So Easy!
77
161. def render(self, name, value, attrs=None):
Custom Widget Output
# HTML to be added to the output
widget_labels = [
'<label for="id_%s">Address: </label>',
'<label for="id_%s">Number: </label>'
]
if self.is_localized:
for widget in self.widgets:
widget.is_localized = self.is_localized
# value is a list of values, each corresponding to a widget
So Easy!
# in self.widgets.
if not isinstance(value, list):
value = self.decompress(value)
output = []
final_attrs = self.build_attrs(attrs)
id_ = final_attrs.get('id', None)
for i, widget in enumerate(self.widgets):
try:
widget_value = value[i]
except IndexError:
widget_value = None
if id_:
Advanced Django Form Usage
final_attrs = dict(final_attrs, id='%s_%s' % (id_, i))
# Adding labels
@pydanny / @maraujop
output.append(widget_labels[i] % ('%s_%s' % (name, i)))
output.append(widget.render(name + '_%s' % i, widget_value, final_attrs))
return mark_safe(self.format_output(output))
77
162. def render(self, name, value, attrs=None):
Custom Widget Output
# HTML to be added to the output
widget_labels = [
'<label for="id_%s">Address: </label>',
'<label for="id_%s">Number: </label>'
]
if self.is_localized:
for widget in self.widgets:
widget.is_localized = self.is_localized
# value is a list of values, each corresponding to a widget
So Easy!
# in self.widgets.
if not isinstance(value, list):
value = self.decompress(value)
output = []
final_attrs = self.build_attrs(attrs)
id_ = final_attrs.get('id', None)
for i, widget in enumerate(self.widgets):
try:
widget_value = value[i]
except IndexError:
widget_value = None
if id_:
Advanced Django Form Usage
final_attrs = dict(final_attrs, id='%s_%s' % (id_, i))
# Adding labels
@pydanny / @maraujop
output.append(widget_labels[i] % ('%s_%s' % (name, i)))
output.append(widget.render(name + '_%s' % i, widget_value, final_attrs))
return mark_safe(self.format_output(output))
77
164. Problems with Custom
Widget Output
• Overring render means indepth knowledge
• Hard to do custom output with built-in widgets
• You can’t call super.render and customize easily
• Templates? Open Ticket #15667
Advanced Django Form Usage
@pydanny / @maraujop
79
166. Problems with Custom
Widget Output
• Oldest ticket in Django is related to forms
(#23)
• ComboField is broken
• Validators are thought to validate simple values
Advanced Django Form Usage
because of the way run_validators is coded
@pydanny / @maraujop
81
167. HTML5 tickets
• Ticket #16304
• Ticket #16630
• Just use django-floppyforms
Advanced Django Form Usage
@pydanny / @maraujop
82
168. Validators
• Imagine you have an input that get a list of emails seperated
by spaces
• Your widget returns: [“[email protected]”, “[email protected]”]
• You want to run validators on all of them
•
Advanced Django Form Usage
There is an EmailValidator
@pydanny / @maraujop
83
169. MultiValidator
class MultiValidator(object):
def __init__(self, validators):
self.validators = validators
def __call__(self, data_list):
errors = []
for value in data_list:
for validator in self.validators:
try:
validator(value)
except ValidationError, e:
Advanced Django Form Usage
if hasattr(e, 'code'):
errors.append("FiXED MESSAGE")
@pydanny / @maraujop
raise ValidationError(errors)
84
170. Amazing stuff
• Ticket #27 reported by Adrian Holovaty
• Single form field for multiple database fields
Advanced Django Form Usage
@pydanny / @maraujop
85
173. This has been
incredible
• We’ve just scratched the surface
Advanced Django Form Usage
@pydanny / @maraujop
87
174. This has been
incredible
• We’ve just scratched the surface
• Keep your code clean - or you’ll regret it
Advanced Django Form Usage
@pydanny / @maraujop
87
175. This has been
incredible
• We’ve just scratched the surface
• Keep your code clean - or you’ll regret it
• Miguel is awesome
Advanced Django Form Usage
@pydanny / @maraujop
87
177. This has been
incredible
• We want to see this and more in the
formal Django docs
Advanced Django Form Usage
@pydanny / @maraujop
88
178. This has been
incredible
• We want to see this and more in the
formal Django docs
• We’ve scratched our own itch
Advanced Django Form Usage
@pydanny / @maraujop
88
179. This has been
incredible
• We want to see this and more in the
formal Django docs
• We’ve scratched our own itch
• There are hidden things that need to see
the light of day
Advanced Django Form Usage
@pydanny / @maraujop
88
180. This has been
incredible
• We want to see this and more in the
formal Django docs
• We’ve scratched our own itch
• There are hidden things that need to see
the light of day
Advanced Django Form Usage
• Danny holds the DjangoCon talks record
@pydanny / @maraujop
88
#16: D\nIf you can reduce your line count from 10 to 2 and make it more obvious, that is good\nThis is why so many people prefer things like Python over Java\n
#17: D\nYou want to have shallow code with as little if statements as possible\nOtherwise you create lots of hard to test edge cases\n
#108: M\nBecause both DUF and DFF do things in a clean, non-magical way - they just work together. \nNamespaces and clean code beat smart hackery any day.\n
#121: M Of course you could do the same with a regular CharField using form validationclean_<fieldname> method, but...\n
#122: M - Duplicated code. So do a custom form field instead of duplicating code everywhere\nYes, you could solve this with form inheritance, but what if the inheritance chain gets too long?\n
#144: M * You can raise a ValidationError with a code. * You can raise a ValidationError with a list of messages. * You could raise a ValidationError on the first email that fails, but error will be less helpful. * Hard to customize, no error_messages, Do this in an upper layer, rewrite run_validators\n