title: FieldError at /answer/ Cannot resolve keyword 'i' into field. Choices are: add_time, answer, detail, id,
body: <p>believe it or not I've been here for 4 hours trying to get this to work, so yes, I've been trying to make a question and answer site, currently trying to make an answer form so I can send in answers to the question that I am currently viewing, trying to get the id of the question so I can attach the answer into that, but I'm getting this error, I'm sure I wrote 'id' but it thinks I wrote 'i'... What? Anyway here is the traceback, please tell me what I am doing wrong, thanks.</p>
  <p>Traceback:</p>
  <pre><code>Environment:
  
  
  Request Method: POST
  Request URL: http://127.0.0.1:8000/answer/
  
  Django Version: 4.0.4
  Python Version: 3.8.10
  Installed Applications:
  ['django.contrib.humanize',
   'forum',
   'django.contrib.admin',
   'django.contrib.auth',
   'django.contrib.contenttypes',
   'crispy_forms',
   'django.contrib.sessions',
   'django.contrib.messages',
   'django.contrib.staticfiles',
   'users',
   'vote']
  Installed Middleware:
  ['django.middleware.security.SecurityMiddleware',
   'django.contrib.sessions.middleware.SessionMiddleware',
   'django.middleware.common.CommonMiddleware',
   'django.middleware.csrf.CsrfViewMiddleware',
   'django.contrib.auth.middleware.AuthenticationMiddleware',
   'django.contrib.messages.middleware.MessageMiddleware',
   'django.middleware.clickjacking.XFrameOptionsMiddleware']
  
  
  
  Traceback (most recent call last):
    File &quot;/home/titsnium/.local/lib/python3.8/site-packages/django/core/handlers/exception.py&quot;, line 55, in inner
      response = get_response(request)
    File &quot;/home/titsnium/.local/lib/python3.8/site-packages/django/core/handlers/base.py&quot;, line 197, in _get_response
      response = wrapped_callback(request, *callback_args, **callback_kwargs)
    File &quot;/home/titsnium/.local/lib/python3.8/site-packages/django/views/generic/base.py&quot;, line 84, in view
      return self.dispatch(request, *args, **kwargs)
    File &quot;/home/titsnium/.local/lib/python3.8/site-packages/django/views/generic/base.py&quot;, line 119, in dispatch
      return handler(request, *args, **kwargs)
    File &quot;/home/titsnium/.local/lib/python3.8/site-packages/django/views/generic/edit.py&quot;, line 184, in post
      return super().post(request, *args, **kwargs)
    File &quot;/home/titsnium/.local/lib/python3.8/site-packages/django/views/generic/edit.py&quot;, line 153, in post
      return self.form_valid(form)
    File &quot;/home/titsnium/Documents/eduzec/forum/views.py&quot;, line 78, in form_valid
      form.question = Question.objects.get('id')
    File &quot;/home/titsnium/.local/lib/python3.8/site-packages/django/db/models/manager.py&quot;, line 85, in manager_method
      return getattr(self.get_queryset(), name)(*args, **kwargs)
    File &quot;/home/titsnium/.local/lib/python3.8/site-packages/django/db/models/query.py&quot;, line 482, in get
      clone = self._chain() if self.query.combinator else self.filter(*args, **kwargs)
    File &quot;/home/titsnium/.local/lib/python3.8/site-packages/django/db/models/query.py&quot;, line 1071, in filter
      return self._filter_or_exclude(False, args, kwargs)
    File &quot;/home/titsnium/.local/lib/python3.8/site-packages/django/db/models/query.py&quot;, line 1089, in _filter_or_exclude
      clone._filter_or_exclude_inplace(negate, args, kwargs)
    File &quot;/home/titsnium/.local/lib/python3.8/site-packages/django/db/models/query.py&quot;, line 1096, in _filter_or_exclude_inplace
      self._query.add_q(Q(*args, **kwargs))
    File &quot;/home/titsnium/.local/lib/python3.8/site-packages/django/db/models/sql/query.py&quot;, line 1502, in add_q
      clause, _ = self._add_q(q_object, self.used_aliases)
    File &quot;/home/titsnium/.local/lib/python3.8/site-packages/django/db/models/sql/query.py&quot;, line 1532, in _add_q
      child_clause, needed_inner = self.build_filter(
    File &quot;/home/titsnium/.local/lib/python3.8/site-packages/django/db/models/sql/query.py&quot;, line 1377, in build_filter
      lookups, parts, reffed_expression = self.solve_lookup_type(arg)
    File &quot;/home/titsnium/.local/lib/python3.8/site-packages/django/db/models/sql/query.py&quot;, line 1187, in solve_lookup_type
      _, field, _, lookup_parts = self.names_to_path(lookup_splitted, self.get_meta())
    File &quot;/home/titsnium/.local/lib/python3.8/site-packages/django/db/models/sql/query.py&quot;, line 1677, in names_to_path
      raise FieldError(
  
  Exception Type: FieldError at /answer/
  Exception Value: Cannot resolve keyword 'i' into field. Choices are: add_time, answer, detail, id, num_vote_down, num_vote_up, slug, tags, title, user, user_id, vote_score, votes
  </code></pre>
  <p>views.py:</p>
  <pre><code>from django.shortcuts import render, get_object_or_404
  from django.http import JsonResponse, HttpResponseRedirect
  from django.views import View
  from django.views.generic.list import ListView
  from django.views.generic import DetailView, CreateView
  from django.contrib.auth.mixins import LoginRequiredMixin
  from django.db.models import Count
  from requests import request
  from .forms import QuestionForm, AnswerForm
  from django.contrib.messages.views import SuccessMessageMixin
  from django.urls import reverse, reverse_lazy
  from . import models
  from .models import Question, Answer, Comment
  
  from vote.models import UP, DOWN
  from .utilities import cast_vote, save_text_help
  
  class QuestionsView(ListView):
      model = Question
      template_name = 'forum/questions.html'
      context_object_name = &quot;quests&quot;
      paginate_by = 5
  
      def get_queryset(self):
          qs = super(QuestionsView, self).get_queryset()
  
          search = self.request.GET.get('q')
          if search:
              qs = qs.filter(title__icontains=search)
  
          qs = qs.order_by(&quot;-id&quot;)
          qs = qs.annotate(count_of_answers=Count('answer'))
          return qs
  
  class QuestionDetailView(DetailView):
      model = Question
      template_name = 'forum/detail.html'
      context_object_name = 'quest'
  
      def get_context_data(self, **kwargs):
          context = super(QuestionDetailView, self).get_context_data(**kwargs)
  
          context['tags'] = self.object.tags.split(',')
          answers = Answer.objects.filter(question=self.object).order_by('-vote_score')    
          comments = []
          for answer in answers:
              comments.append(Comment.objects.filter(answer=answer))
          context['answers_comments'] = zip(answers, comments)
          
          return context
  
      def get_queryset(self):
          qs = super(QuestionDetailView, self).get_queryset()
          qs = qs.annotate(count_of_answers=Count('answer'))
  
          return qs
      
  
  class AskForm(SuccessMessageMixin , CreateView):
      template_name = 'forum/ask-question.html'
      model = Question
      form_class = QuestionForm
      success_message = 'Success!'
      
      
      def form_valid(self, form):
          form.instance.user = self.request.user
          form.save()
          return super(AskForm, self).form_valid(form)
      
  class AnswerForm(SuccessMessageMixin, CreateView):
      template_name = 'forum/answer-question.html'
      model = Answer
      form_class = AnswerForm
      success_message = 'Success!'
      
      def form_valid(self, form):
          form.question = Question.objects.get('id')
          form.instance.user = self.request.user
          form.save()
          return super(AskForm, self).form_valid(form)
  
  class WriteCommentAnswerView(View):
      def post(self, request):
          text=request.POST['text']
          id=request.POST['id']
          text_type = request.POST['type']
          user=request.user
  
          if text_type == &quot;comment&quot;:
              return render(request, 'forum/includes/single_comment.html', {'comment': save_text_help(text, id, text_type, user)})
          else:
              return render(request, 'forum/includes/single_answer.html', {'answer': save_text_help(text, id, text_type, user)})
  
  class SaveVoteView(LoginRequiredMixin, View):
      def post(self, request):
          id = request.POST['id']
          user_id = request.user.id
          vote_to = request.POST['vote_to']
          vote_type = request.POST['vote_type']
  
          return JsonResponse({'bool': cast_vote(vote_type, vote_to, user_id, id)})
  </code></pre>
  <p>models.py:</p>
  <pre><code>from time import time
  from django.conf import settings
  from django.db import models
  from vote.models import VoteModel
  from django.urls import reverse
  from django.utils.text import slugify
  from users.models import CustomUser
  
  # This is the question model
  class Question(VoteModel, models.Model):
      user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True)
      title = models.CharField(max_length=30)
      slug = models.SlugField(unique=True)
      detail = models.TextField()
      tags = models.TextField(default='')
      add_time = models.DateTimeField(auto_now_add=True)
      
      def get_absolute_url(self):
          return f&quot;/questions/&quot;
  
      def __str__(self):
          return self.title
  
  
  # This is the answer model
  
  class Answer(VoteModel, models.Model):
      question = models.ForeignKey(Question, on_delete=models.CASCADE)
      user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
      detail = models.TextField()
      add_time = models.DateTimeField(auto_now_add=True)
  
      def __str__(self):
          return self.detail
  
  
  class Comment(models.Model):
      answer = models.ForeignKey(Answer, on_delete=models.CASCADE)
      user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='comment_user')
      comment = models.TextField(default='')
      add_time = models.DateTimeField(auto_now_add=True)
  
      def __str__(self):
          return f&quot;Comment on \&quot;{self.answer}\&quot; by {self.user}&quot;
  </code></pre>
  <p>urls.py:</p>
  <pre><code>from django.urls import path
  from . import views
  
  urlpatterns = [
      path('questions/', views.QuestionsView.as_view(), name='questions'),
      path('ask/', views.AskForm.as_view(), name='ask'),
      path('answer/', views.AnswerForm.as_view(), name='answer'),
      path('detail/&lt;pk&gt;', views.QuestionDetailView.as_view(), name='detail'),
      path('save-text', views.WriteCommentAnswerView.as_view(), name='save-text'),
      path('save-vote', views.SaveVoteView.as_view(), name='save-vote'),
  ]
  </code></pre>
  <p>forms.py:</p>
  <pre><code>from django import forms
  from django.forms import ModelForm
  from .models import Answer, Question
  
  class QuestionForm(ModelForm):
      class Meta:
          model = Question
          fields = ['title', 'detail', 'tags']
          exclude = ('user', 'add_time')
          
  class AnswerForm(ModelForm):
      class Meta:
          model = Answer
          fields = ['detail']
          exclude = ('user', 'add_time')
  </code></pre>