Django(16) Retreive Data From MySQL Database

To retreive Mysql Database, and add this to news page. Here are some tips.

Retreive Data From MySQL Database

  1. In views.py file, create a new object and use obj = News.objects.get(id=1) to get information where id = 1.
def NewsP(request):
    # return HttpResponse('<h1>This is our latest news</h1>')
    obj = News.objects.get(id=1)

    context = {
        "data": obj

    }

    return render(request, 'news.html', context)
  1. And in news.html, you can access these data in following way.
{% extends 'base.html' %}

{% block title %} News {% endblock %}

{% block body %}

<h1>This is our news page content</h1>

<!-- <p>This is our content description</p> -->

<h1>{{ data.author }}</h1>
<h2>{{ data.title }}</h2>
<p>{{ data.description }}</p>

{% endblock %}
  1. Refresh your launched page, you will see this as a result.


    Django(16)_Retreive_Data_From_MySQL_Database_1.png

So far, you have learnt how to get data from MySQL Database. Hopefully, it helps.

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容