1

I'm getting started with django, I've been following the official tutorial and I've run into an issue. I have this block of code:

def vote(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    try:
        selected_choice = question.choice_set.get(pk=request.POST["choice"])
    except (KeyError, Choice.DoesNotExist):
        # Redisplay the question voting form.
        return render(
            request,
            "polls/detail.html",
            {
                "question": question,
                "error_message": "You didn't select a choice.",
            },
        )
    else:
        selected_choice.votes += 1
        selected_choice.save()
        # Always return an HttpResponseRedirect after successfully dealing
        # with POST data. This prevents data from being posted twice if a
        # user hits the Back button.
        return HttpResponseRedirect(reverse("polls:results", args=(question.id,)))

The code works perfectly fine, however, for some reason VS Code highlights the ID and CHOICE_SET attributes. Here's my models.py:

class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField("date published")

    def __str__(self) -> str:
        return self.question_text

    def was_published_recently(self):
        return self.pub_date >= timezone.now() - datetime.timedelta(days=1)


class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

    def __str__(self) -> str:
        return self.choice_text

I suppose that there's an issue with VS Code because as I said the code works just fine and I can run it. I just really wanna remove the red highlighting and fix it.

1 Answers1

0

I suspect it's because your VS Code can't find where your django package was installed on your disk (so that VS Code knows your class Question, but not the class models.Model from which Question inherits, so the IDE complains about not knowing attributes which are only defined in models.Model). Since I don't work with VS Code, I can't say precisely what steps to take; you probably need to somehow adjust the environment variable "PYTHONPATH" which your VS Code uses; similarly perhaps to here: https://stackoverflow.com/a/57742434/17093315

David S.
  • 457
  • 2
  • 13