@@ -11,59 +11,44 @@ The package can be installed via:
1111
1212## Usage
1313
14- There are a few ways of setting a widget for a form field:
15-
16- ### via ` forms.py `
14+ For the most common usage, first create a model:
1715
1816``` python
19- from django import forms
20- from charsleft_widget.widgets import CharsLeftInput
21-
22- class ExampleForm (forms .Form ):
23- name = forms.CharField(widget = CharsLeftInput())
17+ from django.db import models
18+
19+ class Song (models .Model ):
20+ title = models.CharField(max_length = 100 )
2421```
2522
26- or
23+ then create a custom model form that uses the custom widget class. ** Note that it's important
24+ to include the ` maxlength ` attribute manually when making use of the widget, as it will not
25+ be pulled in automatically from your model field.**
2726
2827``` python
2928from django import forms
3029from charsleft_widget.widgets import CharsLeftInput
31-
32- class ExampleForm (forms .Form ):
33- name = forms.CharField()
3430
35- def __init__ (self , * args , * kwargs ):
36- super (ExampleForm, self ).__init__ (* args, ** kwargs)
37- self .fields[' name' ].widget = CharsLeftInput
38- ```
31+ from .models import Song
3932
40- ### via ` admin.py `
33+ class SongForm (forms .ModelForm ):
34+ name = forms.CharField(widget = CharsLeftInput(attrs = {' maxlength' : 100 }))
4135
42- ``` python
43- from django.contrib import admin
44- from charsleft_widget.widgets import CharsLeftInput, MediaMixin
45-
46- # The MediaMixin is what loads the css and javascript only one time per admin page
47- class ExampleAdmin (MediaMixin , admin .ModelAdmin ):
48- # Use widget on all instances of this form field
49- formfield_overrides = {
50- models.TextField: {' widget' : CharsLeftInput()},
51- }
36+ class Meta :
37+ model = Song
38+ fields = " __all__"
5239```
5340
54- or
41+ If you are using it in the Django admin, import your custom model form in your ` ModelAdmin ` :
42+
5543
5644``` python
5745from django.contrib import admin
58- from charsleft_widget.widgets import CharsLeftInput, MediaMixin
59-
60- # The MediaMixin is what loads the css and javascript only one time per admin page
61- class MyModelAdmin (MediaMixin , admin .ModelAdmin ):
62- pass
63-
64- # Use widget on particular instances of the form field
65- def formfield_for_dbfield (self , db_field , ** kwargs ):
66- if db_field.name is ' my_field_name' :
67- kwargs[' widget' ] = CharsLeftInput(attrs = {' size' :' add normal attrs here, like field size numbers' })
68- return super (ContentObjectAdmin,self ).formfield_for_dbfield(db_field,** kwargs)
69- ```
46+
47+ from .models import Song
48+ from .forms import SongForm
49+
50+
51+ @admin.register (Song)
52+ class SongAdmin (admin .ModelAdmin ):
53+ form = SongForm
54+ ```
0 commit comments