有没有一种简单的方法就可以在Django模板中显示mysql数据而无需创建应用程序? [英] Is there a simple way to display mysql data in Django template without creating an app?

查看:48
本文介绍了有没有一种简单的方法就可以在Django模板中显示mysql数据而无需创建应用程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的MySQL数据库中有一个名为mysite_categories的表,共有4列,但出于我的目的,我只需要两列(名称,base_url).

I have a table in my MySQL database named mysite_categories, there are 4 columns but for my purposes I just need two (name, base_url).

我目前有一个模板'* base_categories.html *',可用于手动加载类别.

I currently have a template '*base_categories.html*' that I use to load the categories manually.

base_categories.html(已精简)

{% block content %}
  <div class="section" style="float: right;">
    <h4 class="gradient">Category List</h4>
    <ul>
      <li><a href="/categories/Art" id="nav_font">Art</a></li>
      <li><a href="/categories/Biography" id="nav_font">Biography</a></li>
      <li><a href="/categories/Science" id="nav_font">Science</a></li>
    </ul>
  </div>
{% endblock %}

我想做的是从数据库中提取数据,并在for循环中使用它.像这样:

What I'd like to do is pull the data from the db and use it in a for loop. Something like:

{% block content %}
  <div class="section" style="float: right;">
    <h4 class="gradient">Category List</h4>
    <ul>
      {% for category in mysite_categories %}
        <li><a href="{{ category.base_url }}" id="nav_font">{{ category.name }}</a></li>
      {% endfor %}
    </ul>
  </div>
{% endblock %}

这可能是一个新手问题,但是否可以在不创建应用的情况下进行类似操作?

This is probably a newbie question but is it possible to something like this without creating an app?

*EDIT 1*

*EDIT 1*

这些是我的应用程序文件,我承认这可能是垃圾,我尝试了来自许多不同职位的大量编辑,我敢肯定我已经在:P某处将其弄乱了.我打算将其删除并重新开始,但我想我最好将其发布以查看可能出了问题的地方?

These are my app files, I'll admit this is probably junk, I have tried so many edits from so many different posts I'm sure I've broke it somewhere :P. I was going to remove it and start fresh but I figure I might as well post it to see where I might have gone wrong?

views.py

from django.shortcuts import render_to_response
from categories.models import categoryList


def index(request):
    categories = categoryList.objects.all()
    extra_context = {"categories": categories}

    return render_to_response("myapp/index.html", extra_context)

models.py

from django.db import models


class categoryList(models.Model):
    #id = models.IntegerField(unique=True, db_column='ID') # Field name made lowercase.
    name = models.CharField(max_length=255L, unique=True)
    base_url = models.CharField(max_length=255L, unique=True)
    thumb = models.CharField(max_length=1L, unique=True, blank=True)
    class Meta:
        db_table = 'mysite_categories'

index.html

{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}

<div class="section" style="float: right;">
  <h4 class="gradient">Category List</h4>
  <ul>
    {% for category in categories %}
      <li><a href="" id="nav_font">{{ category.title }}</a></li>
    {% endfor %}
  </ul>
</div>

如前所述,目前可能是垃圾,如果任何人可以帮助我弄清楚这一点,将不胜感激!

As mentioned, it's probably junk at this point, if any of you can help me straighten this out it would be appreciated!

*EDIT 2*

*EDIT 2*

base_right_panel.html

{% block content %}
  <div style="float: right;">
    <div id="base_categories" style="margin: 10px; padding-bottom: 10px;">
      {% block base_categories %}
        {% include "base_categories.html" %}
      {% endblock %}
    </div>
  </div>
{% endblock %}

*Edit 3*

*Edit 3*

base_categories.html

{% block content %}
  <div class="section" style="float: right;">
    <h4 class="gradient">Category List</h4>
    <ul>
      {% if categories %}
        {% for category in categories %}
          <li><a href="" id="nav_font">{{ category.title }}</a></li>
        {% endfor %}
      {% else %}
        <p>no data! {{ categories|length }}</p>
      {% endif %}
    </ul>
  </div>
{% endblock %}

*EDIT 4*

*EDIT 4*

(应用程序名称已更改为CategoryList)

(Application name was changed to CategoryList)

CategoryList/views.py

from django.views.generic import TemplateView
from CategoryList.models import CategorylistCategorylist #<-- Changed to match inspectdb result

class IndexView(TemplateView):
    template_name="categorylist.html" #<-- Changed name from index.html for clarity

    def get_context_data(self, **kwargs):
        context = super(IndexView, self).get_context_data(**kwargs)
        context["categories"] = CategorylistCategorylist.objects.all()
        return context

CategoryList/models.py

from django.db import models

class CategorylistCategorylist(models.Model): #<-- Changed to match inspectdb
    id = models.IntegerField(primary_key=True)
    name = models.CharField(max_length=255L, unique=True)
    base_url = models.CharField(max_length=255L, unique=True)
    thumb = models.ImageField(upload_to="dummy", blank=True) #<-- Ignored inspectdb's suggestion for CharField

    def __unicode__(self):
        return self.name

    # Re-added Meta to match inspectdb
    class Meta:
        db_table = 'categorylist_categorylist'

CategoryList/urls.py

from django.conf.urls.defaults import patterns, url, include
from django.contrib import admin
from django.conf import settings
from CategoryList import views

admin.autodiscover()

urlpatterns = patterns('',
    url(r'^$', views.IndexView.as_view(), name='categorylist'),
)

if settings.DEBUG:
    urlpatterns = patterns('',
    url(r'^media/(?P<path>.*)$', 'django.views.static.serve',
        {'document_root': settings.MEDIA_ROOT, 'show_indexes': True}),
    url(r'', include('django.contrib.staticfiles.urls')),
) + urlpatterns

MySite/urls.py

from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.conf import settings
from home import views as home_view
from CategoryList import views as index_view

admin.autodiscover()

urlpatterns = patterns('',
    url(r'^$', home_view.HomeView.as_view(), name="home"),

    url(r'^categories/$', index_view.IndexView.as_view(), name='categorylist'),#include('CategoryList.urls')),

    url(r'^admin/', include(admin.site.urls)),
    #url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
)

if settings.DEBUG:
    urlpatterns = patterns('',
    url(r'^media/(?P<path>.*)$', 'django.views.static.serve',
        {'document_root': settings.MEDIA_ROOT, 'show_indexes': True}),
    url(r'', include('django.contrib.staticfiles.urls')),
) + urlpatterns

到目前为止,我可以加载URL" localhost:8000/categories ",并且我会看到类别名称列表按预期显示在屏幕的右侧,但是没有模板格式应用.在我的"* base_right_panel.html *"文件中,我尝试" {%包括"categorylist.html%} ""直接链接到应用程序,该应用程序显示正确的模板格式,但显示是 {%else%} 的答复,而不是" {%if category%} "的分类?我尝试将include更改为指向" categories/",它可以在浏览器中运行,但是它告诉我找不到模板?

So far I can load the url "localhost:8000/categories" and I will see the list of category names appear on the right side of the screen as expected, but there is no template formatting applied. Inside my "*base_right_panel.html*" file I've tried "{% include "categorylist.html %}" to link directly to the application, which displays the correct template formatting, but displays the "{% else %}" response from "{% if categories %}" instead of the categories? I have tried changing the include to point to "categories/", which works in the browser, but it tells me it cannot find the template?

我现在很迷st ..?

I'm sooo stumped right now..?

推荐答案

您可以

You could execute custom SQL directly to fetch categories in your view, and loop through the output in your template. This would not require an app.

如果您创建模型,则可以使用Django queryset api,这非常方便,例如

If you create a model, you will be able to use the Django queryset api, which is very convenient, e.g.

mysite_categories = Category.objects.all()

这确实需要您创建一个应用.但是,创建应用程序确实非常容易,只需使用 startapp 命令.

This does require you to create an app. However, creating an app is really easy, just use the startapp command.

python manage.py startapp myapp

创建应用后,您可以使用 inspectdb 命令来检查数据库,并为mysite_categories表创建模型.

Once you've created your app, you can use the inspectdb command to inspect your database, and create a model for your mysite_categories table.

这篇关于有没有一种简单的方法就可以在Django模板中显示mysql数据而无需创建应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆