Django Admin Model ArrayField Change Delimiter

Viewed 4601

My model looks like this:

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.

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.

2 Answers

Slightly cleaner solution (without overriding the __init__ in the Form class) would be to just specify the field on the form.

from django.contrib.postgres.forms import SimpleArrayField
from django import forms
from django.forms.fields import CharField
from django.forms.widgets import Textarea

class TriggerForm(forms.ModelForm):
    solutions = SimpleArrayField(CharField(), delimiter='|', widget=Textarea())

This way you can easily choose to go with, for example SplitArrayField or specify different widget for the field.

Related