I am trying to filter list of products linked with a user. I want to display only current users product instead of listing all.
I tried this
class ProductCreateList(generics.ListCreateAPIView):
serializer_class = ProductSerializer
def get_queryset(self):
user = self.request.user
return Product.objects.filter(user=user.id)
serializers.py
class ProductSerializer(serializers.ModelSerializer):
class Meta:
model = Product
fields = ['id', 'user', 'name', 'imgUrl', 'selling_price', 'actual_price', 'quantity', 'get_profit']
models.py
class Product(models.Model):
user = models.ForeignKey('accounts.Account', on_delete=models.CASCADE, default=1)
name = models.CharField(max_length=100, null=True, blank=True)
imgUrl = models.TextField(default='')
selling_price = models.FloatField(null=True, blank=True)
actual_price = models.FloatField(null=True, blank=True)
quantity = models.IntegerField()
I got [] object when I tried to execute the endpoint. What's my mistake here?
There are a few mistakes, mainly in your view. I have done the following:
models.py
from django.db import models
from django.contrib.auth import get_user_model
class Product(models.Model):
user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, default=1)
name = models.CharField(max_length=100, null=True, blank=True)
imgUrl = models.TextField(default='')
selling_price = models.FloatField(null=True, blank=True)
actual_price = models.FloatField(null=True, blank=True)
quantity = models.IntegerField()
class Meta:
db_table = 'product'
serializers.py: Remove 'get_profit' field or implement a serializermethodfield
from rest_framework import serializers
from core.models import Product
class ProductSerializer(serializers.ModelSerializer):
class Meta:
model = Product
fields = ['id', 'user', 'name', 'imgUrl', 'selling_price', 'actual_price', 'quantity']
views.py: To filter by user, guarantee that the user is Authenticated and has auth permission by using authentication_classes and permission_classes. Use the filter_queryset hook, to filter your queryset by user.
from rest_framework.authentication import SessionAuthentication, BasicAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework import generics
from core.api.serializers import ProductSerializer
from core.models import Product
class ProductCreateList(generics.ListCreateAPIView):
authentication_classes = [SessionAuthentication, BasicAuthentication]
permission_classes = [IsAuthenticated]
serializer_class = ProductSerializer
queryset = Product.objects.all()
def filter_queryset(self, queryset):
queryset = queryset.filter(user=self.request.user)
return super().filter_queryset(queryset)
I extended my User model with a new model just called UserExtended:
# Django imports
from django.db import models
from django.contrib.auth.models import User
class UserExtended(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
crm_guid = models.UUIDField(unique=True)
security_q1 = models.CharField(max_length=255, blank=True, null=True)
security_a1 = models.CharField(max_length=255, blank=True, null=True)
security_q2 = models.CharField(max_length=255, blank=True, null=True)
security_a2 = models.CharField(max_length=255, blank=True, null=True)
attempts = models.SmallIntegerField(blank=False, null=False, default=0)
key = models.CharField(max_length=255, blank=True, null=True)
key_expires = models.DateTimeField(blank=True, null=True)
method = models.CharField(max_length=4, blank=True, null=True)
class Meta:
db_table = 'auth_user_extended'
I was hoping by just doing that some Django magic would take care of the rest and I wouldn't have to change my views.py or serializers.py. But when I send a request to the end-point I get:
[api] django.core.exceptions.ImproperlyConfigured: Field name `guid` is not valid for model `User`.
So it does apparently need to be specified. I've been looking at the documentation and similar SO questions to find an answer.
This is what I have for my views.py:
# Django imports
from django.contrib.auth.models import User
# Third party imports
from rest_framework import generics
from rest_framework.permissions import IsAdminUser
# App imports
from users.serializers import UserSerializer
class UsersListCreateView(generics.ListCreateAPIView):
permission_classes = [IsAdminUser]
serializer_class = UserSerializer
def get_queryset(self):
queryset = User.objects.all()
email = self.request.query_params.get('email')
username = self.request.query_params.get('username')
if email:
queryset = queryset.filter(email=email)
if username:
queryset = queryset.filter(username=username)
return queryset
class UserRetrieveUpdateDeleteView(generics.RetrieveUpdateDestroyAPIView):
permission_classes = [IsAdminUser]
queryset = User.objects.all()
serializer_class = UserSerializer
For my serializers.py I just have:
# Django imports
from django.contrib.auth.models import User
from users.models import UserExtended
from django.contrib.auth.hashers import make_password
# Third party imports
from rest_framework import serializers
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ['id', 'last_login', 'first_name',
'last_name', 'username', 'email', 'is_active', 'guid']
If I change model = User to model = UserExtemded, then I'll get an error like:
[api] django.core.exceptions.ImproperlyConfigured: Field name `last_login` is not valid for model `UserExtended`.
I'm thinking I need to do one of two things:
Create a serializer class for both models and call them both from the views.py. I've toyed with this a little by trying to pass a list or tuple in of serializer_class (apparently singular for a reason).
Setup the relationship in the serializers.py. I'm looking into this now.
Suggestions for how to resolve this issue?
You need a different serializer and viewset to operate on UserExtended
My suggestion would be keep old serializer as is and create UserExtendedSerializer
class UserExtendedSerializer(serializers.ModelSerializer):
user = UserSerializer(many=False, read_only=True)
class Meta:
model = UserExtended
fields = "__all__"
and viewset would be simply:
class UserExtendedViewSet(ModelViewSet):
serializer_class = UserExtendedSerializer
queryset = UserExtended.objects.all()
this should solve your issue
I am trying to join two tables and serialize them as an API. I have referred to the docs of the Django rest framework and tried a code. It didn't work. Could not resolve the problem even after trying so many times. I am trying to get a JSON file like
{
'album_name': 'The Grey Album',
'artist': 'Danger Mouse',
'tracks': [
{'order': 1, 'title': 'Public Service Announcement'},
{'order': 2, 'title': 'What More Can I Say'},
{'order': 3, 'title': 'Encore'},
...
],
}
But what I get is
{
'album_name': 'The Grey Album',
'artist': 'Danger Mouse',
}
This is the model file I am using
Model.py
from django.db import models
from django.contrib.auth.models import User
STATUS_CHOICE = (
('simple', 'simple'),
('intermediate', 'intermediate'),
)
class Quiz(models.Model):
quiz_name = models.CharField(max_length=1000)
video_id = models.ForeignKey("youtube.Youtube", on_delete=models.CASCADE)
questions_count = models.IntegerField(default=0)
description = models.CharField(max_length=70, null=True)
created = models.DateTimeField(auto_now_add=True)
slug = models.SlugField()
pass_mark = models.IntegerField()
class Meta:
ordering = ['created']
def __str__(self):
return self.quiz_name
class Category(models.Model):
category = models.CharField(max_length=20, choices=STATUS_CHOICE, default='simple')
quiz_id = models.ForeignKey(Quiz, on_delete=models.CASCADE)
def __str__(self):
return self.category
class Questions(models.Model):
quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE)
question = models.CharField(max_length=1000)
mark = models.IntegerField()
def __str__(self):
return self.question
class Choice(models.Model):
question = models.ForeignKey(Questions, on_delete=models.CASCADE)
choice_1 = models.CharField(max_length=1000)
choice_2 = models.CharField(max_length=1000)
choice_3 = models.CharField(max_length=1000)
choice_4 = models.CharField(max_length=1000)
answer = models.CharField(max_length=1000, default=choice_1)
def __str__(self):
return self.answer
Serializer.py
from rest_framework import serializers
from rest_framework.permissions import IsAuthenticated
from .models import Category, Quiz, Questions, Choice
from django.contrib.auth import authenticate
from django.contrib.auth.hashers import make_password
class QuizSerializer(serializers.ModelSerializer):
class Meta:
model = Quiz
fields = '__all__'
class QuestionsSerializer(serializers.ModelSerializer):
class Meta:
model = Questions
fields = '__all__'
class ChoiceSerializer(serializers.ModelSerializer):
class Meta:
model = Choice
fields = '__all__'
class CategorySerializer(serializers.ModelSerializer):
quiz_name = QuizSerializer(read_only=True)
class Meta:
model = Category
fields = ['id','category','quiz_name']
View.py
from rest_framework import generics, permissions, mixins
from rest_framework.response import Response
from .serializer import CategorySerializer
from .models import Category
class ViewQuiz(generics.ListCreateAPIView):
permission_classes = [
permissions.AllowAny,
]
queryset = Category.objects.all()
serializer_class = CategorySerializer
def list(self, request):
queryset = self.get_queryset()
serializer = CategorySerializer(queryset, many=True)
print(serializer.data)
return Response(serializer.data)
class CategorySerializer(serializers.ModelSerializer):
class Meta:
model = Category
fields = ['id','category','quiz_id']
def to_representation(self, instance):
response = super().to_representation(instance)
response['quiz_id'] = QuizSerializer(instance.quiz_id).data
return response
This will produce the result you want, I made an change in how the serializer represent the data. I have some of my serializer doing the same, but my views are working a bit different from yours.
Looks like you are trying to get questions serializes in quiz.
To do that you need to:
1. In Questions model include related_name in quiz field:
class Questions(models.Model):
quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE, related_name="questions")
question = models.CharField(max_length=1000)
mark = models.IntegerField()
def __str__(self):
return self.question
In QuizSerializer include questions field and set many to True:
class QuizSerializer(serializers.ModelSerializer):
questions = QuestionsSerializer(source="questions", many=True)
class Meta:
model = Quiz
fields = ("questions", ... other needed fields)
Include source attribute in QuizSerializer in CategorySerializer:
class CategorySerializer(serializers.ModelSerializer):
quiz_name = QuizSerializer(read_only=True, source="quiz_id")
class Meta:
model = Category
fields = ['id', 'category', 'quiz_name']
Your Quiz was not serialized because the relation between Category and Quiz in tables are called quiz_id but your field is called quiz_name, so the framework did not know where it should take quiz, because it was looking at quiz_name relation which does not exist.
Hey Guys this is my first project in Django, I am trying to get my 'foreign keys' field into my API with Django Rest framework.
I am trying to do a Post a product. since i cannot see input fields i am stuck here.
It might be something very simpel, i might didn’t see it.
*******UPDATE********
As requested, have put an image here for more details of what i actually want to achieve.
In the image below is what i WANT in my api to show and i do get it like this, all my field like how i want them (apart from that i get category twice , one in digits also)
But if u take a closer look down below, the POST form is limited to the attributes of the product Model class itself. So i can not do an actual post from the frontend side.
in the serializers
If i comment the fields out i do get down below my fields to POST, yeah.. but When i post i get digits in my API rather than the names of the foreign keys
So notice i get all the field that i need for my frontend in order to handle the post function. But then i get digits in the api instead
I hope i made it more clear than before.. :)
Thank you in advance
serializers.py
from rest_framework import serializers
from rest_framework.serializers import ModelSerializer
from .models import *
from django.contrib.auth.models import User
from rest_framework.authtoken.models import Token
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id', 'username', 'password')
extra_kwargs = {'password':{'write_only':True,'required':True}}
def create(self, validated_data):
user = User.objects.create_user(**validated_data)
print(user)
Token.objects.create(user=user)
return user
class ProductSerializer(serializers.ModelSerializer):
product_id = serializers.CharField(source='product.url', read_only=True)
category_name = serializers.CharField(source='category.name', read_only=True)
user_id = serializers.CharField(source='user.id', read_only=True)
subject = serializers.CharField(source='subject.subject', read_only=True)
condition = serializers.CharField(source='condition.condition', read_only=True)
major = serializers.CharField(source='major.major', read_only=True)
state = serializers.CharField(source='state.state', read_only=True)
school = serializers.CharField(source='school.school', read_only=True)
location = serializers.CharField(source='location.location', read_only=True)
class Meta:
model = Product
fields = '__all__'
class SubjectSerializer(serializers.ModelSerializer):
model = Subject
fields = '__all__'
class CategorySerializer(serializers.ModelSerializer):
class Meta:
model = Category
fields = ('url', 'id', 'name')
class StateSerializer(serializers.ModelSerializer):
# state_count = serializers.SerializerMethodField()
class Meta:
model = State
fields = ['id', 'url', 'state']
# def get_state_count(self, obj):
# if State.objects.count()
# return obj.children().count()
# return 0
class ConditionSerializer(serializers.ModelSerializer):
class Meta:
model = Condition
fields = '__all__'
class MajorSerializer(serializers.ModelSerializer):
class Meta:
model = Major
fields = '__all__'
class LocationSerializer(serializers.ModelSerializer):
class Meta:
model = Location
fields = '__all__'
class FaqSerializer(serializers.ModelSerializer):
class Meta:
model = Faq
fields = '__all__'
views
from django.shortcuts import render
from rest_framework import viewsets, status
from rest_framework.decorators import api_view
from .models import Product, State, Category, Subject
from django.contrib.auth.models import User
from .serializer import *
from rest_framework.permissions import IsAuthenticated,AllowAny
from rest_framework.authentication import TokenAuthentication
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.filters import SearchFilter, OrderingFilter
from rest_framework.response import Response
from rest_framework.authtoken.views import ObtainAuthToken
from rest_framework.authtoken.models import Token
from rest_framework.pagination import LimitOffsetPagination
class ProductViewPagination(LimitOffsetPagination):
default_limit = 8
max_limit = 12
class ProductViewSet(viewsets.ModelViewSet):
queryset = Product.objects.all()
serializer_class = ProductSerializer
product_count = Product.objects.count()
authentication_classes = (TokenAuthentication,)
permission_calsses = (IsAuthenticated,)
filter_backends = (DjangoFilterBackend, SearchFilter, OrderingFilter)
search_fields = ('=title','=category__name','=user__id','=subject__subject', '=major__major', '=condition__condition', '=location__location')
pagination_class = ProductViewPagination
# def delete(self,request,*args,**kwargs):
# response = {'message':'product cannot be updated like this'}
# return Response(response, status = statu.HTTP_400_BAD_REQUEST)
# def create(self,request,*args,**kwargs):
# response = {'message':'product cannot be created like this'}
# return Response(response, status = status.HTTP_400_BAD_REQUEST)
class CategoryViewSet(viewsets.ModelViewSet):
queryset = Category.objects.all()
serializer_class = CategorySerializer
permission_calsses = (IsAuthenticated,)
filter_backends = (DjangoFilterBackend, SearchFilter, OrderingFilter)
search_fields = ('=name', 'id')
class SubjectViewSet(viewsets.ModelViewSet):
queryset = Subject.objects.all()
serializer_class = SubjectSerializer
filter_backends = (DjangoFilterBackend, SearchFilter, OrderingFilter)
search_fields = ('=subject',)
class ConditionViewSet(viewsets.ModelViewSet):
queryset = Condition.objects.all()
serializer_class = ConditionSerializer
filter_backends = (DjangoFilterBackend, SearchFilter, OrderingFilter)
search_fields = ('=condition',)
class MajorViewSet(viewsets.ModelViewSet):
queryset = Major.objects.all()
serializer_class = MajorSerializer
filter_backends = (DjangoFilterBackend, SearchFilter, OrderingFilter)
search_fields = ('=major',)
class LocationViewSet(viewsets.ModelViewSet):
queryset = Location.objects.all()
serializer_class = LocationSerializer
filter_backends = (DjangoFilterBackend, SearchFilter, OrderingFilter)
search_fields = ('=location',)
# class StateCountViewSet(viewsets.ModelViewSet):
# queryset = State.objects.all()
# serializer_class = StateSerializer
# permission_calsses = (IsAuthenticated,)
# def get(self, request, format=None):
# state_count = State.objects.count()
# content = {'state_count' : state_count}
# return Response(content)
class StateViewSet(viewsets.ModelViewSet):
queryset = State.objects.all()
serializer_class = StateSerializer
permission_calsses = (IsAuthenticated,)
class FaqViewSet(viewsets.ModelViewSet):
queryset = Faq.objects.all()
serializer_class = FaqSerializer
permission_calsses = (AllowAny,)
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
authentication_classes = (TokenAuthentication,)
permission_classes = (AllowAny, )
# #api_view(['POST',])
# def registration_view(request):
# if request.method == 'POST':
# serializer = RegristrationSerializer(data=request.data)
# data = {}
# if serializer.is_valid():
# user = serialzer.save()
# data['response'] = "successfully registered a new userrrR"
# data['username'] = user.username
# else:
# data = serializer.errors
# return user
urls.py
from django.conf.urls import url, include
from django.contrib.auth.models import User
from rest_framework import routers, serializers, viewsets
from django.urls import path
from restapi.views import *
# class UserSerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
# model = User
# fields = ['id', 'url', 'username', 'email', 'is_staff']
# # ViewSets define the view behavior.
# class UserViewSet(viewsets.ModelViewSet):
# queryset = User.objects.all()
# serializer_class = UserSerializer
# Routers provide an easy way of automatically determining the URL conf.
router = routers.DefaultRouter()
router.register('users', UserViewSet)
router.register('product', ProductViewSet)
router.register('category', CategoryViewSet)
router.register('state', StateViewSet)
#router.register('stateCount', StateCountViewSet)
router.register('subject', SubjectViewSet)
router.register('major', MajorViewSet)
router.register('condition', ConditionViewSet)
router.register('location', LocationViewSet)
router.register('faq', FaqViewSet)
urlpatterns = [
path('', include(router.urls)),
path('api-auth/', include('rest_framework.urls', namespace='rest_framework'))
#path('state/count/:state_id', StateCountViewSet, name='states-count')
]
admin.py
from django.contrib import admin
from .models import *
admin.site.register(Product)
admin.site.register(Category)
admin.site.register(Subject)
admin.site.register(State)
admin.site.register(Major)
admin.site.register(Condition)
admin.site.register(Location)
admin.site.register(Faq)
model.py
from django.db import models
from django.contrib.auth.models import User
# class User(models.Model):
# id_user = models.DecimalField(max_digits=10, decimal_places=2, null=True)
# def __str__(self):
# return self.id_user
class Faq(models.Model):
question = models.CharField(max_length = 400, null = True,)
answer = models.CharField(max_length = 900, null = True,)
def __str__(self):
return self.question
class Category(models.Model):
name = models.CharField(max_length = 200, null = True,)
def __str__(self):
return self.name
class State(models.Model):
STATE_CHOICES = [('Ordered', 'Ordered'), ('Pending', 'Pending'),
('Placed', 'Placed')
]
state = models.CharField(max_length = 200, null = True,
choices = STATE_CHOICES)
def __str__(self):
return self.state
class Subject(models.Model):
SUBJECT_CHOICES=[('Mathematics','Mathematics'),('Algoritmes','Algoritmes'),('Analyses','Analyses'),('Informatica','Informatica'),]
subject=models.CharField(max_length=200,null=True,choices=SUBJECT_CHOICES)
def __str__(self):return self.subject
class Major(models.Model):
MAJOR_CHOICES = (
('IT','IT'),
('Marketing','Marketing'),
('DIFF','DIFF'),
)
major = models.CharField(max_length=200,choices=MAJOR_CHOICES, null=True)
def __str__(self):return self.major
class Condition(models.Model):
CONDITION_CHOICES = [
('New','New'),
('Used','Used'),
]
condition = models.CharField(max_length=200,choices=CONDITION_CHOICES, null=True)
def __str__(self):return self.condition
class Location(models.Model):
LOCATION_CHOICES = [
('Brussel','Brussel'),
('Leuven','Leuven'),
('Gent','Gent'),
('Antwerpen','Antwerpen'),
]
location = models.CharField(max_length=200,choices=LOCATION_CHOICES, null=True)
def __str__(self):return self.location
class Product(models.Model):
user = models.ForeignKey(User,null=True, on_delete=models.SET_NULL)
state = models.ForeignKey(State, null=True, on_delete=models.SET_NULL)
category = models.ForeignKey(Category, null=True, on_delete=models.SET_NULL)
subject = models.ForeignKey(Subject, null=True, on_delete=models.SET_NULL)
major = models.ForeignKey(Major, null=True, on_delete=models.SET_NULL)
condition = models.ForeignKey(Condition, null=True, on_delete=models.SET_NULL)
location = models.ForeignKey(Location, null=True, on_delete=models.SET_NULL)
title = models.CharField(max_length=200)
description = models.TextField(max_length=800, null=True)
price = models.DecimalField(max_digits=10, decimal_places=2, null=True)
#image = models.ImageField(upload_to='post_image', blank=True, width_field=None, height_field=None, max_length=100,)
date_created = models.DateTimeField(auto_now_add=True, null=True)
class Meta:
unique_together = (('user','title'),)
index_together = (('user','title'),)
SCHOOL_CHOICES = (
('Erasmushogeschool | EHB',(
('Campus Kaai', 'Campus Kaai'),
('Campus Bloemberg', 'Campus Bloemberg'),
)),
('Vrije Universiteit Brussel | VUB',(
('Campus Jette', 'Campus Jette'),
('Campus Schaarbeek', 'Campus Schaarbeek'),
)),
('Katholieke universiteit leuven | KUL',(
('KUL Gent', 'KUL Gent'),
('Campus Antwerpen', 'Campus Antwerpen'),
)),
)
school = models.CharField(max_length=50, choices=SCHOOL_CHOICES, null=True)
# MAJOR_CHOICES = (
# ('IT','IT'),
# ('Marketing','Marketing'),
# ('DIFF','DIFF'),
# )
# major = models.CharField(max_length=200,choices=MAJOR_CHOICES, null=True)
# SUBJECT_CHOICES = [
# ('Mathematics','Mathematics'),
# ('Algoritmes','Algoritmes'),
# ('Analyses','Analyses'),
# ]
# subject = models.CharField(max_length=200,choices=SUBJECT_CHOICES, null=True)
# CONDITION_CHOICES = [
# ('New','New'),
# ('Used','Used'),
# ]
# condition = models.CharField(max_length=200,choices=CONDITION_CHOICES, null=True)
# LOCATION_CHOICES = [
# ('Brussel','Brussel'),
# ('Leuven','Leuven'),
# ('Gent','Gent'),
# ('Antwerpen','Antwerpen'),
# ]
# location = models.CharField(max_length=200,choices=LOCATION_CHOICES, null=True)
def __str__(self):
return self.title
I registred Category admin in models.py. I added that model in Post model via ForenKey. But when i log into admin console i cannot see my Categories, I just see Category Object(1), Category Object(2) and so on.
I will provide you a print screen and a code.
http://prntscr.com/nxt25y
instead if Japanese Kitchen or any other category (im working blog for chef),
i see Category Object, the one that i highlighted on printscreen.
I think its not a big deal but i didnt worked on django for quite some time so i forgot a lot.
Can you spot a mistake?
Thanks guys
from django.utils import timezone
from django.contrib.auth.models import User
from django.urls import reverse
from django.utils.text import slugify
from ckeditor_uploader.fields import RichTextUploadingField
class Category(models.Model):
name = models.CharField(max_length=150)
slug = models.SlugField(max_length=150)
class Meta:
ordering = ('name',)
verbose_name = 'catergory'
verbose_name_plural = 'catergories'
def __str__(self):
return self.name
class Post(models.Model):
title = models.CharField(max_length=100)
slug = models.SlugField(
help_text="A short label, generally used in URLs.", default='', max_length=100)
category = models.ForeignKey(
Category, on_delete=models.CASCADE, default='New category')
image = models.ImageField(default='default.jpg', upload_to='profile_pics')
content = RichTextUploadingField(blank=True, null=True)
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
class Meta:
ordering = ['-date_posted']
def save(self, *args, **kwargs):
self.slug = slugify(self.title)
super(Post, self).save(*args, **kwargs)
def get_absolute_url(self):
return reverse('detail', kwargs={'slug': self.slug})
def __str__(self):
return self.title
this is admin.py
from .models import Post, Category
from django.forms import ModelForm
from django.contrib.admin import ModelAdmin
from suit_ckeditor.widgets import CKEditorWidget
class PostForm(ModelForm):
class Meta:
widgets = {
'name': CKEditorWidget(editor_options={'startupFocus': True})
}
class CategoryAdmin(admin.ModelAdmin):
list_display = ('name', 'slug')
prepopulated_fields = {'slug': ('name',)}
admin.site.register(Category, CategoryAdmin)
class PostAdmin(admin.ModelAdmin):
form = PostForm
list_display = ['title', 'slug', 'date_posted', 'author']
list_filter = ['title', 'date_posted']
prepopulated_fields = {'slug': ('title',)}
admin.site.register(Post, PostAdmin)
You need to override __str__ method in your models to handle what you intend to display on admin.
class Category(models.Model):
name = models.CharField(max_length=150)
slug = models.SlugField(max_length=150)
class Meta:
ordering = ('name',)
verbose_name = 'catergory'
verbose_name_plural = 'catergories'
def __str__(self):
return self.name