gpt4 book ai didi

python - 类型错误 : Field 'id' expected a number but got DeferredAttribute object at 0x000002B6ADE878D0

转载 作者:行者123 更新时间:2023-12-02 04:46:07 30 4
gpt4 key购买 nike

我在 Django 中使用查询集 - 每当我运行服务器时,它都会给出错误。

TypeError: Field 'id' expected a number but got <django.db.models.query_utils.DeferredAttribute object at 0x000002B6ADE878D0

我的表单的查询集导致了错误。

我不知道这是否是我的 models.py 或我的 forms.py 的问题我尝试在 Google 上查找这个 DeferredAttribute 对象,但我并没有真正看到任何适合我的答案。

forms.py:

from .models import Task, Categories
from django import forms
from django.forms import ModelForm
from django.db.models import Q

class TaskForm(ModelForm):

task_title = forms.CharField(max_length=100)
task_description = forms.CharField(widget=forms.Textarea)
due_date = forms.DateTimeField()
is_completed = forms.BooleanField()
#categories = forms.ModelChoiceField(empty_label="---None---")

class Meta:
model = Task
fields = ['task_title', 'task_description', 'due_date', 'is_completed', 'categories', 'parent']

def __init__(self, user, *args, **kwargs):
# Get all the categories from the database for that specific user
super(TaskForm, self).__init__(*args, **kwargs)

# It is something about this line that causes the error
self.fields['categories'].queryset = Categories.objects.filter(Q(user_id__isnull=True) | Q(user_id=user.id))

models.py:

from django.db import models
from django.db.models import Q
from users.models import CustomUser
from django.urls import reverse
from django.contrib.auth import get_user_model


class Categories(models.Model):
category_type = models.CharField(max_length=50)
user = models.ForeignKey(CustomUser, null = True, on_delete=models.CASCADE)

def __str__(self):
return '%s ' % (self.category_type)

def get_absolute_url(self):
return reverse('task_list')


class Task(models.Model):
task_title = models.CharField(max_length=100)
task_description = models.TextField()
date_added = models.DateTimeField(auto_now_add=True)
due_date = models.DateTimeField()
is_completed = models.BooleanField(default=False)
user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE)

categories = models.ForeignKey('Categories', on_delete=models.CASCADE)
parent = models.ForeignKey("self", on_delete=models.CASCADE)

class Meta:
verbose_name = "Task"
verbose_name_plural = "Tasks"

def __str__(self):
return '%s ID: %s' % (self.task_title, self.last_name)

def get_absolute_url(self):
return reverse('task_detail')

自定义用户模型:

from django.contrib.auth.models import AbstractUser
from django.db import models

class CustomUser(AbstractUser):
nationality = models.CharField(null=True, blank=True, max_length=60)

views.py:

from django.views.generic import TemplateView
from django.views.generic.edit import UpdateView, DeleteView , CreateView
from django.urls import reverse_lazy
from .forms import TaskForm
from django.contrib.auth import get_user_model
from django.http import JsonResponse
from django.template.loader import render_to_string

class TaskListView(TemplateView):
template_name = "tasks.html"

# This is the actual create view I am for using now
class TaskCreateView(CreateView):
template_name = 'create.html'
form_class = TaskForm(get_user_model())
success_url = reverse_lazy('task_list')

# I am using this for a modal, but its not working so I fell back to the normal create view
def task_create(request):
form = TaskForm(get_user_model())
context = {'form': form}
html_form = render_to_string('tasks/partial_task_create.html',
context,
request=request,
)
return JsonResponse({'html_form': html_form})

最佳答案

类似的声明:

form = TaskForm(<s>get_user_model()</s>)

没有多大意义。事实上,get_user_model() 返回对用户的引用,而不是对用户对象(如登录用户)的引用。您可以使用以下方式构建这样的表单:

from django.contrib.auth.decorators import login_required

<b>@login_required</b>
def task_create(request):
form = TaskForm(<b>request.user</b>)
context = {'form': form}
html_form = render_to_string('tasks/partial_task_create.html',
context,
request=request,
)
return JsonResponse({'html_form': html_form})

这里我们使用@login_required decorator [Django-doc]防止未登录的用户访问该 View 。这很有用,因为在这种情况下 request.user 不是用户对象。

或在CreateView [Django-doc]中您可以覆盖 get_form_kwargs method [Django-doc]至:

from django.contrib.auth.mixins import LoginRequiredMixin

class TaskCreateView(<b>LoginRequiredMixin</b>, CreateView):
template_name = 'create.html'
form_class = <b>TaskForm</b>
success_url = reverse_lazy('task_list')

def get_form_kwargs(self):
kwargs = super().get_form_kwargs()
<b>kwargs.update(user=self.request.user)</b>
return kwargs

为了强制用户登录,我们使用 LoginRequiredMixin mixin [Django-doc] .

关于python - 类型错误 : Field 'id' expected a number but got DeferredAttribute object at 0x000002B6ADE878D0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59615964/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com