Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/365.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Django分割由';分隔的charfield输出';(逗号)转换为字符串数组。?_Python_Django_Django Templates - Fatal编程技术网

Python Django分割由';分隔的charfield输出';(逗号)转换为字符串数组。?

Python Django分割由';分隔的charfield输出';(逗号)转换为字符串数组。?,python,django,django-templates,Python,Django,Django Templates,template.html {{ profile.tag }} {% for tag in tags_list %} <p>{{ tag }}</p> {% endfor %} views.py class ProfileView(CanEditMixin, UserPassesTestMixin, DetailView): template_name = "profile/profile_view.html" queryset = User.ob

template.html

{{ profile.tag }}
{% for tag in tags_list %}
    <p>{{ tag }}</p>
{% endfor %}
views.py

class ProfileView(CanEditMixin, UserPassesTestMixin, DetailView):
   template_name = "profile/profile_view.html"
   queryset = User.objects.all()
   context_object_name = 'profile'
   slug_field = "username"`
输出为“tag1、tag2、tag3”

django本身有没有办法做到这一点


我希望输出如下所示

在您的视图中,按如下方式拆分逗号值
CharField
字段:

class ProfileView(CanEditMixin, UserPassesTestMixin, DetailView):
    template_name = "profile/profile_view.html"
    queryset = User.objects.all()
    context_object_name = 'profile'
    slug_field = "username"`

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)  # get parent context
        # the model here should be replaced with the object that has the "tag" attribute. DO NOT use the "model" word.
        # Try self.object.tag.split(',')
        tag_list = model.tag.split(',')  # conversion from a string to a list
        context['tag_list'] = tag_list  # add to the context the tag_list list
        return context
然后在模板中,只需对其进行迭代:

{% for tag in tag_list %}
    <p>{{ tag }}</p>
{% endfor %}
{%for tag_list%}
{{tag}}

{%endfor%}
通过在
models.py
文件中添加附加函数,我找到了解决问题的更好方法

models.py

def tags_list(self):
    return self.tags.split(',')
template.html

{{ profile.tag }}
{% for tag in tags_list %}
    <p>{{ tag }}</p>
{% endfor %}
{%for tags in tags\u list%}
{{tag}}

{%endfor%}

简单易用

正确的方法是可行的,但我会使用
list
内置方法来更改数组中的字符串

class MyModel(models.Model):
    string_array = models.CharField(max_length=100)

    def pass_to_list(self):
        return list(self.string_array)
笔记:
  • 请记住,字符串数组必须是数据库上的实际数组,包含“[”和所有内容
  • 这种方法通过使用内置的
    list
    方法来工作,但也可以只返回用逗号分隔的字符串

我已经声明了一个上下文,是否有一种方法可以覆盖声明多个上下文?我是一个新手我编辑了上面的视图。我需要在视图中更改什么?更新我的答案以满足您的需要。不,它不起作用,它输出为单个字符串,没有“,”a(逗号)。好的。让我了解一下,您希望字符串
'cat1,cat2,cat3'
转换为
['cat1','cat2','cat3']
?当您必须存储字符串数组时,背后的想法会有所帮助,但您使用的是mysql,但如果您使用的是postgres,我强烈建议您使用