我正在处理一个Todo列表,该列表具有单独的用户和他们自己的列表。 最初,我将models.py设置为:
from django.db import models
from django.contrib.auth.models import User
class Todo(models.Model):
text = models.CharField(max_length=40, default='Test User')
complete = models.BooleanField(default = False)
task_priority = models.CharField(max_length=40, default='high')
def __str__(self):
return self.text
但是,当我尝试将单个用户与其自己的todotask(文本字段)集合及其优先级和状态链接在一起时。
我在这样的字段中添加了一个:
from django.db import models
from django.contrib.auth.models import User
class Todo(models.Model):
user = models.OneToOneField(User,on_delete=models.CASCADE,primary_key='user_id') #new
text = models.CharField(max_length=40, default='Test User')
complete = models.BooleanField(default = False)
task_priority = models.CharField(max_length=40, default='high')
def __str__(self):
return self.text
它抛出了这样的错误:
FieldError位于/ 无法将关键字“ id”解析为字段。选项包括:完整,任务优先级,文本,用户,用户ID
我不完全理解一对一字段的概念,在困惑的天气中在线查看教程,我需要制作另一个表并将其链接到Todo表或使用主键添加另一个字段?
帮我理解这个概念。 预先感谢。
编辑: views.py文件:
from django.shortcuts import render, redirect
from .models import Todo
from .form import TodoForm,ContactForm
import datetime
from django.conf import settings
from django.utils import timezone
from django.views.decorators.http import require_POST
from django.core.mail import send_mail, BadHeaderError
from django.http import HttpResponse, HttpResponseRedirect
import json
def index(request):
todo_list = Todo.objects.order_by('id')
form = TodoForm()
mydate = datetime.datetime.now()
context = {'todo_list': todo_list, 'form': form, 'mydate':mydate}
return render(request,'todo/index.html',context)
def login(request):
return render(request, 'todo/login.html')
@require_POST
def addTodo(request):
form = TodoForm(request.POST)
text_input = form.get_cleaned_data['text']
priority_input = form.get_cleaned_data['task_priority']
if form.is_valid():
new_todo = Todo(text = text_input, task_priority = priority_input)
# new_todo = Todo(text = request.POST['text'])
new_todo.save()
return redirect('index')
def completeTodo(request, todo_id):
todo = Todo.objects.get(pk=todo_id)
todo.complete = True
todo.save()
return redirect('index')
def deleteCompleted(request):
Todo.objects.filter(complete__exact=True).delete()
return redirect('index')
def deleteAll(request):
Todo.objects.all().delete()
return redirect('index')
def emailView(request):
todo = Todo.objects.all();
task_list = []
status_list = []
for item in todo:
stritem=str(item)
task_list.append(stritem)
if item.complete == True:
status_list.append('complete')
else:
status_list.append('incomplete')
if request.method == 'GET':
form = ContactForm()
else:
form = ContactForm(request.POST)
if form.is_valid():
from_email = form.cleaned_data['from_email']
message = form.cleaned_data['message']
#maillist = Todo.objects.all()
email_list=dict(zip(task_list,status_list))
strlist = json.dumps(email_list)
content = message + strlist
try:
send_mail('Todo List', content ,settings.EMAIL_HOST_USER,[from_email])
except BadHeaderError:
return HttpResponse('Invalid header found.')
return redirect('success')
return render(request, "email.html", {'form': form})
def successView(request):
return HttpResponse('Success! Thank you for your message.')
新模型。py:
from django.db import models
from django.contrib.auth.models import User
class Todo(models.Model):
user = models.OneToOneField(User,on_delete=models.CASCADE)
text = models.CharField(max_length=40, default="")
complete = models.BooleanField(default = False)
task_priority = models.CharField(max_length=40, default='high')
def __str__(self):
return self.text
遇到
在/ add NOT NULL约束处的IntegrityError失败:todo_todo.user_id
答案 0 :(得分:1)
此:
user = models.OneToOneField(User,on_delete=models.CASCADE,primary_key='user_id')
根本没有按照您的想法去做。 primary_key
需要一个布尔值,而不是字段名,并且与该关系完全无关。由于字符串'user_id'
不为空,因此将其解释为True,并等同于:
user = models.OneToOneField(User,on_delete=models.CASCADE,primary_key=True)
,这意味着user
现在是Todo模型的主键。这不是你想要的。
删除该primary_key
子句。