Django’s ModelForm unique_together validation

I solved this same problem by overriding the validate_unique() method of the ModelForm: def validate_unique(self): exclude = self._get_validation_exclusions() exclude.remove(‘problem’) # allow checking against the missing attribute try: self.instance.validate_unique(exclude=exclude) except ValidationError, e: self._update_errors(e.message_dict) Now I just always make sure that the attribute not provided on the form is still available, e.g. instance=Solution(problem=some_problem) on the initializer.

How do I display the value of a Django form field in a template?

This was a feature request that got fixed in Django 1.3. Here’s the bug: https://code.djangoproject.com/ticket/10427 Basically, if you’re running something after 1.3, in Django templates you can do: {{ form.field.value|default_if_none:”” }} Or in Jinja2: {{ form.field.value()|default(“”) }} Note that field.value() is a method, but in Django templates ()‘s are omitted, while in Jinja2 method calls … Read more

Simple Log to File example for django 1.3+

I truly love this so much here is your working example! Seriously this is awesome! Start by putting this in your settings.py LOGGING = { ‘version’: 1, ‘disable_existing_loggers’: True, ‘formatters’: { ‘standard’: { ‘format’ : “[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s”, ‘datefmt’ : “%d/%b/%Y %H:%M:%S” }, }, ‘handlers’: { ‘null’: { ‘level’:’DEBUG’, ‘class’:’django.utils.log.NullHandler’, }, ‘logfile’: { ‘level’:’DEBUG’, … Read more

Django – Static file not found

I confused STATIC_ROOT and STATICFILES_DIRS Actually I was not really understanding the utility of STATIC_ROOT. I thought that it was the directory on which I have to put my common files. This directory is used for the production, this is the directory on which static files will be put (collected) by collectstatic. STATICFILES_DIRS is the … Read more

Get type of Django form widget from within template

Making a template tag might work? Something like field.field.widget|widget_type Edit from Oli: Good point! I just wrote a filter: from django import template register = template.Library() @register.filter(‘klass’) def klass(ob): return ob.__class__.__name__ And now {{ object|klass }} renders correctly. Now I’ve just got to figure out how to use that inside a template’s if statement. Edit … Read more

conversion of datetime Field to string in django queryset.values_list()

https://docs.djangoproject.com/en/2.2/ref/models/fields/#datetimefield A date and time, represented in Python by a datetime.datetime instance. You can get a string representation of a DateTimeField casting it directly: str(obj) # obj = qs[0][0] ? or qs[0][1] ? You’ll get result like this (in this example I use datetime.datetime.now() since a DateTimeField is represented by datetime.datetime is the same behavior): … Read more