Last active
December 1, 2022 00:40
-
-
Save bulv1ne/e0d3f3b0b2999b3b04f5e6a677d71293 to your computer and use it in GitHub Desktop.
Django MultipleChoiceField JSONField
This file contains 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
from django.contrib import admin | |
from django.template.loader import render_to_string | |
from .forms import UserRoleAdminForm | |
from .models import UserRole | |
@admin.register(UserRole) | |
class UserRoleAdmin(admin.ModelAdmin): | |
list_display = ('name', 'fields_data',) | |
form = UserRoleAdminForm | |
def fields_data(self, obj): | |
return render_to_string('fields_data.html', { | |
'fields': obj.fields_dict.items() | |
}) |
This file contains 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
{% load staticfiles %} | |
<ul> | |
{% for field, selected in fields %} | |
<li> | |
{% if selected %} | |
<img src="{% static 'admin/img/icon-yes.svg' %}" alt="True"> | |
{% else %} | |
<img src="{% static 'admin/img/icon-no.svg' %}" alt="False"> | |
{% endif %} | |
{{ field }} | |
</li> | |
{% endfor %} | |
</ul> |
This file contains 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
from django import forms | |
from .models import UserRole | |
class UserRoleAdminForm(forms.ModelForm): | |
fields = forms.MultipleChoiceField(choices=UserRole.CHOICES, widget=forms.CheckboxSelectMultiple) | |
class Meta: | |
model = UserRole | |
fields = ('name', 'fields',) |
This file contains 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
from collections import OrderedDict | |
from django.contrib.postgres.fields import JSONField | |
from django.db import models | |
class UserRole(models.Model): | |
CHOICES = ( | |
('admin:invite', 'Invite user'), | |
) | |
name = models.CharField(max_length=255, unique=True) | |
fields = JSONField(default=list) | |
@property | |
def fields_dict(self): | |
fields = set(self.fields) | |
return OrderedDict([ | |
(field[0], field[0] in fields) | |
for field in self.CHOICES | |
]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you very much.