如何在Django中为不同的用户创建不同的模型数据库

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何在Django中为不同的用户创建不同的模型数据库相关的知识,希望对你有一定的参考价值。

我正在尝试创建一个todo网站。因为所有用户都有自己的Todos列表。但是它向所有用户显示相同的列表,并且其他用户可以编辑,删除和添加到所有用户再次可见的待办事项列表。

models.朋友

from django.db import models
from django.contrib.auth import get_user_model
from django.conf import settings


class todo (models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete="models.CASCADE")
    todo_topic = models.CharField (max_length = 50)
    todo_description = models.TextField(max_length=100)
    todo_date = models.DateTimeField(null = True)
    date_added = models.DateTimeField(auto_now = True,)
    completed_or_not = models.CharField(choices=(('Done', 'Done'), ('Not Done', 'Not Done')), default = 'Not Done', max_length=10)

views.朋友

from django.shortcuts import render
from .models import todo
from .forms import addTodo_form, edit_form
from django.contrib.auth.models import User
from django.http import HttpResponseRedirect
from django.urls import reverse
from django.contrib.auth.decorators import login_required

def dashboard(request):
    if request.user.is_authenticated:
        todo_list = todo.objects.order_by('-date_added')
        template = 'customers/dashboard.html'
        return render (request, template, {'todo_list' : todo_list})
    else :
        return render (request, 'customers/home.html')

@login_required
def addTodo(request):
    if request.method == 'POST' :
        form = addTodo_form(request.POST)
        if form.is_valid():
            topic = form.cleaned_data['topic']
            des = form.cleaned_data['description']
            date = form.cleaned_data['todo_date']
            #user = User.objects.get(username=request.user.username)
            user=request.user
            gta = user.todo_set.create(todo_topic = topic, todo_description = des, todo_date = date)
            message = 'Item Added To Your Todo List'
            return render(request, 'customers/add.html', {'form' : form, 'msg' : message})
    else :
        form = addTodo_form()
    return render(request, 'customers/add.html', {'form' : form})

@login_required
def showForm(request, id):
    a = todo.objects.get(pk=id)
    data_dict = {'topic' : a.todo_topic, 'description' : a.todo_description, 'todo_date' : a.todo_date, 'completed_or_not' : a.completed_or_not}
    form = edit_form(initial = data_dict)
    return render(request, 'customers/edit.html', {'form' : form, 'date_added' : a.date_added})

@login_required
def edit(request, date_added):
    if request.method == 'POST':
        form = edit_form(request.POST)
        if form.is_valid():
            topic = form.cleaned_data['topic']
            des = form.cleaned_data['description']
            date = form.cleaned_data['todo_date']
            status = form.cleaned_data['completed_or_not']
            instance = todo.objects.get(date_added = date_added)
            instance.todo_topic = topic
            instance.todo_description = des
            instance.todo_date = date
            instance.completed_or_not = status
            instance.save(update_fields=['todo_topic', 'todo_description', 'todo_date', 'completed_or_not'])
            message = 'Updated'
            return HttpResponseRedirect(reverse ('dashboard'))

@login_required
def delete(request, id):
    todo.objects.get(pk=id).delete()
    return HttpResponseRedirect(reverse('dashboard'))

forms.朋友

from django import forms

class SignUpForm(forms.Form):
    first_name = forms.CharField(max_length = 20, label = 'First Name', required = True)
    last_name = forms.CharField(max_length = 20, label = 'Last Name', required = True)

    def signup(self, request, user):
        user.first_name : self.cleaned_data['first_name']
        user.last_name : self.cleaned_data['last_name']
        user.save()

class addTodo_form(forms.Form):
    topic = forms.CharField(label = 'Topic', max_length=50, required = True)
    description = forms.CharField(widget=forms.Textarea, label = 'Description', max_length=100)
    todo_date = forms.DateField (label = 'Date', widget=forms.SelectDateWidget)


class edit_form(forms.Form):
    topic = forms.CharField(label = 'Topic', max_length=50, required = True)
    description = forms.CharField(widget=forms.Textarea, label = 'Description', max_length=100)
    todo_date = forms.DateField (label = 'Date', widget=forms.SelectDateWidget)
    completed_or_not = forms.ChoiceField(choices = (
                                            ('Done', 'Done'),
                                            ('Not Done', 'Not Done'),
                                            ))

Project_Directory

project_directory
├───static
│   ├───media
│   ├───static
│   │   ├───css
│   │   └───js
│   └───static-only
│       ├───admin
│       │   ├───css
│       │   │   └───vendor
│       │   │       └───select2
│       │   ├───fonts
│       │   ├───img

│       │   │   └───gis
│       │   └───js
│       │       ├───admin
│       │       └───vendor
│       │           ├───jquery
│       │           ├───select2
│       │           │   └───i18n
│       │           └───xregexp
│       ├───css
│       └───js
└───todo_website
    ├───customers
    │   ├───migrations
    │   │   └───__pycache__
    │   ├───templates
    │   │   ├───account
    │   │   └───customers
    │   └───__pycache__
    └───todo_website
        └───__pycache__

问题是,我使用user1登录并创建了一个待办事项列表然后我退出了。我再次使用user2登录,在那里我看到user1创建的列表已经存在即使我创建了一个新帐户并登录,user1创建的列表也会出现在那里。

答案

您正在检索所有对象。按用户过滤待办事项并仅显示该用户创建的待办事项。

todo_list = todo.objects.filter(user=request.user).order_by('-date_added')

以上是关于如何在Django中为不同的用户创建不同的模型数据库的主要内容,如果未能解决你的问题,请参考以下文章

在 Django 中为特定视图设置用户权限

如何在django中为问题添加多个表单字段类型的选项?

在 Django 中为 BooleanField 使用不同的数据库值

如何在 Django 中从用户模型的字段自动填充和显示数据到来自不同应用程序的另一个模型?

如何在 cakephp 中为不同的模型设置不同的布局

如何在 Django 中为用户模型加载 sql 夹具?