Django models choice textField mapping

Viewed 220

I am building a website for myself I am updating my projects from django admin I wanted to create a custom field which is a map of choice(tag color) and tag text.

I want to make it look something like this

enter image description here

This is my model

class Project(models.Model):
    projectTemplate = CloudinaryField('image')
    projectTitle = models.TextField(default="Title ")
    desc = models.TextField(default="not mentioned")
    projectLink = models.URLField(max_length=200, default="not mentioned")
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return f'{self.projectTitle} - {self.desc[:15]} ..'

views.py

def projects(request):
    Projects = Project.objects.all()
    return render(request, 'devpage/projects.html',{'Projects': Projects})

This is my current DTL

{% for project in Projects %}
<div class="col">
    <div class="card shadow-sm">
        <img src="{{ project.projectTemplate.url }}" height="225" width="100%">
        <div class="card-body">
            <h6 class="text-center">
                {{ project.projectTitle }}
            </h6>
            <p class="card-text">{{ project.desc }}</p>
            <div class="mb-3">
            <span class="badge rounded-pill bg-secondary">Django</span>
                <span class="badge rounded-pill bg-success">Python</span>

            </div>
            <div class="d-flex justify-content-between align-items-center">
                <div class="btn-group">
                    <button type="button" class="btn btn-sm btn-warning btn-outline-secondary"><a
                            href="{{ project.projectLink }}" target="_blank" type="button"
                            class="btn">View</a></button>
                </div>
                <small class="text-muted">{{ project.created_at }}</small>
            </div>
        </div>
    </div>
</div>
{% endfor %}

I want a custom model field which takes choice of label color and corresponding text with dynamic size I tried using json(field name tags) but its not interactive its like {"primary":"django","success":"Python","seconday":"webApp"}

This is JSON DTL

//Inner for loop for tags
<div class="mb-3">
{% for color,text in Project.tags.items %}
    <span class="badge rounded-pill bg-{{ color }}">{{ text }}</span>
{% endfor %}
</div>
1 Answers

Assuming you have a Tag model which is a ManyToManyField, you could just store the color as an attribute to the model.

Your model:

class Tag(models.Model):
    text = models.CharField(max_length=32)
    color = models.CharField(max_length=32, default="bg-success")

class Project(models.Model):
    ...
    tags = models.ManyToManyField(Tag)

Your template:

{% for tag in Project.tags %}
    <span class="badge rounded-pill {{ tag.color }}">{{ tag.text }}</span>
{% endfor %}

Some future improvement to this could be a subclass that pre-defines all of the colors.

Related