Skip to content

Commit 4f90734

Browse files
authored
Fix #194: use formfield_callback to assume HTTPS scheme. (#195)
* fix #194: use formfield_callback to assume HTTPS scheme * test: test scheme of URLField * fix: option only exists since Django 5.0
1 parent 2c20097 commit 4f90734

File tree

2 files changed

+30
-1
lines changed

2 files changed

+30
-1
lines changed

extra_settings/forms.py

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,27 @@
1-
from django import forms
1+
from django import VERSION, forms
22
from django.conf import settings
3+
from django.db import models
34

45
from extra_settings.models import Setting
56
from extra_settings.utils import enforce_uppercase_setting
67

78

9+
def urlfields_assume_scheme(field, **kwargs):
10+
"""
11+
ModelForm.Meta.formfield_callback function to set assume_scheme for scheme-less
12+
domains in URLFields. Only since Django version 5.0.
13+
"""
14+
if isinstance(field, models.URLField) and VERSION >= (5, 0):
15+
kwargs["assume_scheme"] = "https"
16+
17+
return field.formfield(**kwargs)
18+
19+
820
class SettingForm(forms.ModelForm):
921
class Meta:
1022
model = Setting
1123
fields = "__all__"
24+
formfield_callback = urlfields_assume_scheme
1225

1326
def __init__(self, *args, **kwargs):
1427
super().__init__(*args, **kwargs)

tests/test_forms.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
from django import VERSION
12
from django.test import TestCase
23

34
from extra_settings.forms import SettingForm
@@ -34,3 +35,18 @@ def test_form_with_optional_data(self):
3435
}
3536
form_obj = SettingForm(data=form_data)
3637
self.assertTrue(form_obj.is_valid())
38+
39+
def test_form_assume_scheme(self):
40+
form_data = {
41+
"name": "PACKAGE_NAME",
42+
"value_type": Setting.TYPE_URL,
43+
"description": "A URL field",
44+
"value_url": "example.com",
45+
}
46+
form_obj = SettingForm(data=form_data)
47+
self.assertTrue(form_obj.is_valid())
48+
49+
if VERSION >= (5, 0):
50+
self.assertEqual(form_obj.cleaned_data["value_url"], "https://example.com")
51+
else:
52+
self.assertEqual(form_obj.cleaned_data["value_url"], "http://example.com")

0 commit comments

Comments
 (0)