TypeError: Field 'id' expected a number but got DeferredAttribute object at 0x000002B6ADE878D0

huangapple go评论101阅读模式
英文:

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 &#39;id&#39; expected a number but got &lt;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=&quot;---None---&quot;)

    class Meta:
        model = Task
        fields = [&#39;task_title&#39;, &#39;task_description&#39;, &#39;due_date&#39;, &#39;is_completed&#39;, &#39;categories&#39;, &#39;parent&#39;]        

    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[&#39;categories&#39;].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 &#39;%s &#39; % (self.category_type)

    def get_absolute_url(self):
        return reverse(&#39;task_list&#39;)


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(&#39;Categories&#39;, on_delete=models.CASCADE)
    parent = models.ForeignKey(&quot;self&quot;, on_delete=models.CASCADE)

    class Meta:
        verbose_name = &quot;Task&quot;
        verbose_name_plural = &quot;Tasks&quot;

    def __str__(self):
        return &#39;%s ID: %s&#39; % (self.task_title, self.last_name)

    def get_absolute_url(self):
        return reverse(&#39;task_detail&#39;)

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 = &quot;tasks.html&quot;

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

# 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 = {&#39;form&#39;: form}
    html_form = render_to_string(&#39;tasks/partial_task_create.html&#39;,
        context,
        request=request,
    )
    return JsonResponse({&#39;html_form&#39;: 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()
    &lt;b&gt;kwargs.update(user=self.request.user)&lt;/b&gt;
    return kwargs&lt;/code&gt;&lt;/pre&gt;

In order to enforce a user to be logged in, we then use a LoginRequiredMixin mixin [Django-doc].

huangapple
  • 本文由 发表于 2020年1月7日 00:49:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/59615964.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定