Home > Mobile >  Get data from django database
Get data from django database

Time:12-05

So,how get data from django database?I have django models and created 2 objects there.I want to get 2 objects and write in html file. admin panel: https://i.stack.imgur.com/7WUZr.png

view.py

    def vds(request):
    HTML_STRING = render_to_string("vds.html", context=context1)
    return HttpResponse(HTML_STRING)
VDSTARIFS_obj = VDSTARIFS.objects.get(id=1)
context1 = {
    "prise": VDSTARIFS_obj.prise,
}

file with models

class VDSTARIFS( models.Model):
    prise = models.CharField(max_length= 10,)
    
    def __str__(self):
        return str(self.prise)```

CodePudding user response:

Referring to the Django docs:

https://docs.djangoproject.com/en/3.2/intro/tutorial03/#a-shortcut-render

from django.shortcuts import render
from .models import Question

def index(request):
    latest_question_list = Question.objects.order_by('-pub_date')[:5]
    context = {'latest_question_list': latest_question_list}
    return render(request, 'polls/index.html', context)

Edited for your model

from django.shortcuts import render
from .models import VDSTARIFS

def vds(request):
    ALL_VDSTARIFS = VDSTARIFS.objects.all()
    FIRST_VDSTARIF = ALL_VDSTARIFS[:1]

    # Get prise
    prise = FIRST_VDSTARIF.prise

    # Alternatives to print 'prise' in template 

    # Pass only the first item of vds list
    context = {
        "FIRST_VDSTARIF": FIRST_VDSTARIF
    }

    # Pass prise only
    
    context = {
        "prise": prise
    }

    # All records in html also the needed one in separated item
    context = {
        "ALL_VDSTARIFS": VDSTARIFS,
        "FIRST_VDSTARIF": FIRST_VDSTARIF
    }

    return render(request, 'vds.html', context)
}

In template you can use if https://docs.djangoproject.com/en/3.2/ref/templates/builtins/#if

{# Runs along all tarifs and print only one, not good. #}
{% for vdstarif in ALL_VDSTARIFS %}
 {% if vdstarifs.id == "1" %}
   {{ vdstarif.prise }}
 {% endif %}
{% endfor %}

{# Only print the needed one #}
{{ FIRST_VDSTARIF.prise }}


{# Print prise #}
{{ prise }}

You might follow python and django coding conventions and my suggestions.

Rename VDSTARIFS -> VdsTarif (look at your admin page, Django adds 's' to your model to make it plural)

Use singular names for your models and add a suffix to variable names in views like vdstarif_list.

For "prise" field use DecimalField, looks like it is a CharField. Is it prise or price? https://docs.djangoproject.com/en/3.2/ref/models/fields/#decimalfield

from django.shortcuts import render
from .models import VdsTarif

def vds(request):
   vdstarif_list = VdsTarif.objects.all()

   context = {
        "vdstarif_list" : vfstarif_list[:0].prise
   }

   return render(request, 'vds.html', context)
  • Related