template.html
{{ profile.tag }}
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本身做到这一点?
所示答案 0 :(得分:0)
在您的视图中,将逗号值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 %}
答案 1 :(得分:0)
通过在models.py
文件
models.py
def tags_list(self):
return self.tags.split(',')
template.html
{% for tag in tags_list %}
<p>{{ tag }}</p>
{% endfor %}
简单易行!
答案 2 :(得分:0)
正确的方法有效,但我会使用 list
内置方法来更改数组中的字符串。
class MyModel(models.Model):
string_array = models.CharField(max_length=100)
def pass_to_list(self):
return list(self.string_array)
list
方法起作用,但您也可以只返回由逗号分隔的字符串