小编Ale*_*ich的帖子

将 Validationerror 转换为serializers.Validationerror 在 Django Rest 框架中

我有以下问题。\n我有一个模型级验证,用于检查每次保存时的数据一致性。\n在序列化器中,如果此模型级别验证有效,它会产生server error 500回溯,而serializer.Validationerror在序列化器中,会产生漂亮且干净的结果,400 error并带有 json 中的错误消息。

\n\n

为了将模型级别转换Validationerrorserializers. Validationerror我在序列化器中使用以下代码。

\n\n
def perform_create(self, validated_data):\n    try:\n        return super().perform_create(validated_data)\n    except exceptions.ValidationError as err:\n        raise serializers.ValidationError(\n            f'Model level validation assertion -- {str(err)}'\n        ) from err\n
Run Code Online (Sandbox Code Playgroud)\n\n

它有效,但我不能并且不想覆盖每一个序列化器以转换 Validationerrorserializers. Validationerror.

\n\n

问题是 - 有没有办法捕获所有 Validationerror 并将它们转换为序列化器。验证错误?

\n

django-rest-framework

8
推荐指数
1
解决办法
2219
查看次数

在 Django ORM 中的子查询中返回多个值

问题是关于SubqueryDjango ArrayAggORM 的。

\n

例如,我有 2 个模型,彼此之间没有任何关系:

\n
\nclass Example1(models.Model):\n    ident = Integerfield()\n\nclass Example2(models.Model):\n    ident = IntegerField()\n    email = EmailField()\n
Run Code Online (Sandbox Code Playgroud)\n

FK、M2M、O2O 等 2 个模型之间没有连接,但ident两个模型中的字段\n 可能是相同的整数(这在某种程度上是连接),并且通常对于 1 个实例,Example1有多个具有Example2相同的实例ident

\n

我想制作一个subqueryor arrayagg(db Postgres) 或 RAWSQL 之外的任何方式来进行如下注释:

\n
Example1.objects.annotate(\ncls2=Subquery(\nExample2.objects.filter(\nident=OuterRef(\xe2\x80\x98ident\xe2\x80\x99\n).values_list(\xe2\x80\x98email\xe2\x80\x99, flat=True).\n\n#or\n\nExample1.objects.annotate(\ncls2=StringAgg(\nsomething here???, \ndelimeter=\xe2\x80\x99, \xe2\x80\x98,\n distinct=True,)\n\n
Run Code Online (Sandbox Code Playgroud)\n

当然,这不起作用,因为Subquery返回多行,并且似乎不可能使用, StringAgg因为我们在模型之间没有任何连接(没有任何内容可以放入其中 StringAgg)。

\n

有什么想法如何 使用一个查询集中Example1的电子邮件 进行注释吗?Example2

\n

这将在 CASE 表达式中使用。

\n

谢谢...

\n

django django-orm

7
推荐指数
1
解决办法
7989
查看次数

登录过程中带有 (user.is_active =False) 标志的用户的消息

我试图在登录过程中添加消息,对于拥有帐户但已停用的用户,如果他想进入,他必须激活它。

我使用 LoginView 控制器,它使用称为 AuthenticationForm 的内置标准表单

AuthenticationForm 有以下方法:


def confirm_login_allowed(self, user):
    """
    Controls whether the given User may log in. This is a policy setting,
    independent of end-user authentication. This default behavior is to
    allow login by active users, and reject login by inactive users.

    If the given user cannot log in, this method should raise a
    ``forms.ValidationError``.

    If the given user may log in, this method should return None.
    """
    if not user.is_active:
        raise forms.ValidationError(
            self.error_messages['inactive'],
            code='inactive',

# and …
Run Code Online (Sandbox Code Playgroud)

django django-forms django-authentication

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

cached_property 和 classmethod 不能一起工作,Django

我试图在视图集中一起使用cached_propertyclassmethod装饰器,但无论它们的相互位置如何,它都不起作用。有没有机会让它一起工作或cached_property不工作classmethod?特南克斯。

    @cached_property
    @classmethod
    def get_child_extra_actions(cls):
        """
        Returns only extra actions defined in this exact viewset exclude actions defined in superclasses.
        """
        all_extra_actions = cls.get_extra_actions()
        parent_extra_actions = cls.__base__.get_extra_actions()
        child_extra_actions = set(all_extra_actions).difference(parent_extra_actions)
        return (act.__name__ for act in child_extra_actions)
Run Code Online (Sandbox Code Playgroud)

django django-rest-framework

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

使 Redis 数据在 Docker 容器中的 docker-compose down 和 up 之间保持活动状态

问题是关于Redisdocker-compose up 和之间保持数据存活docker-compose down.

docker-compose.yaml文件波纹管db服务使用 -postgres_data:/var/lib/postgresql/data/卷来保持数据活动。我想为redis服务做这样的事情,但我找不到可行的解决方案。我设法实现这一目标的唯一方法是将数据存储在本地存储中 - ./storage/redis/data:/data.所有使用外部卷的实验都没有给出任何结果。

问题是 - 是否有可能以某种方式将 redis 数据存储在卷之间docker-compose downdocker-compose up卷中,就像它在DB服务中所做的那样?

对不起,如果问题很幼稚……

谢谢

version: '3.8'

services:
  web:
    build: .
    command: python /code/manage.py runserver 0.0.0.0:8000
    env_file:
      - ./series/.env
    volumes:
      - .:/code
    ports:
      - 8000:8000
    depends_on:
      - db
      - redis

  db:
    build:
      context: .
      dockerfile: postgres.dockerfile
    restart: always
    env_file:
      - ./series/.env
    environment:
      - POSTGRES_DB=postgres
      - POSTGRES_USER=postgres
      - POSTGRES_PASSWORD=1q2w3e
    volumes: …
Run Code Online (Sandbox Code Playgroud)

django redis docker

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

同一服务器上的 2 个数据库之间的 Postgres 复制

我需要创建现有数据库的副本,它将任何更改操作从主数据库复制到从数据库,即创建某种镜像。我在网上找到了很多例子,但它们都描述了主从服务器位于不同服务器上时的过程。我想在 master 所在的同一服务器上创建一个写副本,而不启动第二个 Postgres 实例。

是否可以这样做?您能给我指出一个方向,让我可以找到解决方案吗?

谢谢。

PS 我知道在两台服务器上进行复制更好,但我只需要在一台公共服务器上进行复制即可。

postgresql

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

django-extra-views 中的 form_valid 方法。现实形式_有效

我正在尝试使用 Django Extra Views pack 基于模型+内联表单集+来自 USER 模型的额外信息创建新条目。我知道如何通过基于函数的视图来做到这一点,但现在尝试减少代码量:

我有2个模型+用户模型:


Model1: # primary model 
author = models.ForeignKey("ExtraUser", )
+some fileds

Model2 # secondary model
photo = models.ForeignKey("Model1", )
+ some fields

# user model
Model ExtraUser(AbstractBaseUser)
+ some fileds
Run Code Online (Sandbox Code Playgroud)

我使用以下 VIEW 来渲染并将其全部保存在一起:


class ItemInline(InlineFormSetFactory):
    model = Model2
    fields = ["somefiled"]


class CreateBoatView(SuccessMessageMixin, LoginRequiredMixin, CreateWithInlinesView):
    model = Model1
    inlines = [ItemInline]
    fields = ["list of the fields here"]
    template_name = 'create.html'

    def get_success_url(self):
        return reverse('app:url', args=(self.object.pk, ))

Run Code Online (Sandbox Code Playgroud)

除了一件事之外,一切都有效:我无法指定当前用户作为条目作者,即author = models.ForeignKey("ExtraUser", ) 始终为NULL …

django django-forms django-views django-authentication

0
推荐指数
1
解决办法
625
查看次数