Snippet List
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
The Mixin approach for applying permissions to CBV views suffers from 3 issues:
1. you need to read the code to see what permissions are being applied to a View
2. multiple bits of disparate code required to specify, e.g., a simple permission check
3. permissions set on a base class are overridden by permission set on sub-class, unless special care is taken
Here's a nice trick, using only built-in django machinery, apply a decorator intended to decorate a django view function to a CBV view. https://docs.djangoproject.com/en/1.11/topics/class-based-views/intro/#decorating-the-class
This approach works for any function decorators with arguments - simply wrap it in a function that takes the same arguments:
def my_cbv_decorator(*args **kwargs):
return method_decorator(a_view_function_decorator(*args, **kwargs), name='dispatch')
Use your new CBV decorator to decorate View sub-classes:
@my_cbv_decorator('some_parameter')
class MyCBView(django.views.generic.TemplateView):
pass # dispatch method for this view is now wrapped by a_view_function_decorator
Note: you can also pass decorator parameter directly to method_decorator, but wrapping it up like this makes the code read nicer.
- view
- decorator
- permissions
- cbv
**Use Case**: Specify the DB to run tests against. For example, use a legacy DB (un-managed), or a read-only DB where it is un-important to test creation, but important to test connection, trigger functions, and that models match schema.
**Usage**: in DATABASES setting, add:
'TEST' :{
'USEDB': 'your_test_DB_name_here',
}
and setting:
`TEST_RUNNER = 'your_app.test_runner.UseDBTestRunner' `
Advantages over --keepdb:
1. DB specific setting for multi-DB setup (e.g., default can use normal test DB, while legacy can use a pre-existing table).
2. Can specify any DB table, including the one used by the app (for non-destructive tests, or dev DB)
3. Allows testing against DB where creation or copying is prohibitive.
powderflask has posted 3 snippets.