英文:
TypeError: Field 'id' expected a number but got DeferredAttribute object at 0x000002B6ADE878D0
问题
I am using a queryset in Django- whenever I run the server, it gives an error.
TypeError: Field 'id' expected a number but got <django.db.models.query_utils.DeferredAttribute object at 0x000002B6ADE878D0
It is something about the queryset of my form that causes the error.
我在Django中使用一个查询集,每当我运行服务器时,都会出现错误。
TypeError: 字段 'id' 期望一个数字,但得到了 <django.db.models.query_utils.DeferredAttribute 对象 at 0x000002B6ADE878D0>
这与我的表单的查询集有关,导致了错误。
英文:
I am using a queryset in Django- whenever I run the server, it gives an error.
TypeError: Field 'id' expected a number but got <django.db.models.query_utils.DeferredAttribute object at 0x000002B6ADE878D0
It is something about the queryset of my form that causes the error.
I don't know whether its an issue with my models.py or my forms.py
I tried looking up this DeferredAttribute object on Google, but I didn't really see any answer that works for me.
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')
CustomUser model:
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})
答案1
得分: 2
A statement like:
form = TaskForm(get_user_model())
does not make much sense. Indeed, get_user_model()
returns a reference to the user class, not to a user object (like the logged in user). You can construct such a form with:
from django.contrib.auth.decorators import login_required
@login_required
def task_create(request):
form = TaskForm(request.user)
context = {'form': form}
html_form = render_to_string('tasks/partial_task_create.html',
context,
request=request,
)
return JsonResponse({'html_form': html_form})
Here we use the @login_required
decorator to prevent users who are not logged in from accessing the view. This is useful, since in that case request.user
is not a user object.
or in the CreateView
, you can override the get_form_kwargs
method to:
from django.contrib.auth.mixins import LoginRequiredMixin
class TaskCreateView(LoginRequiredMixin, CreateView):
template_name = 'create.html'
form_class = TaskForm
success_url = reverse_lazy('task_list')
def get_form_kwargs(self):
kwargs = super().get_form_kwargs()
kwargs.update(user=self.request.user)
return kwargs
In order to enforce a user to be logged in, we then use a LoginRequiredMixin
mixin.
英文:
A statement like:
<pre><code>form = TaskForm(<s>get_user_model()</s>)</code></pre>
does not make much sense. Indeed, get_user_model()
returns a reference to the user class, not to a user object (like the logged in user). You can construct such a form with:
<pre><code>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})</code></pre>
Here we use the @login_required
decorator [Django-doc] to prevent user that are not logged in to access the view. This is useful, since in that case request.user
is not a user object.
or in the CreateView
[Django-doc] you can override the get_form_kwargs
method [Django-doc] to :
<pre><code>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</code></pre>
In order to enforce a user to be logged in, we then use a LoginRequiredMixin
mixin [Django-doc].
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论