Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: AttributeError: type object 'GroupModel' has no attribute '_meta'

Tags:

django

I am new in Django, in my code when I requested from postman I got this error, may someone help me what's wrong in my code?

model:

from django.db import models

class GroupModel(object):
    title=models.CharField(max_length=20)
    description = models.CharField()

    class Meta:
        db_table = 'group'
    def __str__(self):
        return self

serializer:

from rest_framework import serializers
from .models import GroupModel

class GroupSerializer(serializers.ModelSerializer):
    print('hello4')
    class Meta:
        model = GroupModel
        fields = '__all__'

views:

from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
from .serializer import GroupSerializer
from .models import GroupModel
from rest_framework.decorators import api_view
from rest_framework import status
@api_view(['POST'])
def InsetGroup(request):
     data = GroupSerializer(data = request.data)

     if request.method == 'POST':
         if data.is_valid():
             data.save()
             return JsonResponse('saved was saccessfull', safe = False)
         return JsonResponse(data.errors, status = status.HTTP_400_BAD_REQUEST, safe = False)
like image 901
Me Sa Avatar asked Jul 31 '26 10:07

Me Sa


1 Answers

Models in Django need to be a subclass of the Model class [Django-doc]:

from django.db import models

class GroupModel(models.Model):
    title=models.CharField(max_length=20)
    description = models.CharField()

    def __str__(self):
        return self.title

    class Meta:
        db_table = 'group'

Your __str__ should also return a string, so for example self.title, not self, since that is a GroupModel object, not a string.

like image 139
Willem Van Onsem Avatar answered Aug 02 '26 09:08

Willem Van Onsem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!