Python 在django模型的每个字段上实现隐私的最佳方法
我试图在模型的字段级别为用户提供隐私设置。因此,用户可以决定要显示哪些数据以及要隐藏哪些数据 例如:Python 在django模型的每个字段上实现隐私的最佳方法,python,django,django-permissions,Python,Django,Django Permissions,我试图在模型的字段级别为用户提供隐私设置。因此,用户可以决定要显示哪些数据以及要隐藏哪些数据 例如: class Foo(models.Model): user = models.OneToOneField("auth.User") telephone_number = models.CharField(blank=True, null=True, max_length=10) image = models.ImageField(upload_to=get_photo_s
class Foo(models.Model):
user = models.OneToOneField("auth.User")
telephone_number = models.CharField(blank=True, null=True, max_length=10)
image = models.ImageField(upload_to=get_photo_storage_path, null=True, blank=True)
我想为用户提供一个选项,选择他想要显示和不想要显示的字段。
考虑用户不想显示电话号码,所以他应该有选择。
哪种方法是最好的 您可以在模型内创建一个CommaSeparatedIntegerField字段,并使用它存储用户想要隐藏的字段名列表(表示字段名的整数) 您可以在models.py中创建字段_名称和整数之间的映射作为常量。并检查用户已检查的字段名称 映射示例:
FIELD_NAME_CHOICES = (
(1, Foo._meta.get_field('telephone_number')),
(2, Foo._meta.get_field('name')),
.
.
)
查看以下链接以供参考非常明显的简单愚蠢的解决方案是为每个字段添加一个布尔“show_xxx”,即:
class Foo(models.Model):
user = models.OneToOneField("auth.User")
telephone_number = models.CharField(blank=True, null=True, max_length=10)
show_telephone_number = models.BooleanField(default=True)
image = models.ImageField(upload_to=get_photo_storage_path, null=True, blank=True)
show_image = models.BooleanField(default=True)
然后在模板中检查show_xxx
字段的值:
{% if foo.telephone_number and foo.show_telephone_number %}
<p>Telephone number: {{ foo.telephone_number }}</p>
{% endif %}
但我不确定这是否真的是一种“优化”。。。您还必须手动处理编辑表单中的复选框等。您还可以使用多选字段。。。下面的代码来自Django代码片段,所以请不要给我任何学分,因为我只是在分享别人的作品
class MultiSelectField(models.CharField):
""" Choice values can not contain commas. """
def __init__(self, *args, **kwargs):
self.max_choices = kwargs.pop('max_choices', None)
super(MultiSelectField, self).__init__(*args, **kwargs)
self.max_length = get_max_length(self.choices, self.max_length)
self.validators[0] = MaxValueMultiFieldValidator(self.max_length)
if self.max_choices is not None:
self.validators.append(MaxChoicesValidator(self.max_choices))
@property
def flatchoices(self):
return None
def get_choices_default(self):
return self.get_choices(include_blank=False)
def get_choices_selected(self, arr_choices):
choices_selected = []
for choice_selected in arr_choices:
choices_selected.append(string_type(choice_selected[0]))
return choices_selected
def value_to_string(self, obj):
value = self._get_val_from_obj(obj)
return self.get_prep_value(value)
def validate(self, value, model_instance):
arr_choices = self.get_choices_selected(self.get_choices_default())
for opt_select in value:
if (opt_select not in arr_choices):
if django.VERSION[0] == 1 and django.VERSION[1] >= 6:
raise ValidationError(self.error_messages['invalid_choice'] % {"value": value})
else:
raise ValidationError(self.error_messages['invalid_choice'] % value)
def get_default(self):
default = super(MultiSelectField, self).get_default()
if isinstance(default, (int, long)):
default = string_type(default)
return default
def formfield(self, **kwargs):
defaults = {'required': not self.blank,
'label': capfirst(self.verbose_name),
'help_text': self.help_text,
'choices': self.choices,
'max_length': self.max_length,
'max_choices': self.max_choices}
if self.has_default():
defaults['initial'] = self.get_default()
defaults.update(kwargs)
return MultiSelectFormField(**defaults)
def get_prep_value(self, value):
return '' if value is None else ",".join(value)
def to_python(self, value):
if value:
return value if isinstance(value, list) else value.split(',')
def contribute_to_class(self, cls, name):
super(MultiSelectField, self).contribute_to_class(cls, name)
if self.choices:
def get_list(obj):
fieldname = name
choicedict = dict(self.choices)
display = []
if getattr(obj, fieldname):
for value in getattr(obj, fieldname):
item_display = choicedict.get(value, None)
if item_display is None:
try:
item_display = choicedict.get(int(value), value)
except (ValueError, TypeError):
item_display = value
display.append(string_type(item_display))
return display
def get_display(obj):
return ", ".join(get_list(obj))
setattr(cls, 'get_%s_list' % self.name, get_list)
setattr(cls, 'get_%s_display' % self.name, get_display)
MultiSelectField = add_metaclass(models.SubfieldBase)(MultiSelectField)
这将浪费DB空间和大量额外字段,如果我的模型有20个字段会怎么样。我需要另外20个标志字段。不是优化的解决方案添加了“数据库空间优化”解决方案。。。但我不确定我会称之为优化。我完全同意。空间很便宜,浪费它吧。但是我想看到一种用mixin@SebastianWozny这可以通过一个装饰器(用来标记哪些字段应该是“可标记的”)和一个自定义元类来完成。你能演示一下吗?这似乎是一个最复杂的解决方案。目前还可以作为PyPi模块使用,称为django multiselectOne,应该为此权限创建一个单独的类,因为我们无法在Foo内部访问类Foo。好吧,您可以做很多事情,这可以驻留在Foo类内部的classmethod中。在那里,您可以通过cls变量访问该类。其次,现在我们也有了Django中可用的JSONField类型。可直接用于将字段名存储为列表。
class MultiSelectField(models.CharField):
""" Choice values can not contain commas. """
def __init__(self, *args, **kwargs):
self.max_choices = kwargs.pop('max_choices', None)
super(MultiSelectField, self).__init__(*args, **kwargs)
self.max_length = get_max_length(self.choices, self.max_length)
self.validators[0] = MaxValueMultiFieldValidator(self.max_length)
if self.max_choices is not None:
self.validators.append(MaxChoicesValidator(self.max_choices))
@property
def flatchoices(self):
return None
def get_choices_default(self):
return self.get_choices(include_blank=False)
def get_choices_selected(self, arr_choices):
choices_selected = []
for choice_selected in arr_choices:
choices_selected.append(string_type(choice_selected[0]))
return choices_selected
def value_to_string(self, obj):
value = self._get_val_from_obj(obj)
return self.get_prep_value(value)
def validate(self, value, model_instance):
arr_choices = self.get_choices_selected(self.get_choices_default())
for opt_select in value:
if (opt_select not in arr_choices):
if django.VERSION[0] == 1 and django.VERSION[1] >= 6:
raise ValidationError(self.error_messages['invalid_choice'] % {"value": value})
else:
raise ValidationError(self.error_messages['invalid_choice'] % value)
def get_default(self):
default = super(MultiSelectField, self).get_default()
if isinstance(default, (int, long)):
default = string_type(default)
return default
def formfield(self, **kwargs):
defaults = {'required': not self.blank,
'label': capfirst(self.verbose_name),
'help_text': self.help_text,
'choices': self.choices,
'max_length': self.max_length,
'max_choices': self.max_choices}
if self.has_default():
defaults['initial'] = self.get_default()
defaults.update(kwargs)
return MultiSelectFormField(**defaults)
def get_prep_value(self, value):
return '' if value is None else ",".join(value)
def to_python(self, value):
if value:
return value if isinstance(value, list) else value.split(',')
def contribute_to_class(self, cls, name):
super(MultiSelectField, self).contribute_to_class(cls, name)
if self.choices:
def get_list(obj):
fieldname = name
choicedict = dict(self.choices)
display = []
if getattr(obj, fieldname):
for value in getattr(obj, fieldname):
item_display = choicedict.get(value, None)
if item_display is None:
try:
item_display = choicedict.get(int(value), value)
except (ValueError, TypeError):
item_display = value
display.append(string_type(item_display))
return display
def get_display(obj):
return ", ".join(get_list(obj))
setattr(cls, 'get_%s_list' % self.name, get_list)
setattr(cls, 'get_%s_display' % self.name, get_display)
MultiSelectField = add_metaclass(models.SubfieldBase)(MultiSelectField)