Is there any good articles that explain custom form fields in django, not custom model fields? I couldn't find any through google.
Look at the existing Django fields (in django/db/models/fields/__init__.py ) for inspiration. Try to find a field that's similar to what you want and extend it a little bit, instead of creating an entirely new field from scratch. Put a __str__() method on the class you're wrapping up as a field.
To answer your question, with the new migration introduced in Django 1.7, in order to add a new field to a model you can simply add that field to your model and initialize migrations with ./manage.py makemigrations and then run ./manage.py migrate and the new field will be added to your DB.
Let's try to use required via Django Web application we created, visit http://localhost:8000/ and try to input the value based on option or validation applied on the Field. Hit submit. Hence Field is accepting the form even without any data in the geeks_field. This makes required=False implemented successfully.
Form fields are easy to customize:
class UpperCaseField(forms.CharField): def clean(self, value) try: return value.upper() except: raise ValidationError
basically you just create a class that inherits from the field that most resembles what you want, then rewrite the clean() method so that it returns the value you want. Here is another example:
class MyObjectField(forms.ModelChoiceField): # in this case, 'value' is a string representing # the primary key of a MyObject def clean(self, value): try: return MyObject.objects.get(pk=value) except: raise ValidationError
custom widgets on the other hand, are a little more useful, but a little more hard to do because there are a few more methods that need to be written so that they work smoothly.
As always with open-source code, you'll learn a great deal by reading the source itself. See the django.forms.fields
module to see how all the different form fields are defined - most of them are subclasses of others already, so you can just replicate that and change what you need.
It's not a tutorial, but django's docs talks about this a little:
If the built-in Field classes don't meet your needs, you can easily create custom Field classes. To do this, just create a subclass of django.forms.Field. Its only requirements are that it implement a clean() method and that its
__init__()
method accept the core arguments mentioned above (required, label, initial, widget, help_text).
You can read about the clean method and see an example at the django docs. Again, not a tutorial, but useful.
I find I am learning a lot by reading the code in some of the the django app projects that are available, such as django-extensions, which override the form fields and are good learning tools (for me, at least). This can help get you started.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With