Refactoring preferences to be more cohesive

No need to list the preference fields three times in three places in the code. A class decorator ought to be able to sleuth them out from the model itself. Should make it easier to add new preferences.
This commit is contained in:
Cy 2020-05-30 06:40:53 +00:00 committed by Cy
parent 00e35409ef
commit 0b93eb78f4
No known key found for this signature in database
GPG Key ID: F66D599380F88521
3 changed files with 16 additions and 28 deletions

View File

@ -28,19 +28,7 @@ class OAuthLoginForm(forms.Form):
class PreferencesForm(forms.ModelForm): class PreferencesForm(forms.ModelForm):
class Meta: class Meta:
model = Preference model = Preference
fields = [ fields = Preference._fields
"theme",
"filter_replies",
"filter_boosts",
"timezone",
"no_javascript",
"notifications",
"click_to_load",
"lightbox",
"filter_notifications",
"bundle_notifications",
"poll_frequency",
]
class PostForm(forms.Form): class PostForm(forms.Form):

View File

@ -30,6 +30,17 @@ class Theme(models.Model):
return self.name return self.name
def set_fields(klass):
fields = {}
for n in dir(klass):
assert n != "_fields"
v = getattr(klass, n)
if isinstance(v, models.Field):
fields.add(n)
setattr(klass, '_fields', fields)
return klass
@set_fields
class Preference(models.Model): class Preference(models.Model):
theme = models.ForeignKey(Theme, models.CASCADE, null=False, default=1) theme = models.ForeignKey(Theme, models.CASCADE, null=False, default=1)
filter_replies = models.BooleanField(default=False) filter_replies = models.BooleanField(default=False)

View File

@ -767,21 +767,10 @@ def settings(request):
if request.method == "POST": if request.method == "POST":
form = PreferencesForm(request.POST) form = PreferencesForm(request.POST)
if form.is_valid(): if form.is_valid():
account.preferences.theme = form.cleaned_data["theme"] for field in account.preferences._fields:
account.preferences.filter_replies = form.cleaned_data["filter_replies"] if field in form.cleaned_data:
account.preferences.filter_boosts = form.cleaned_data["filter_boosts"] setattr(account.preferences, field,
account.preferences.timezone = form.cleaned_data["timezone"] form.cleaned_data[field])
account.preferences.no_javascript = form.cleaned_data["no_javascript"]
account.preferences.notifications = form.cleaned_data["notifications"]
account.preferences.click_to_load = form.cleaned_data["click_to_load"]
account.preferences.lightbox = form.cleaned_data["lightbox"]
account.preferences.filter_notifications = form.cleaned_data[
"filter_notifications"
]
account.preferences.bundle_notifications = form.cleaned_data[
"bundle_notifications"
]
account.preferences.poll_frequency = form.cleaned_data["poll_frequency"]
request.session["timezone"] = account.preferences.timezone request.session["timezone"] = account.preferences.timezone
account.preferences.save() account.preferences.save()
account.save() account.save()