有没有办法阻止 Django 修剪文本字段中的前导白色 space?

Is there a way to prevent Django from trimming leading white space in a text field?

有没有办法阻止 Django 修剪 models.TextField 中的前导白色 space?我一直在搜索文档,但没有找到任何东西。我使用的数据库是 PSQL。任何指导将不胜感激。

一个回答让我意识到有一个使用表单的解决方案。截至目前,我不使用表格:

class Song(models.Model):
    """
    Fields that are displayed on the Song screeen
    """
    name = models.CharField(max_length=100, blank=True, default="")
    artist = models.CharField(max_length=100, blank=True, default="")
    creator = models.ForeignKey(get_user_model(), on_delete=models.CASCADE)
    lyrics = models.TextField(default="", blank=True)
    pulled_lyrics = models.TextField(default="", blank=True)
    chords = models.TextField(default="", blank=True)
    strumming_pattern = models.CharField(max_length=30, default="", blank=True)

    """
    Additional information used to determine where to display the song
    """
    public = models.BooleanField(default=False)
    is_favourite = models.BooleanField(default=False)

    def __str__(self):
        return self.name 
class SongViewSet(viewsets.ModelViewSet):
    serializer_class = SongSerializer

    def get_queryset(self):
        """
        Sets queryset to be songs owned by user
        This makes it so that a user can only manipulate their own songs
        """
        if not self.request.user.is_authenticated:
            return []

        user = self.request.user
        qs = Song.objects.all()
        if user.is_superuser:
            return qs
        else:
            return qs.filter(creator=user)
    
    def create(self, request):
        """
        Create user with given request body
        """
        try:
            song = Song.objects.create(creator=request.user, **request.data)
        except:
            return Response('The provided data was of an invalid form.', status=status.HTTP_400_BAD_REQUEST)
        song_serializer = SongSerializer(song)
        return Response(song_serializer.data, status=status.HTTP_200_OK)

JS(React)代码分别创建新歌和修补歌曲:

const response = await axios.post(
                "/api/songs/",
                {},
                {
                    withCredentials: true,
                    headers: {
                        "X-CSRFToken": getToken(),
                    },
                }
            );
const songCopy = { ...item }
    delete songCopy["creator"];
    axios.patch(`/api/songs/${item.id}/`, songCopy, {
        withCredentials: true,
        headers: {
            "Content-Type": "application/json",
            "X-CSRFToken": getToken(),
        },
    });

,你的表单域应该在表单中设置strip=False [Django-doc],所以:

class MyForm(forms.Form):
    some_field = forms.CharField(<strong>strip=False</strong>)

对于序列化程序,这非常相似,在您的序列化程序中,您应该设置 trim_whitespace=False [DRF-doc]:

from rest_framework import serializers

class SongSerializer(ModelSerializer):
    lyrics = serializers.CharField(<strong>trim_whitespace=False</strong>)

正如 documentation 所说:

If True (default), the value will be stripped of leading and trailing whitespace.

如果您呈现数据,则多个(前导)space 将在网页上呈现为一个 space。您可以使用 <pre> 标签作为 预格式化 文本元素,因此:

{{ some_variable }}