-
Notifications
You must be signed in to change notification settings - Fork 23
Add choice fields #15
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
lieryan
wants to merge
9
commits into
CodeYellowBV:master
Choose a base branch
from
lieryan:add-choice-fields
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
6a9dc40
Remove unused import
ed62da9
Add migration serializer for relativedelta
21625c6
Add migration to testproject
35aaa64
Add IntervalWithChoice to testproject
cde1bfb
Add admin for testproject.IntervalWithChoice
065f77d
Implement form fields for RelativeDeltaField(choices)
b6aa64a
Use deconstructible instead of MigrationWriter.register_serializer()
154ad09
Document RelativeDeltaChoiceField and RelativeDeltaField(choices)
c35a188
Automatically choose between register_serializer() or deconstructible()
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,24 @@ | ||
import relativedeltafield | ||
from dateutil.relativedelta import relativedelta | ||
from django import forms | ||
|
||
|
||
class RelativeDeltaChoiceField(forms.TypedChoiceField): | ||
def _set_choices(self, value): | ||
value = [(self.prepare_value(val), label) for val, label in value] | ||
super()._set_choices(value) | ||
choices = property(forms.TypedChoiceField._get_choices, _set_choices) | ||
|
||
def to_python(self, value): | ||
if value in self.empty_values: | ||
return None | ||
return relativedeltafield.parse_relativedelta(value) | ||
|
||
def prepare_value(self, value): | ||
if isinstance(value, relativedelta): | ||
return relativedeltafield.format_relativedelta(value) | ||
return super().prepare_value(value) | ||
|
||
def valid_value(self, value): | ||
value = self.prepare_value(value) | ||
return super().valid_value(value) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,72 @@ | ||
from dateutil.relativedelta import relativedelta | ||
from django import forms | ||
from django.test import TestCase | ||
from testapp.models import Interval, IntervalWithChoice | ||
|
||
IntervalForm = forms.modelform_factory(model=IntervalWithChoice, fields=forms.ALL_FIELDS) | ||
|
||
|
||
class RelativeDeltaFormFieldTest(TestCase): | ||
def setUp(self): | ||
self.obj = Interval.objects.create(value=relativedelta(years=1)) | ||
|
||
def test_unbound_form_rendering(self): | ||
form = IntervalForm() | ||
|
||
self.assertHTMLEqual( | ||
str(form['value']), | ||
''' | ||
<select name="value" id="id_value"> | ||
<option value="" selected>---------</option> | ||
<option value="P1M">1 month</option> | ||
<option value="P3M">3 months</option> | ||
<option value="P6M">6 months</option> | ||
</select> | ||
''' | ||
) | ||
|
||
def test_bound_form_rendering(self): | ||
self.obj = Interval.objects.create(value=relativedelta(months=3)) | ||
form = IntervalForm(instance=self.obj) | ||
|
||
self.assertHTMLEqual( | ||
str(form['value']), | ||
''' | ||
<select name="value" id="id_value"> | ||
<option value="">---------</option> | ||
<option value="P1M">1 month</option> | ||
<option selected value="P3M">3 months</option> | ||
<option value="P6M">6 months</option> | ||
</select> | ||
''' | ||
) | ||
|
||
def test_form_submission_string_choice(self): | ||
self.obj = IntervalWithChoice.objects.create(value=relativedelta(months=1)) | ||
data = {'value': 'P3M'} | ||
form = IntervalForm(data, instance=self.obj) | ||
self.assertTrue(form.is_valid()) | ||
form.save() | ||
|
||
self.obj.refresh_from_db() | ||
self.assertEqual(self.obj.value, relativedelta(months=3)) | ||
|
||
def test_form_submission_relativedelta_choice(self): | ||
self.obj = IntervalWithChoice.objects.create(value=relativedelta(months=1)) | ||
data = {'value': 'P6M'} | ||
form = IntervalForm(data, instance=self.obj) | ||
self.assertTrue(form.is_valid()) | ||
form.save() | ||
|
||
self.obj.refresh_from_db() | ||
self.assertEqual(self.obj.value, relativedelta(months=6)) | ||
|
||
def test_form_submission_empty(self): | ||
self.obj = IntervalWithChoice.objects.create(value=relativedelta(months=1)) | ||
data = {'value': ''} | ||
form = IntervalForm(data, instance=self.obj) | ||
self.assertTrue(form.is_valid()) | ||
form.save() | ||
|
||
self.obj.refresh_from_db() | ||
self.assertIsNone(self.obj.value) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,22 @@ | ||
# Generated by Django 3.1.1 on 2020-09-28 19:01 | ||
|
||
import relativedeltafield | ||
from django.db import migrations, models | ||
|
||
|
||
class Migration(migrations.Migration): | ||
|
||
initial = True | ||
|
||
dependencies = [ | ||
] | ||
|
||
operations = [ | ||
migrations.CreateModel( | ||
name='Interval', | ||
fields=[ | ||
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), | ||
('value', relativedeltafield.RelativeDeltaField(blank=True, null=True)), | ||
], | ||
), | ||
] |
22 changes: 22 additions & 0 deletions
22
tests/testproject/testapp/migrations/0002_intervalwithchoice.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,22 @@ | ||
# Generated by Django 3.1.1 on 2020-09-28 22:05 | ||
|
||
from dateutil.relativedelta import relativedelta | ||
from django.db import migrations, models | ||
import relativedeltafield | ||
|
||
|
||
class Migration(migrations.Migration): | ||
|
||
dependencies = [ | ||
('testapp', '0001_initial'), | ||
] | ||
|
||
operations = [ | ||
migrations.CreateModel( | ||
name='IntervalWithChoice', | ||
fields=[ | ||
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), | ||
('value', relativedeltafield.RelativeDeltaField(blank=True, choices=[(relativedelta(months=+1), '1 month'), (relativedelta(months=+3), '3 months'), (relativedelta(months=+6), '6 months')], null=True)), | ||
], | ||
), | ||
] |
Empty file.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,5 +1,16 @@ | ||
from dateutil.relativedelta import relativedelta | ||
from django.db import models | ||
from relativedeltafield import RelativeDeltaField | ||
|
||
|
||
class Interval(models.Model): | ||
value=RelativeDeltaField(null=True, blank=True) | ||
|
||
|
||
class IntervalWithChoice(models.Model): | ||
CHOICES = [ | ||
(relativedelta(months=1), '1 month'), | ||
('P3M', '3 months'), | ||
(relativedelta(months=6), '6 months'), | ||
] | ||
value=RelativeDeltaField(null=True, blank=True, choices=CHOICES) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,8 +1,15 @@ | ||
from django.contrib import admin | ||
|
||
from testapp.models import Interval | ||
from testapp.models import Interval, IntervalWithChoice | ||
|
||
|
||
@admin.register(Interval) | ||
class IntervalAdmin(admin.ModelAdmin): | ||
list_display = ['value'] | ||
list_filter = ['value'] | ||
|
||
|
||
@admin.register(IntervalWithChoice) | ||
class IntervalWithChoiceAdmin(admin.ModelAdmin): | ||
list_display = ['value'] | ||
list_filter = ['value'] |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Why is this migration stuff needed, exactly?
I've used django-relativedelta in a few projects and it never required any special code.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
makemigrations
does not know how to serialiserelativedelta
if the model fields' arguments contains arelativedelta
object, and this tells it how.choices
are defined by a "list of (relativedelta, str) pair", so we need this whenchoices
is defined. Without this, you'd get an error when doingmakemigrations
:Without this serialisation stuffs,
default
wouldn't work eitherRelativeDeltaField(default=relativedelta(days=1))
.