Home > Software design >  Django rest framework: All fields for a model not visible in the browseable interface
Django rest framework: All fields for a model not visible in the browseable interface

Time:01-11

I am trying to learn django rest framework by making a simple CRUD expense tracker app. I want to add expenses from the DRF browse-able interface. All the fields required for adding the expense are not visible in the browse-able interface, which then is not allowing me to add new expense objects.

My URLs:

from django.urls import path
from rest_framework.urlpatterns import format_suffix_patterns
from expenses import views

urlpatterns = [
    path('expenses/', views.ExpenseList.as_view()),
    path('expenses/<int:pk>/', views.ExpenseDetail.as_view()),
    path('categories/', views.CategoryList.as_view()),
    path('categories/<int:pk>/', views.CategoryDetail.as_view()),
    path('addexpense/', views.AddExpense.as_view())
]

urlpatterns = format_suffix_patterns(urlpatterns)

My serializers:

from rest_framework import serializers
from .models import Expense, Category


class ExpenseSerializer(serializers.ModelSerializer):
    created_by = serializers.ReadOnlyField(source='created_by.username')
    category = serializers.ReadOnlyField(source='category.name')

    class Meta:
        model = Expense
        fields = ['created_by', 'amount', 'category', 'created_at', 'updated_at']


class CategorySerializer(serializers.ModelSerializer):
    created_by = serializers.ReadOnlyField(source='created_by.username')

    class Meta:
        model = Category
        fields = ['created_by', 'name', 'description', 'created_at', 'updated_at']

My models:

from django.db import models


# Create your models here.

class Category(models.Model):
    created_by = models.ForeignKey('auth.User', related_name='category', on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    name = models.CharField(max_length=256, null=False, blank=False)
    description = models.CharField(max_length=256, null=False, blank=False)


# maybe add bill photo option here
class Expense(models.Model):
    created_by = models.ForeignKey('auth.User', related_name='expense', on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    category = models.ForeignKey(Category, on_delete=models.CASCADE, null=False, blank=False)
    amount = models.DecimalField(decimal_places=2, null=False, blank=False, default=0.00, max_digits=10)

And my views:

from django.shortcuts import render
from expenses.models import Category, Expense
from expenses.serializers import CategorySerializer, ExpenseSerializer
from rest_framework import generics
from rest_framework import permissions
from .permissions import IsOwnerOrReadOnly


# Create your views here.


class ExpenseList(generics.ListAPIView):
    queryset = Expense.objects.all()
    serializer_class = ExpenseSerializer


class AddExpense(generics.CreateAPIView):
    permission_classes = [permissions.IsAuthenticated]
    queryset = Expense.objects.all()
    serializer_class = ExpenseSerializer

    def perform_create(self, serializer):
        serializer.save()


class ExpenseDetail(generics.RetrieveUpdateDestroyAPIView):
    permission_classes = [permissions.IsAuthenticated]
    queryset = Expense.objects.all()
    serializer_class = ExpenseSerializer


class CategoryList(generics.ListCreateAPIView):
    permission_classes = [permissions.IsAuthenticated]
    queryset = Category.objects.all()
    serializer_class = CategorySerializer

    def perform_create(self, serializer):
        serializer.save(created_by=self.request.user)


class CategoryDetail(generics.RetrieveUpdateDestroyAPIView):
    permission_classes = [permissions.IsAuthenticated]
    queryset = Category.objects.all()
    serializer_class = CategorySerializer

This is what I see on the addexpense page right now:

enter image description here

As you can see, I don't see an option to add a category related to the expense.

On trying to add an expense, I get the error message:

Environment:


Request Method: POST
Request URL: http://127.0.0.1:8000/addexpense/

Django Version: 4.0.5
Python Version: 3.10.6
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'rest_framework',
 'expenses']
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 "/usr/local/lib/python3.10/dist-packages/django/db/backends/utils.py", line 89, in _execute
    return self.cursor.execute(sql, params)
  File "/usr/local/lib/python3.10/dist-packages/django/db/backends/sqlite3/base.py", line 477, in execute
    return Database.Cursor.execute(self, query, params)

The above exception (NOT NULL constraint failed: expenses_expense.created_by_id) was the direct cause of the following exception:
  File "/usr/local/lib/python3.10/dist-packages/django/core/handlers/exception.py", line 55, in inner
    response = get_response(request)
  File "/usr/local/lib/python3.10/dist-packages/django/core/handlers/base.py", line 197, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/usr/local/lib/python3.10/dist-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
    return view_func(*args, **kwargs)
  File "/usr/local/lib/python3.10/dist-packages/django/views/generic/base.py", line 84, in view
    return self.dispatch(request, *args, **kwargs)
  File "/home/praxmon/.local/lib/python3.10/site-packages/rest_framework/views.py", line 509, in dispatch
    response = self.handle_exception(exc)
  File "/home/praxmon/.local/lib/python3.10/site-packages/rest_framework/views.py", line 469, in handle_exception
    self.raise_uncaught_exception(exc)
  File "/home/praxmon/.local/lib/python3.10/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception
    raise exc
  File "/home/praxmon/.local/lib/python3.10/site-packages/rest_framework/views.py", line 506, in dispatch
    response = handler(request, *args, **kwargs)
  File "/home/praxmon/.local/lib/python3.10/site-packages/rest_framework/generics.py", line 190, in post
    return self.create(request, *args, **kwargs)
  File "/home/praxmon/.local/lib/python3.10/site-packages/rest_framework/mixins.py", line 19, in create
    self.perform_create(serializer)
  File "/home/praxmon/code/expensetracker/expenses/views.py", line 23, in perform_create
    serializer.save()
  File "/home/praxmon/.local/lib/python3.10/site-packages/rest_framework/serializers.py", line 212, in save
    self.instance = self.create(validated_data)
  File "/home/praxmon/.local/lib/python3.10/site-packages/rest_framework/serializers.py", line 962, in create
    instance = ModelClass._default_manager.create(**validated_data)
  File "/usr/local/lib/python3.10/dist-packages/django/db/models/manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/usr/local/lib/python3.10/dist-packages/django/db/models/query.py", line 514, in create
    obj.save(force_insert=True, using=self.db)
  File "/usr/local/lib/python3.10/dist-packages/django/db/models/base.py", line 806, in save
    self.save_base(
  File "/usr/local/lib/python3.10/dist-packages/django/db/models/base.py", line 857, in save_base
    updated = self._save_table(
  File "/usr/local/lib/python3.10/dist-packages/django/db/models/base.py", line 1000, in _save_table
    results = self._do_insert(
  File "/usr/local/lib/python3.10/dist-packages/django/db/models/base.py", line 1041, in _do_insert
    return manager._insert(
  File "/usr/local/lib/python3.10/dist-packages/django/db/models/manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/usr/local/lib/python3.10/dist-packages/django/db/models/query.py", line 1434, in _insert
    return query.get_compiler(using=using).execute_sql(returning_fields)
  File "/usr/local/lib/python3.10/dist-packages/django/db/models/sql/compiler.py", line 1621, in execute_sql
    cursor.execute(sql, params)
  File "/usr/local/lib/python3.10/dist-packages/django/db/backends/utils.py", line 103, in execute
    return super().execute(sql, params)
  File "/usr/local/lib/python3.10/dist-packages/django/db/backends/utils.py", line 67, in execute
    return self._execute_with_wrappers(
  File "/usr/local/lib/python3.10/dist-packages/django/db/backends/utils.py", line 80, in _execute_with_wrappers
    return executor(sql, params, many, context)
  File "/usr/local/lib/python3.10/dist-packages/django/db/backends/utils.py", line 84, in _execute
    with self.db.wrap_database_errors:
  File "/usr/local/lib/python3.10/dist-packages/django/db/utils.py", line 91, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "/usr/local/lib/python3.10/dist-packages/django/db/backends/utils.py", line 89, in _execute
    return self.cursor.execute(sql, params)
  File "/usr/local/lib/python3.10/dist-packages/django/db/backends/sqlite3/base.py", line 477, in execute
    return Database.Cursor.execute(self, query, params)

Exception Type: IntegrityError at /addexpense/
Exception Value: NOT NULL constraint failed: expenses_expense.created_by_id

My question: Why are all the fields not visible on this page? How do I add them? Is there something wrong with my serializer?

CodePudding user response:

Try this:

created_by = serializers.CharField(source='created_by.username', read_only=True)

category = serializers.CharField(source='category.name', read_only=True)

CodePudding user response:

There are a few things that I noticed.

Firstly, you "don't see an option to add a category related to the expense."
However if you go to your ExpenseSerializer you will see that you have set the category field to be a ReadOnlyField. If you remove that line, you should be able to set the ID of the category that you want and it should work.

class ExpenseSerializer(serializers.ModelSerializer):
    created_by = serializers.ReadOnlyField(source='created_by.username')
    category = serializers.ReadOnlyField(source='category.name')

    class Meta:
        model = Expense
        fields = ['created_by', 'amount', 'category', 'created_at', 'updated_at']

Secondly, the error you are receiving has nothing to do with the category but has to do with the creation of your Expense object. At the very end it says:

Exception Type: IntegrityError at /addexpense/
Exception Value: NOT NULL constraint failed: expenses_expense.created_by_id

So what is happening is that you are trying to create an expense but you haven't set the created_by field. This might be because your AddExpense view doesn't really do anything with it's perform_create function. (You aren't setting the user like you do in the perform_create of CategoryList)

  • Related