When does the ‘django.core.exceptions.FieldError’ error occur?

To comprehend the resolution for this issue, we initiated a project named ‘Db’.

Starting the Project Folder

To start the project use this command

django-admin startproject Db
cd Db

To start the app use this command

python manage.py startapp app

Now add this app to the ‘settings.py’

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'app'
]

Setting Necessary Files

models.py: Below code defines a Django model named “People” with two fields: “name” as a character field with a maximum length of 255 characters, and “age” as an integer field. This model represents a data structure for storing information about people, such as their name and age, in a Django web application.

Python




from django.db import models
  
# Create your models here.
class People(models.Model):
    name = models.CharField(max_length=255)
    age = models.IntegerField()


views.py: Below code defines a view function, `get_people_by_name`, which takes a request and a name parameter. It retrieves a person’s data from the `People` model based on the provided name and returns an HTTP response displaying the person’s name and age. If the record doesn’t exist, it raises an exception.

Python




from django.shortcuts import render
from django.http import HttpResponse
from django.core.exceptions import ObjectDoesNotExist
from .models import People
  
def get_people_by_name(request,name):
    people = People.objects.get(fullName=name)
    return HttpResponse(f"{people.name} and {people.age}")


Run the server with the help of following command:

python3 manage.py runserver

Output

FieldError in Django

In this article, we will address the resolution of the ‘django.core.exceptions.FieldError’ in Django. This particular error, ‘django.core.exceptions.FieldError’, points to a problem associated with a field in your model or query. The discussion will focus on identifying and rectifying this error through practical examples.

Similar Reads

What is ‘django.core.exceptions.FieldError’

The `django.core.exceptions.FieldError` occurs in a Django application when there is a discrepancy or misapplication of a field. This issue can arise due to misspelled field names, incorrect references in queries, attempts to use fields not included in models, or forgetting to migrate changes in the database....

When does the ‘django.core.exceptions.FieldError’ error occur?

To comprehend the resolution for this issue, we initiated a project named ‘Db’....

How to fix django.core.exceptions.FieldError?

...

Conclusion

...