get the first day and the last day of the current quarter
current_quarter = (current_date.month - 1) / 3 + 1
end_quarter = (end_date.month - 1) / 3 + 1
self.valid_date = datetime.datetime(year=current_date.year, month=int(3 * current_quarter - 2), day=1)
self.valid_end = datetime.datetime(year=end_date.year, month=int(3 * end_quarter + 1), day=1) -\
datetime.timedelta(days=1)
Import Export Widget
For anyone else who stumbled across this looking for an easy way to import/export your choice display values, I made a couple tweaks to @int-ua’s code above and it’s working well for me:
from import_export.widgets import Widget
class ChoicesWidget(Widget):
"""
Widget that uses choice display values in place of database values
"""
def __init__(self, choices, *args, **kwargs):
"""
Creates a self.choices dict with a key, display value, and value,
db value, e.g. {'Chocolate': 'CHOC'}
"""
self.choices = {str(value): str(key) for (key, value) in choices}
def clean(self, value, row=None):
"""Returns the db value given the display value"""
return self.choices.get(value, value) if value else None
def render(self, value):
"""Returns the display value given the db value"""
for display_val, db_val in self.choices.items():
if db_val == value:
return display_val
return ''
To use the widget, be sure to pass in the choices from your model:
from import_export import resources, fields
class MyModelResource(resources.ModelResource):
my_choice_field = fields.Field(
widget=ChoicesWidget(MyModel.MY_CHOICE_FIELD_CHOICES),
column_name='my_choice_field',
attribute='my_choice_field',
)
class Meta:
...
create fake object to substitute request
request = FakeRequest()
request.user = import_job.created_by
args = ()
kwargs = {'request': request}
resource = resource_class(*args, **kwargs)
write string to file - ContentFile
context = Context({'data': MyModel.objects.all()})
rendered = render_to_string('mytemplate.html', context)
cf = ContentFile(rendered.encode('ascii'))
set default value to django foreign key
class Country(models.Model):
sigla = models.CharField(max_length=5, unique=True)
def __unicode__(self):
return u'%s' % self.sigla
class City(models.Model):
nome = models.CharField(max_length=64, unique=True)
nation = models.ForeignKey(Country, to_field='sigla', default='IT')
Convert floating point number to a certain precision, and then copy to string
Python 3.6
Just to make it clear, you can use f-string formatting. This has almost the same syntax as the format method, but make it a bit nicer.
Example:
print(f'{numvar:.9f}')
How to show download link for attached file in FileField in Django Admin
If you have a model “Case” for example, you could add a method to your class which “creates” the link to the uploaded file :
class Case(models.Model)
...
file = models.FileField(upload_to=FOLDER_FILES_PATH)
...
def file_link(self):
if self.file:
return "<a href='%s'>download</a>" % (self.file.url,)
else:
return "No attachment"
file_link.allow_tags = True
Understanding ManyToMany fields in Django with a through model
Yes, using an explicit through table basically eliminates the need for a ManyToManyField.
The only real advantage to having it is if you’d find the related manager convenient. That is, this:
group.members.all() # Persons in the group
looks nicer than this:
Person.objects.filter(membership_set__group=group) # Persons in the group
In practice, I think the main reason for having both is that often people start with a plain ManyToManyField; realize they need some additional data and add a through table; and then end up with both due to code that uses both managers.
Xadmin extensions with celery and hstore
https://github.com/jneight/django-xadmin-extras
differentiate null=True, blank=True in django
null=True sets NULL (versus NOT NULL) on the column in your DB. Blank values for Django field types such as DateTimeField or ForeignKey will be stored as NULL in the DB.
blank=True determines whether the field will be required in forms. This includes the admin and your own custom forms. If blank=True then the field will not be required, whereas if it’s False the field cannot be blank.
The combo of the two is so frequent because typically if you’re going to allow a field to be blank in your form, you’re going to also need your database to allow NULL values for that field. The exception is CharFields and TextFields, which in Django are never saved as NULL. Blank values are stored in the DB as an empty string (‘’).
A few examples:
models.DateTimeField(blank=True) # raises IntegrityError if blank
models.DateTimeField(null=True) # NULL allowed, but must be filled out in a form
Obviously those two options don’t make logical sense to use (though, there might be a use case for null=True, blank=False if you want a field to always be required in forms, but optional when dealing with an object through something like the shell.)
models.CharField(blank=True) # No problem, blank is stored as ''
models.CharField(null=True) # NULL allowed, but will never be set as NULL
CHAR and TEXT types are never saved as NULL by Django, so null=True is unnecessary. However, you can manually set one of these fields to None to force set it as NULL. If you have a scenario where that might be necessary, you should still include null=True.
Reverse and return the absolute path
If you want to use it with reverse() you can do this : ```python
request.build_absolute_uri(reverse(‘view_name’, args=(obj.pk, )))
### Django combine list (queryset)
```python
mandant = user.mandant
all_course_mandant = MandantCourse.objects.filter(mandant=mandant, start_date__lte=current_date,
end_date__gte=current_date).values_list('course', flat=True)
all_course_id = list(all_course_id) + list(set(all_course_mandant) - set(all_course_id))
all_course = Course.objects.filter(id__in=all_course_id).order_by("-click_nums")