Django Admin模型ArrayField更改分隔符 [英] Django Admin Model ArrayField Change Delimiter

查看:122
本文介绍了Django Admin模型ArrayField更改分隔符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的模型如下所示:

from django.contrib.postgres.fields import ArrayField
class Trigger(models.Model):
    solutions = ArrayField(models.TextField(blank=True, null=True), blank=True, null=True, help_text='some helpful text')

这使我可以输入默认情况下用逗号分隔的解决方案列表。例如:我可以在该文本字段中输入:

This allows me to enter a list of solutions separated by a comma by default. For example: I can enter in that textfield:

1. watch out for dust.,
2. keep away from furry animals.,

创建两个单独的字符串项目的列表。但是,如果解决方案文本本身包含逗号,例如:

This does create a list of two separate string items. However, if a solution text itself contains a comma, for example:

1. cockroaches, polens and molds might be harmful. 

这将创建两个单独的解决方案行,因为该句中存在逗号。

This will create two separate solution lines, because of the existence of a comma in that sentence.

我如何告诉Django使用与逗号不同的分隔符,因为它几乎肯定是句子的一部分。如何使用 |之类的分隔符?我查看了arrayfield类的内部,但不允许使用任何分隔符。

How do I tell django to use a different delimiter than comma as it would be almost certainly a part of sentences. How can I use a separator like '|'? I looked inside the arrayfield class, but it doesn't allow any separator.

推荐答案

一些相关文档:

  • https://docs.djangoproject.com/en/1.11/ref/contrib/postgres/fields/#arrayfield
  • https://docs.djangoproject.com/en/1.11/ref/contrib/postgres/forms/#simplearrayfield

如果您在管理站点上使用内置表单,或者使用ModelForm而不自定义任何字段,则该字段可能会自动使用 SimpleArrayField 表单字段。看起来您可以覆盖定界符。文档中指出了以下警告:

If you're using built in forms on the admin site, or using a ModelForm without customising any fields then the field is probably automatically using the SimpleArrayField form field. It looks like you can override the delimiter character. The documentation states this caveat:


该字段不支持对定界符进行转义,因此在定界符为有效字符的情况下要格外小心在基础字段中。分隔符不必只是一个字符。

The field does not support escaping of the delimiter, so be careful in cases where the delimiter is a valid character in the underlying field. The delimiter does not need to be only one character.






无论如何,您可以这样做


Anyways, you could do this by providing a custom form like this...

# forms.py

from django import forms
from .models import Trigger


class TriggerForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['solutions'].delimiter = '|'  # Or whichever other character you want.

    class Meta:
        model = Trigger
        fields = '__all__'






如果要在管理站点中使用...


And if this is for use in the admin site...

# admin.py

from django.contrib import admin
from .forms import TriggerForm
from .models import Trigger


@admin.register(Trigger)
class TriggerAdmin(admin.ModelAdmin):
    form = TriggerForm

这篇关于Django Admin模型ArrayField更改分隔符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆