Login

All snippets written in Python

Snippet List

URLMan serializer field for Django Rest Framework (DRF)

This snippet shows how to add a `url` field to your API objects, which will then show up as an object in your JSON output. As parameters, you can specify: - `urls`: A list of strings that exist on your URLMan class - `attribute`: The name of the URLMan class on your model, defaults to `"urls"` - `full`: If the full URLs including schema and hostname should be supplied, defaults to `True`

  • django-rest-framework
  • urlman
Read More

Geoip middleware to restrict users to a set of allowed countries

This middleware uses Django's Geoip support (https://docs.djangoproject.com/fr/2.2/ref/contrib/gis/geoip2/), as well as axes's package helper to retrieve IP address (since Django's REMOTE_ADDR might be wrong when behind a reverse proxy). Ensure your geolite DB files are up to date (eg. with https://djangosnippets.org/snippets/10674/). The checker is optional, but ensures that security is not broken due to a misspelled/missing GEOIP_COUNTRY_WHITELIST.

  • middleware
  • ip
  • country
  • geoip
  • restriction
  • blocker
Read More

CBV to mix FormView and DetailView functionalities

Use this to display an object on a page AND be able to process a form on this page. This is just a copy of the [Django docs advice](https://docs.djangoproject.com/en/2.2/topics/class-based-views/mixins/#using-formmixin-with-detailview), but put as a reusable, standalone View.

  • view
  • form
  • cbv
  • detail
Read More

Strict Boolean Form Field

A form field for a Boolean that forces the user to make a choice from a list of choices. **Use Case** You have a Yes/No question the user must answer, but they may answer it yes or no. You don't want to supply a default because your need to force the user to actively select their answer. If they do not select an answer, the field should raise a validation error, like "This field is required". Normal BooleanField logic is based on a "checkbox", which, when "required" is required to be checked. This logic assumes that an empty value is the same as False -- in fact, there is no way for validators to distinguish between the empty value and False. Based on excellent suggestion from Peter DeGlopper: https://stackoverflow.com/a/56677670/1993525

  • form_field
Read More

updated django-mptt enabled FilteredSelectMultiple m2m widget, Django 1.11 compatible

Small fix to make https://www.djangosnippets.org/snippets/1779/ compatible with Django 1.11 To use this you'll also need the javascript from https://www.djangosnippets.org/snippets/1780/ I added an overridden optgroups method that can handle the additional tuple and a couple minor things I gathered while investigating for a fix (a default level_indicator of "+--" and changed paths for the JS files. All credits goes to @anentropic :-)

  • widget
  • mptt
Read More

StringField: CharField with no max_length for Postgres

Django's CharField requires a max_length, and TextField displays a multi- line widget, but in Postgres there's no reason to add an arbitrary max thanks to the `varlena` storage format. So this is a TextField that displays as a single line instead of a multiline TextArea.

  • orm
  • postgres
  • charfield
Read More

Calculating Maintainability Index for a whole project

With this command you can calculate the maintainability index for your whole project. In your settings you have to add a dictionary called `RADON_MI_SETTINGS`. It could be like this: ```python RADON_MI_SETTINGS = { 'paths': ['projectname'], 'exclude': 'projectname/some_app/some_file.py', 'ignore': 'migrations,tests', } ``` I had to add following packages: ``` radon==3.0.1 progress==1.5 plotly==3.7.0 GitPython==2.1.11 ``` Following commands are available: * `python manage.py calculate_maintainability_index` Only display the maintainability index of the project. The average from every file is build by using the logical lines of code per file. * `python manage.py calculate_maintainability_index --init` Go through every commit filtered by their commit_message (is set to “bump version” currently) and calculate the maintainability index for the whole project. This creates a file with the history. * `python manage.py calculate_maintainability_index --showhistory` Display the history of the maintainability_index in a graph in your browser. * `python manage.py calculate_maintainability_index --commit` Calculate the current maintainability_index and append it to your history. Commit your edited history file. * `python manage.py calculate_maintainability_index --fail` Calculate the current maintainability_index and raise an Error, if it is lower than the last entry in your history. Useful for use in an automated pipeline. Hints: * radon has a problem with large lists and dictionaries. If you have a file with a list or dictionary with more than 100 entries, you should exclude it. * To initialize your history you should change the commitmessage filter to something, that suits your needs. Created by Martin Becker at [Jonas und der Wolf GmbH](https://www.jonasundderwolf.de)

  • django
  • command
  • git
  • maintainability
Read More

Django nginx sendfile example

Use nginx sendfile (X-Accel-Redirect) function to serve files but pass traffic through django. Can be used to serve media files only to logged-in users.

  • django
  • media
  • sendfile
  • nginx
Read More

LoginRequiredMiddleware

### settings.py MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'utils.LoginRequiredMiddleware', ] LOGIN_REQUIRED_URLS = [ r'^panel/(.*)$' ] this will help any url under `panel/` require login.

  • middleware
  • authentication
  • login_required
Read More

2955 snippets posted so far.