Livetuts Bj
Livetuts Bj

Reputation: 131

Django how to get a value from a query set which have kay value pair in database

I have a models.py like

class SiteSettings(TimeStampedModel):
    
    property_key = models.CharField(max_length=200)
    property_value = models.CharField(max_length=255)

In my views.py the code is like

settings = SiteSettings.objects.filter(status=1)

how can I display the value of the setting in HTML file. Like in my table has 2 values are property_key property_key is_active site_title Some title 1 site_desc Description of the site 1

Now need to display these 2 values in the template. Thanks, in advance.

Upvotes: 0

Views: 54

Answers (2)

Kwaku Kusi
Kwaku Kusi

Reputation: 56

first of all what will be stored in the settings variable in your view will be a queryset (querysets are like a list), so to display it in your template you will have to loop through it. So your view will look like this

def your_view_name(request):
    settings = SiteSettings.objects.filter(status=1)
    return render(request,<path to template>,{'settings':settings})

and in the template you will have something like

<html>
   <body>
       {% for s in settings %}
          <h1>{{s.property_key}} {{s.property_value}}</h1>
       {% endfor %}
   </body>
</html>

Secondly I believe you should filter based on the fields present in your model (but that's just an opinion)

Upvotes: 2

Oliver Hnat
Oliver Hnat

Reputation: 793

If I understand correctly, you want to show your variable "settings" inside your HTML file, so have you tried using jinja2? You could just put this in your html code {{ settings }} and that will substitute the variable for whatever the variable is in python, in your models, before rendering, you just have to specify that "settings=settings", so that the html knows what variable to look for

Upvotes: 0

Related Questions