[Python] views have lost access to models in Django

Discussão em 'Python' iniciado por Stack, Maio 2, 2025.

  1. Stack

    Stack Membro Participativo

    I have DRF installed with Django, and for some reason my ModelViewSets have lost access to the models.

    My views.py

    from rest_framework.decorators import api_view, permission_classes
    from rest_framework.response import Response
    from rest_framework.permissions import IsAdminUser
    from django.contrib.auth import get_user_model
    from rest_framework.viewsets import ModelViewSet
    from rest_framework.permissions import IsAuthenticated
    from .models import *
    from .serializers import *
    from .permissions import *

    # Get custom User model
    CustomUser = get_user_model()

    class VendorViewSet(ModelViewSet):
    queryset = Vendor.objects.all()
    serializer_class = VendorSerializer
    permission_classes = [IsAuthenticated, IsVendor] # Vendors only


    Settings.py does have the app listed

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

    #Third-Party Apps
    'rest_framework',
    'rest_framework.authtoken',
    'rest_framework_simplejwt.token_blacklist',
    'django_filters',
    'corsheaders',
    'allauth',
    'allauth.account',
    'allauth.socialaccount',
    'channels', # Required for real-time notifications
    'mfa', #MFA Support

    # Project Apps
    'VMP.apps.VmpConfig', #<--That is the project
    ]


    apps.py

    from django.apps import AppConfig


    class VmpConfig(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'VMP'

    def ready(self):
    import VMP.signals


    models.py

    from django.db import models
    from django.conf import settings
    from django.contrib.auth.models import User, AbstractBaseUser, BaseUserManager
    from django.utils.timezone import timedelta, now
    from django.core.exceptions import ValidationError

    # File validation function
    def validate_file_type(value):
    allowed_types = ["application/pdf", "application/msword", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"]
    if value.content_type not in allowed_types:
    raise ValidationError("Only PDF and Word documents are allowed.")

    class CustomUserManager(BaseUserManager):
    """Manager for CustomUser"""

    def create_user(self, email, password=None, role="customer"):
    if not email:
    raise ValueError("Users must have an email address")
    user = self.model(email=self.normalize_email(email), role=role)
    user.set_password(password)
    user.save(using=self._db)
    return user

    def create_superuser(self, email, password=None):
    user = self.create_user(email, password, role="admin")
    user.is_staff = True
    user.is_superuser = True
    user.save(using=self._db)
    return user

    class CustomUser(AbstractBaseUser):
    """Custom user model using email authentication"""
    ROLE_CHOICES = [
    ("vendor", "Vendor"),
    ("customer", "Customer"),
    ("admin", "Admin"),
    ]

    email = models.EmailField(unique=True)
    role = models.CharField(max_length=10, choices=ROLE_CHOICES, default="customer")
    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False) # Required for Django admin
    is_superuser = models.BooleanField(default=False) # Required for superuser checks

    objects = CustomUserManager() # Use the custom manager

    USERNAME_FIELD = "email" # Set email as the primary login field
    REQUIRED_FIELDS = ["role"]

    def __str__(self):
    return self.email

    class Vendor(models.Model):
    name = models.CharField(max_length=255)
    email = models.EmailField(unique=True)
    categories = models.ManyToManyField('Tag', related_name="vendors")
    subscription_plan = models.CharField(max_length=50, choices=[
    ('free', 'Free'),
    ('premium', 'Premium'),
    ('enterprise', 'Enterprise')
    ])
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
    return self.name


    my problem is that Django is failing to operate because the error is saying that object.all() in the ModelViewSet is not recognizable by class Vendor. In addition, the line from .models include Vendor is unused.

    how do I rectify this? Thanks!

    Continue reading...

Compartilhe esta Página