Django query filter with variable column

Almost there.. members.filter(**{‘string__contains’: ‘search_string’}) To understand what it’s doing, google around : ) Understanding kwargs in Python ** expands dictionary key/value pairs to keyword argument – value pairs. To adapt your example to the solution: variable_column = ‘name’ search_type=”contains” filter = variable_column + ‘__’ + search_type info=members.filter(**{ filter: search_string })

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

Creating Custom Filters for list_filter in Django Admin

You can indeed add custom filters to admin filters by extending SimpleListFilter. For instance, if you want to add a continent filter for ‘Africa’ to the country admin filter used above, you can do the following: In admin.py: from django.contrib.admin import SimpleListFilter class CountryFilter(SimpleListFilter): title=”country” # or use _(‘country’) for translated title parameter_name=”country” def lookups(self, … Read more

How to get the current url name using Django?

I don’t know how long this feature has been part of Django but as the following article shows, it can be achieved as follows in the view: from django.core.urlresolvers import resolve current_url = resolve(request.path_info).url_name If you need that in every template, writing a template request can be appropriate. Edit: APPLYING NEW DJANGO UPDATE Following the … 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

Pass request context to serializer from Viewset in Django Rest Framework

GenericViewSet has the get_serializer_context method which will let you update context: class MyModelViewSet(ModelViewSet): queryset = MyModel.objects.all() permission_classes = [DjangoModelPermissions] serializer_class = MyModelSerializer def get_serializer_context(self): context = super().get_serializer_context() context.update({“request”: self.request}) return context For Python 2.7, use context = super(MyModelViewSet, self).get_serializer_context()

tech