Changes between Initial Version and Version 1 of CustomFormFields

02/20/2006 03:39:20 AM (13 years ago)

Created the page


  • CustomFormFields

    v1 v1  
     1= Custom Form Fields =
     3This page will document my efforts to create a custom form field for my application.  Hopefully someone will find it useful, contribute, correct my mistakes or post some pointers.
     5==  The Goal ==
     7As I'd like my database driven app to be driven by a database and not a flat file I made sure that my model was properly normalised.  One model deals with recording information about applications and services and so needs to deal with ports numbers and IP protocols.  Since many ports could have many applications I've got a model like this:
     11class Port(meta.model):
     12    number = meta.IntegerField()
     13    protocol = meta.CharField(maxlength=4)
     15class Application(meta.model):
     16    name = meta.CharField(maxlength=50)
     17    version = meta.IntegerField()
     18    ports = meta.ManyToManyField(Port)
     22The 'ports' table is prepopulated with all possible combinations of number+protocol and as such weighs in at around 130000 rows.  Each request for an add or change manipulator therefore takes quite a while (as all the rows are read in) and is not very usable.
     24What I'd like is something similar to the raw admin id but without having to enter ids.  I'd like the user to be able to enter values like so: 80:tcp, 443:tcp, icmp.
     26Now what I could do is just add a text box to the form, process it in the view and then populate the M2M field myself but that feels like cheating.  Plus there's a few other models where something like this but with more functionality would prove useful.
     28== Tagging ==
     30A quick Google made me think that someone had beaten me to it.  I found this post: [ Django and M2M tables] which points to an example of adding tagging to a model.  This seems to provide the answer but it doesn't quite fit my needs, mainly because the whole choices list is still being pulled in.
     32== Findings ==
     34After much messing about I've found that things are a lot simpler than first appeared.  In order to validate the input I've subclassed TextField and added a new validation method to its validator list.  I created a new render method which simply turns the list into something more presentable.  I then created a new convert_post_data method which takes '80:tcp, 443:tcp' or whatever and turns it into a list of ids from the joined table.
     36This now appears to work correctly in my application but fails in the admin view.  When I know more I'll update this page.
Back to Top