[英]Django Split a charfield output which is seperated by ','(comma) into an array of strings.?
通过在models.py
文件中添加附加功能,我找到了解决问题的更好方法
模型.py
def tags_list(self):
return self.tags.split(',')
模板.html
{% for tag in tags_list %}
<p>{{ tag }}</p>
{% endfor %}
简单易行!
在您的视图中,像这样拆分逗号值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 %}
正确的方法有效,但我会使用list
内置方法来更改数组中的字符串。
class MyModel(models.Model):
string_array = models.CharField(max_length=100)
def pass_to_list(self):
return list(self.string_array)
list
方法起作用,但您也可以只返回由逗号分隔的字符串
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.