Django community: RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
Configurer les représentations textuelles qui seront utilisées dans les ChoiceField des forms Django.
Longtemps que je n’avais pas posté de billets dans cette partie du blog. (Vous allez me dire longtemps que je n’ai pas posté de billet tout court, et vous auriez raison, mais ma bonne résolution de fin de vacances d’été est de changer cela). Mais donc, pour reprendre doucement dans la partie technique, je vais commencer par partager un truc que tout le monde connaît sûrement déjà. Sauf que perso, j’oublie à chaque fois que cette fonctionnalité de django existe et donc je galère pour la retrouver. Du coup je me dis qu’en l’écrivant je finirais par la mémoriser (et donc en fait j’écris plus pour moi qu’autre chose, je suis un vilain !:) ). Donc imaginons que vous avez un modèle. Truc assez classique. Ce modèle vous lui avez défini une représentation textuelle de base avec str . Sauf que vous avez plusieurs forms, donc certains ont des ChoiceFields utilisant ce modèle (Exemple un modèle User et vous avez un modèle Post où vous devez choisir le rédacteur du billet). Et manque de chance, vous avez besoin d’une représentation textuelle différentes de celle de base pour un de vos forms. Où même pire, vous avez besoin de plusieurs représentations … -
Understanding the User Experience: Why It’s Time to Get Comfortable with Talking About Emotions
When we discuss the “user experience,” or UX, as it is commonly known, words such as prototype, pain points, A/B testing, information architecture, wireframes, and site map get thrown around. However, it’s likely that neither you nor your users are familiar with these terms and concepts. The post Understanding the User Experience: Why It’s Time to Get Comfortable with Talking About Emotions appeared first on Distillery. -
Understanding the User Experience: Why It’s Time to Get Comfortable with Talking About Emotions
When we discuss the “user experience,” or UX, as it is commonly known, words such as prototype, pain points, A/B testing, information architecture, wireframes, and site map get thrown around. However, it’s likely that neither you nor your users are familiar with these terms and concepts. The post Understanding the User Experience: Why It’s Time to Get Comfortable with Talking About Emotions appeared first on Distillery. -
My Todoist Setup
What is this?Like a lot of others my first experience with todo managers was actually Wunderlist. At the time I was a college student and it was great for helping keep track of projects and other assignments. I never really dove to deep into GTD or any real kind of process then. It was just a bunch of tasks messily thrown in one project with dates attached. As college went on and I started freelancing I quickly realized I needed more help. That's when I started working on this system.Why Todoist?Eventually Microsoft bought Wunderlist. A truly sad day for Wunderlist fans, as Microsoft has a slight history of destroying things they buy. This gave me a good reason to find a new todo manager though. I looked at everything available (and still spend to much time looking at new ones now!), but finally settled on Todoist Premium.I love Todoist minimal interface, managers like Any.do and Asana just had to much clutter. Todoist also offers a really brilliant input interface as well. When adding tasks to Todoist you can add information (Projects, tags, due date, priority, etc) about the task just by typing, no need for clicking or special key bindings! … -
Leaving Webfaction
When I was young Five years ago (2013), when I made my first steps on Web Development, building localhost (dummy) projects I never thought of deployment or security issues. That's the beauty of working locally. You think, write it down, convert it to code, run it and done. Job's done. But, I wanted to make my work available to the public. What's the point of building a house, decorate it, paint it but with no guests at all? The point is to share. To evolve. I was building (still do) Django-based websites and when the time had come to upload it somewhere I did a research. Few players on the board for Python applications. My best bet back then (with no knowledge about web servers, security, redirects, static files handling etc) was to rely on a shared hosting service. I had rejected virtual private services (VPS) since I had absolutely no idea about how to setup a server with a Django application. Remember, it was 5 years ago, Django was at 1.6 release (if I recall correctly), I was just learning HTML, CSS, JS, Git etc and I had my app ready to deploy. I wrote down on a paper … -
Web Development Tutorial: PHP vs. Python & Django
In this tutorial, we'll compare PHP and Python (Django) for web development then we'll see how to create simple demo apps with PHP and Python (using Django one of the most popular frameworks for Python). PHP is a programming languages which has a sole purpose to create back-end web applications while Python is a general purpose programming language that can be used for web development and other fields such as data science and scientific calculations so our comparison will be between PHP and Python equipped with a web framework. The most popular web frameworks for Python are Django and Flask with Django being more popular than Flask. In order to compare PHP with Django we need to consider many factors such as: Are your a beginner or experienced developer? Are looking for quick insertion in the job market? etc. More experienced developers have more potential to quickly learn a new programming language than beginners Both PHP and Python are popular languages. They are both extremely popular among web developers and power most of the websites on the web today. Let's take a look at these three factors: Popularity of PHP and Python with Django for web development The learning curve … -
Changing Default Python 3 in Terminal for Mac OS
Sometimes Python gets upgraded... -
Pipenv Virtual Environments for Python
`Pipenv` is an **amazing** rep... -
Equivalents in Python and JavaScript. Part 4
In the last three parts of the series of articles about analogies in Python and JavaScript, we explored lots of interesting concepts like serializing to JSON, error handling, using regular expressions, string interpolation, generators, lambdas, and many more. This time we will delve into function arguments, creating classes, using class inheritance, and defining getters and setters of class properties. Function arguments Python is very flexible with argument handling for functions: you can set default values there, allow a flexible amount of positional or keyword arguments (*args and **kwargs). When you pass values to a function, you can define by name to which argument that value should be assigned. All that in a way is now possible in JavaScript too. Default values for function arguments in Python can be defined like this: from pprint import pprint def report(post_id, reason='not-relevant'): pprint({'post_id': post_id, 'reason': reason}) report(42) report(post_id=24, reason='spam') In JavaScript that can be achieved similarly: function report(post_id, reason='not-relevant') { console.log({post_id: post_id, reason: reason}); } report(42); report(post_id=24, reason='spam'); Positional arguments in Python can be accepted using the * operator like this: from pprint import pprint def add_tags(post_id, *tags): pprint({'post_id': post_id, 'tags': tags}) add_tags(42, 'python', 'javascript', 'django') In JavaScript positional arguments can be accepted using … -
Equivalents in Python and JavaScript. Part 4
In the last three parts of the series of articles about analogies in Python and JavaScript, we explored lots of interesting concepts like serializing to JSON, error handling, using regular expressions, string interpolation, generators, lambdas, and many more. This time we will delve into function arguments, creating classes, using class inheritance, and defining getters and setters of class properties. Function arguments Python is very flexible with argument handling for functions: you can set default values there, allow a flexible amount of positional or keyword arguments (*args and **kwargs). When you pass values to a function, you can define by name to which argument that value should be assigned. All that in a way is now possible in JavaScript too. Default values for function arguments in Python can be defined like this: from pprint import pprintdef report(post_id, reason='not-relevant'): pprint({'post_id': post_id, 'reason': reason}) report(42)report(post_id=24, reason='spam') In JavaScript that can be achieved similarly: function report(post_id, reason='not-relevant') { console.log({post_id: post_id, reason: reason});}report(42);report(post_id=24, reason='spam'); Positional arguments in Python can be accepted using the * operator like this: from pprint import pprintdef add_tags(post_id, *tags): pprint({'post_id': post_id, 'tags': tags}) add_tags(42, 'python', 'javascript', 'django') In JavaScript positional arguments can be accepted using the ... operator: function add_tags(post_id, ...tags) … -
Pipenv Tutorial for Django Developers
Pipenv is the new officially recommended packaging tool for Python which is similar to modern package managers like NPM (Node.js) or Composer (PHP). Pipenv solves common problems, most Python developers, encounter in the typical workflow using pip and virtualenv or venv. This tutorial will teach you to use Pipenv for managing Python dependencies and how to use the traditional existing tools, such as Pip and virtualenv, with Pipenv. Pipenv Tutorial for Django Developers: Pipenv vs. Pip vs. virtualenv vs. venv Pipenv vs. Pip vs. Virtualenv vs. Venv Multiple Project with Different Versions of Dependencies Pipenv vs Pip Dependency Resolver Getting Started with Pipenv with Django Example Create a Django Project Using Pipenv with Existing Projects Conclusion Pipenv vs. Pip vs. Virtualenv vs. Venv When working with Python projects you usually use a requirements.txt and Pip to install the packages automatically (pip install -r requirements.txt) on your development machine or later on your production machine. An example requirements.txt looks like: Django distribute dj-database-url psycopg2 wsgiref Each line contains a dependency that Pip will install, either globally or in a virtual environment if it's activated. We didn't specify the required versions which will install the latest versions of the wanted packages. Now, … -
Equivalents in Python and JavaScript. Part 3
This is the 3rd part of 4-article series about analogies in Python and JavaScript. In the previous parts we covered a large part of the traditional Python 2.7 and JavaScript based on the ECMAScript 5 standard. This time we will start looking into Python 3.6 and JavaScript based on the ECMAScript 6 standard. ECMAScript 6 standard is pretty new and supported only the newest versions of browsers. For older browsers you will need Babel to compile your next-generation JavaScript code to the cross-browser-compatible equivalents. It opens the door to so many interesting things to explore. We will start from string interpolation, unpacking lists, lambda functions, iterations without indexes, generators, and sets! Variables in strings The old and inefficient way to build strings with values from variables is this concatenation: name = 'World' value = 'Hello, ' + name + '!\nWelcome!' This can get very sparse and difficult to read. Also it is very easy to miss whitespaces in the sentence around variables. Since Python version 3.6 and JavaScript based on the ECMAScript 6 standard, you can use so called string interpolation. These are string templates which are filled in with values from variables. In Python they are also called f-string, … -
Equivalents in Python and JavaScript. Part 3
This is the 3rd part of 4-article series about analogies in Python and JavaScript. In the previous parts we covered a large part of the traditional Python 2.7 and JavaScript based on the ECMAScript 5 standard. This time we will start looking into Python 3.6 and JavaScript based on the ECMAScript 6 standard. ECMAScript 6 standard is pretty new and supported only the newest versions of browsers. For older browsers you will need Babel to compile your next-generation JavaScript code to the cross-browser-compatible equivalents. It opens the door to so many interesting things to explore. We will start from string interpolation, unpacking lists, lambda functions, iterations without indexes, generators, and sets! Variables in strings The old and inefficient way to build strings with values from variables is this concatenation: name = 'World'value = 'Hello, ' + name + '!\nWelcome!' This can get very sparse and difficult to read. Also it is very easy to miss whitespaces in the sentence around variables. Since Python version 3.6 and JavaScript based on the ECMAScript 6 standard, you can use so called string interpolation. These are string templates which are filled in with values from variables. In Python they are also called f-string, because … -
Plain text pypi description formatting: possible cause
Sometimes projects have a plaintext description on pypi.org. You see the restructuredtext formatting, but it isn't applied. See my own z3c.dependencychecker 2.4.2 for example. I use an editor with restructuredtext syntax highlighting. I double-checked everything. I used docutils. I used pypi's own readme_renderer to check it. Not a single error. But still, after some tries, the formatting was still off. Then a fellow contributor adjusted one of the setup() keywords in our setup.py: something might have to be a string (as in another package, with a perfectly-rendering description) instead of a list (as we had). Sadly, no luck. But it made me investigate the other keyword arguments. I noticed, next to long_description, the description. This is normally a one-line description. In our case, it was a multi-line string: long_description = u'\n\n'.join([ ... some files .... ]) description = """ Checks which imports are done and compares them to what's in setup.py and warns when discovering missing or unneeded dependencies. """ setup( name='z3c.dependencychecker', version=version, description=description, long_description=long_description, I changed it to a single line and yes, the next release worked fine on pypi! (Note that I also toyed a bit with encodings in that pull request, but I don't think that had … -
Equivalents in Python and JavaScript. Part 2
Last time we started a new series of articles about analogies in Python and JavaScript. We had a look at lists, arrays, dictionaries, objects, and strings, conditional assignments, and parsing integers. This time we will go through more interesting and more complex things like serializing dictionaries and lists to JSON, operations with regular expressions, as well as raising and catching errors. JSON When working with APIs it is very usual to serialize objects to JSON format and be able to parse JSON strings. In Python it is done with the json module like this: import json json_data = json.dumps(dictionary, indent=4) dictionary = json.loads(json_data) Here we'll indent the nested elements in the JSON string by 4 spaces. In JavaScript there is a JSON object that has methods to create and parse JSON strings: json_data = JSON.stringify(dictionary, null, 4); dictionary = JSON.parse(json_data); Splitting strings by regular expressions Regular expressions are multi-tool that once you master, you can accomplish lots of things. In the last article, we saw how one can join lists of strings into a single string. But how can you split a long string into lists of strings? What if the delimiter can be not a single character as the … -
Equivalents in Python and JavaScript. Part 2
Last time we started a new series of articles about analogies in Python and JavaScript. We had a look at lists, arrays, dictionaries, objects, and strings, conditional assignments, and parsing integers. This time we will go through more interesting and more complex things like serializing dictionaries and lists to JSON, operations with regular expressions, as well as raising and catching errors. JSON When working with APIs it is very usual to serialize objects to JSON format and be able to parse JSON strings. In Python it is done with the json module like this: import jsonjson_data = json.dumps(dictionary, indent=4)dictionary = json.loads(json_data) Here we'll indent the nested elements in the JSON string by 4 spaces. In JavaScript there is a JSON object that has methods to create and parse JSON strings: json_data = JSON.stringify(dictionary, null, 4);dictionary = JSON.parse(json_data); Splitting strings by regular expressions Regular expressions are multi-tool that once you master, you can accomplish lots of things. In the last article, we saw how one can join lists of strings into a single string. But how can you split a long string into lists of strings? What if the delimiter can be not a single character as the comma, but a … -
A few JavaScript Functions for Images and Files
> This post will be updated as... -
Equivalents in Python and JavaScript. Part 1
Although Python and JavaScript are quite different languages, there are some analogies which full stack Python developers should know when developing web projects. In this series of 4 parts, I will explore what is similar in each of those languages and what are the common ways to solve common problems. This is not meant to be a reference and I will skip the basics like primitive variable types, conditions, and loops. But I will dig into more complex structures and data operations using both, Python and JavaScript. Also, I will try to focus on the practical use cases. This series should be interesting for the developers of Django, Flask, or another Python framework who want to get a grasp of traditional and modern vanilla JavaScript. On the other hand, it will be useful for the front-enders who want to better understand how the backend is working and maybe even start their own Django website. Parsing integer We'll begin with integer parsing. In Python that's straightforward: number = int(text) But in JavaScript you have to explain what number system you expect: decimal, octal, hexadecimal, or binary: number = parseInt(text, 10); To use the "normal" decimal number system we are passing number … -
Equivalents in Python and JavaScript. Part 1
Although Python and JavaScript are quite different languages, there are some analogies which full stack Python developers should know when developing web projects. In this series of 4 parts, I will explore what is similar in each of those languages and what are the common ways to solve common problems. This is not meant to be a reference and I will skip the basics like primitive variable types, conditions, and loops. But I will dig into more complex structures and data operations using both, Python and JavaScript. Also, I will try to focus on the practical use cases. This series should be interesting for the developers of Django, Flask, or another Python framework who want to get a grasp of traditional and modern vanilla JavaScript. On the other hand, it will be useful for the front-enders who want to better understand how the backend is working and maybe even start their own Django website. Parsing integers We'll begin with integer parsing. In Python that's straightforward: number = int(text) But in JavaScript you have to explain what number system you expect: decimal, octal, hexadecimal, or binary: number = parseInt(text, 10); To use the "normal" decimal number system we are passing number … -
python django Automatic Testing part 4
Know the testing outputThe testing output of django here we will see that when we run our tests we will see number of test messages as the test runner prepares itself .Test runner is a component which orchestrates the execution of tests and provides the outcome to the user it may use a graphical interface a textual interface or return a special value to indicate the results of executing the tests If you wish you can control the level of detail of these messages with the verbosity option on the command line like you can run tests with more detail (higher verbosity) by passing in the -v flag some of the other options are-b,--buffer:the standard output and standard error streams are buffered during the test run output during a passing test is discarded output is echoed normally on test fail or error and is added to the failure messages-c,--catch: control c during the test run waits for the current test to end and then reports all the results so far A second control-c raises the normal KeyboardInterrupt exception-f --failfast: stop the test run on the first error or failure--locals: show local variables in tracebacksand you can get all the command … -
A good Django view function cache decorator for http.JsonResponse
I use this a lot. It has served me very well. The code: import hashlib import functools import markus # optional from django.core.cache import cache from django import http from django.utils.encoding import force_bytes, iri_to_uri metrics = markus.get_metrics(__name__) # optional def json_response_cache_page_decorator(seconds): """Cache only when there's a healthy http.JsonResponse response.""" def decorator(func): @functools.wraps(func) def inner(request, *args, **kwargs): cache_key = 'json_response_cache:{}:{}'.format( func.__name__, hashlib.md5(force_bytes(iri_to_uri( request.build_absolute_uri() ))).hexdigest() ) content = cache.get(cache_key) if content is not None: # metrics is optional metrics.incr( 'json_response_cache_hit', tags=['view:{}'.format(func.__name__)] ) return http.HttpResponse( content, content_type='application/json' ) response = func(request, *args, **kwargs) if ( isinstance(response, http.JsonResponse) and response.status_code in (200, 304) ): cache.set(cache_key, response.content, seconds) return response return inner return decorator To use it simply add to Django view functions that might return a http.JsonResponse. For example, something like this: @json_response_cache_page_decorator(60) def search(request): q = request.GET.get('q') if not q: return http.HttpResponseBadRequest('no q') results = search_database(q) return http.JsonResponse({ 'results': results, }) The reasons I use this instead of django.views.decorators.cache.cache_page() is because of a couple of reasons. cache_page generates cache keys that don't contain the view function name. cache_page tries to cache the whole http.HttpResponse instance which can't be serialized if you use the msgpack serializer. cache_page also sends Cache-Control headers which is not … -
Checking if you're pwned (with Django)
Back in March I announced the release of a couple security-related projects for Django, one that implements the Referrer-Policy header, and one that uses the Pwned Passwords database of Have I Been Pwned to check users’ passwords. Today I’ve bumped the version and rolled a new release of pwned-passwords-django; if you’re reading this, version 1.2 is on the Python Package Index, and is only a pip install away. And, of course, there’s full documentation available ... Read full entry -
Make ALL Your Django Forms Better
Website experiences need to be consistent as much as they need to be well thought out and aesthetically pleasing. Structure, visual design, user interactions, and accessibility concerns are among many considerations that go into building quality websites. While achieving consistency of experience and implementation is an essential goal of web development, efficiency of execution is also very important. An efficient workflow means this consistent experience doesn’t require redoing work across the site. This post is about efficient consistency when building forms across your site. Django helps you build forms, but one size doesn’t fit all. It can render your forms on its own, or you can take more control of the form markup in your HTML. When Django renders your forms, you adhere to its defaults and assumptions. When those don’t match your site’s designs or other requirements, you have to do it yourself. But you can squeeze more flexibility out of Django’s own form rendering. This lets you match your form styles and implementations site-wide without losing the valuable tools Django has out-of-the-box to make form rendering easier. Why change what Django does? Maybe you’ve always been fine using the forms exactly as Django renders them for you. Or, … -
Make ALL Your Django Forms Better
Website experiences need to be consistent as much as they need to be well thought out and aesthetically pleasing. Structure, visual design, user interactions, and accessibility concerns are among many considerations that go into building quality websites. While achieving consistency of experience and implementation is an essential goal of web development, efficiency of execution is also very important. An efficient workflow means this consistent experience doesn’t require redoing work across the site. This post is about efficient consistency when building forms across your site. Django helps you build forms, but one size doesn’t fit all. It can render your forms on its own, or you can take more control of the form markup in your HTML. When Django renders your forms, you adhere to its defaults and assumptions. When those don’t match your site’s designs or other requirements, you have to do it yourself. But you can squeeze more flexibility out of Django’s own form rendering. This lets you match your form styles and implementations site-wide without losing the valuable tools Django has out-of-the-box to make form rendering easier. Why change what Django does? Maybe you’ve always been fine using the forms exactly as Django renders them for you. Or, … -
python django Automated testing part 3(please read my previous post ))
Finding data form production database when running tests if the code attempts to access the database when its modules are compiled this will occur before the test database is set up with potentially unexpected results For example if we have a database query in the module level code and a real database exists . then the production data could pollute the tests it is a bad idea to have such import time database queries in your codeso we should have to rewrite the code so that it doesn't do this. This also applies to customized implementation of ready()Order of Test executionDjango test runner reorders tests asAll the TestCase subclasses are run firstThen all other Django-based tests (test case based on SimpleTestCase,including TransactionTestCase) are run with no particular ordering guaranteed nor enforced among themthen any other unittest.TestCase test (including doctests) which may alter the database without restoring it to its orginal state are runNote: The new ordering of tests may reveal unexpected dependencies on test case ordering this is the case with doctests that relied on state left in the database by a given TransactionTestCase test they must be updated to be able to run independentlyTo ensure your tests are …