plantilla.html
{{ profile.tag }}vistas.py
class ProfileView(CanEditMixin, UserPassesTestMixin, DetailView): template_name = "profile/profile_view.html" queryset = User.objects.all() context_object_name = 'profile' slug_field = "username"`da salida como "etiqueta1, etiqueta2, etiqueta3"
¿Hay alguna forma de hacerlo en Django?
Encontré una mejor manera de resolver el problema agregando una función adicional en el archivo models.py
modelos.py
def tags_list(self): return self.tags.split(',')plantilla.html
{% for tag in tags_list %} <p>{{ tag }}</p> {% endfor %}¡simple y fácil!
En su opinión, divida el campo CharField de valor de coma de esta manera:
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 contexty luego en su plantilla simplemente itere sobre ella:
{% for tag in tag_list %} <p>{{ tag }}</p> {% endfor %}La forma correcta funciona, pero usaría el método integrado de list para simplemente cambiar la cadena de la matriz.
class MyModel(models.Model): string_array = models.CharField(max_length=100) def pass_to_list(self): return list(self.string_array)list incorporado, pero también puede devolver la cadena dividida por comas