RLave
RLave

Reputation: 8364

Pass value to CSS style Tag from Django View

I have this View where I generate a percentage value that depends on some logic in the backend.

def my_view(request):
    #[..other stuff..]
    perc_value = 80 # this changes with the logic above
    
    context = {'perc_value': perc_value}

    return render(...) 

In my HTML I need to render a progress-bar that will be filled with perc_value, like this:

<div class="progress progress-xl mb-2"> 
    <div class="progress-bar" role="progressbar" style="width: {{ perc_value }}">{{ perc_value }}%</div>
</div>

I have found this similar question (link), which is pretty old and I can't find a way to make it work. What's the best way for this kind of problem?

Upvotes: 1

Views: 849

Answers (3)

Zhivko Zaikov
Zhivko Zaikov

Reputation: 449

Yes, as mentioned above adding px or % should work:

style="width: {{ perc_value }}px"

You could also add a class such as:

class="{{ perc_value }}percentcomplete"

which would turn into 80percentcomplete and then you may configure each class in your CSS. Another option is to use the Bootstrap width classes such as:

w-25, w-50, w-75, w-100 but you need to apply additional logic in the view to return only four values which depend on the progress of the process.

Upvotes: 0

Mamed
Mamed

Reputation: 95

try to add % or px after {{ perc_value}} like below.

<div class="progress progress-xl mb-2"> 
    <div class="progress-bar" role="progressbar" style="width: {{ perc_value }}%">{{ perc_value }}%</div>
</div>

Upvotes: 2

robline
robline

Reputation: 460

You seem really close. First thing I would do is replace the {{ perc_value }} with '80.' Does it work? If not, I would put 80px or 80% or some such. My point is, get it looking on the screen the way you want with static values.

Next, use debugging statements in the template or look at the debug toolbar to make sure perc_value is being passed, it has the right value, and it has the right type. Its possible that you are setting up the context but not actually sending it through the request. Hard to see without the whole view.

Upvotes: 1

Related Questions