相关疑难解决方法(0)

Django LowerCaseCharField

我们实现了LowerCaseCharField.我们很乐意听到更好的实施建议.

from django.db.models.fields import CharField

class LowerCaseCharField(CharField):
    """
    Defines a charfield which automatically converts all inputs to
    lowercase and saves.
    """

    def pre_save(self, model_instance, add):
        """
        Converts the string to lowercase before saving.
        """
        current_value = getattr(model_instance, self.attname)
        setattr(model_instance, self.attname, current_value.lower())
        return getattr(model_instance, self.attname)
Run Code Online (Sandbox Code Playgroud)

事实上我们喜欢的是:

> modelinstance.field_name="TEST"
> print modelinstance.field_name
'test'
Run Code Online (Sandbox Code Playgroud)

当前实现仅在保存时转换为小写.

python django lowercase

12
推荐指数
1
解决办法
6483
查看次数

从 Django 登录表单中的电子邮件中删除区分大小写

我创建了一个自定义 UserModel 并使用电子邮件作为主要的身份验证 ID 而不是用户名。

它区分大小写的问题,因为它将 test@gmail.com,Test@gmail.com 计为 2 个不同的帐户。

我需要强制它处理 1 个帐户,而忽略它是大写还是小写。

这是我的文件:

模型.py

class UserModelManager(BaseUserManager):
    def create_user(self, email, password, pseudo):
        user = self.model()
        user.name = name
        user.email = self.normalize_email(email=email)
        user.set_password(password)
        user.save()

        return user

    def create_superuser(self, email, password):
        '''
        Used for: python manage.py createsuperuser
        '''
        user = self.model()
        user.name = 'admin-yeah'
        user.email = self.normalize_email(email=email)
        user.set_password(password)

        user.is_staff = True
        user.is_superuser = True
        user.save()

        return user


class UserModel(AbstractBaseUser, PermissionsMixin):
    ## Personnal fields.
    email = models.EmailField(max_length=254, unique=True)
    name = models.CharField(max_length=16)
    ## [...] …
Run Code Online (Sandbox Code Playgroud)

python django

7
推荐指数
2
解决办法
5225
查看次数

Custom field in Django get_prep_value() has no effect

So, I've made a similar class to this answer. It looks like:

class TruncatingCharField(models.CharField):
    description = _("String (truncated to %(max_length)s)")

    def get_prep_value(self, value):
        value = super(TruncatingCharField, self).get_prep_value(value)
        if value:
            value = value[:self.max_length]
        return value
Run Code Online (Sandbox Code Playgroud)

I would expect that instantiating a model with this field with strings longer than the threshold should trigger truncation. However this appears not to be the case:

class NewTruncatedField(models.Model):
    trunc = TruncatingCharField(max_length=10)


class TestTruncation(TestCase):

    def test_accepted_length(self):
        trunc = 'a'*5
        obj = NewTruncatedField(trunc=trunc)
        self.assertEqual(len(obj.trunc), 5)

    def …
Run Code Online (Sandbox Code Playgroud)

django django-models

3
推荐指数
1
解决办法
2151
查看次数

标签 统计

django ×3

python ×2

django-models ×1

lowercase ×1