将用户配置文件页面链接到Django中的模型

时间:2017-12-22 20:37:58

标签: python django django-models

我是Django的新手。我为一个简单的文本框应用程序创建了一个模型,如下所示:

from __future__ import unicode_literals
from django.db import model                  
class TODO(models.Model):                     
    task = models.CharField(max_length=200)

另外,我创建了一个用户登录门户。现在我想激活模型并在用户登录时将用户重定向到该页面。

1 个答案:

答案 0 :(得分:0)

一个简单的实现就是这样 -

models.py

from django.db import models

class TODO(models.Model):
    task = models.CharField(max_length=200)

def __str__(self):
    return self.task

urls.py

from django.conf.urls import url
from django.contrib import admin
from demo import views

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^todo/$', views.TaskView, name='list-todo'),
]

views.py

from django.contrib.auth.decorators import login_required
from django.shortcuts import render
from demo import models


@login_required
def TaskView(request):

    if request.method == 'GET':
        todos = models.TODO.objects.all()
        return render(request, 'todo.html', {'todos' : todos})

todo.html
Keep the file under a folder named 'templates' under project root

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Tasks</title>
</head>
<body>
    {% for task in todos %}
    <li>{{ task }}</li>
    {% endfor %}
</body>

settings.py

  1. Add 'templates'in DIR under TEMPLATES settings -

    'DIRS':['templates'],

  2. Add *__'app-name'__* under **INSTALLED_APPS**
  3. 执行迁移

    ./manage.py makemigrations 'app-name'  
    ./manage.py migrate
    

    运行APP
    ./manage.py runserver

    有关详细信息,请查看文档页面。快乐的编码;)