[英]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.