Skip to main content

Posts

Showing posts with the label widget

Django adding custom widget to Django Admin

Sometimes you need to get out of standard behaviour of your Django admin. It means expanding its functionality with custom things. In our case we have a model that we want to add a custom html element. Button that must load something via AJAX from another place to be exact. We have a typical Django polls application for simplicity. Here is its structure: First of all we need to create a structure. So here comes our model: # models.py from django.db import models class Poll (models.Model): question = models.CharField(max_length= 200 ) pub_date = models.DateTimeField( 'date published' ) We have to have our django application admin configuration to display that model: # admin.py from django.contrib import admin from polls.models import Poll admin.site.register(Poll) It will look in Django admin like so: You can see polls available here in admin. You can do all the typical things with Polls model. Add/Delete/Edit... Using standard D...

Implementing a Multiple (Radio) Select + “Other” widget in Django

I have had a task to implement Radio Select field with "Other" choice field in a Django Model Form. Here is my implementation in case someone would benefit from it. The idea is to have it all stored to Django's CharField type of data and have a preselected set of fields. We have a model: # models.py class Entry (models.Model): SET_OF_CHOICES = ( ( 'choice1' , 'choice1' ), ( 'choice2' , 'choice2' ), ( 'choice3' , 'choice3' ), ( 'Other' , 'Other Please Specify' ), ) choice = models.CharField(_( "Selected your choice" ), max_length= 250 ) That makes it ready for the set of fields for for our form. We are overriding Model form default field for this type of data (CharField) by intentionally specifying field with the same name. # forms.py from django.forms import ModelForm, ChoiceField, RadioSelect from models import Entry ...