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
< /code>
settings.py hat die App aufgelistet < /p>
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', #
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
< /code>
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
< /code>
Mein [url=viewtopic.php?t=20324]Problem[/url] ist, dass Django nicht funktioniert, da der Fehler lautet, dass Object.All () im ModelViewSet von Klassenanbieter nicht erkennbar ist. Darüber hinaus ist die Zeile von .models enthält Anbieter
Ich habe DRF mit Django, installiert, und aus irgendeinem Grund haben meine ModelViewsets den Zugriff auf die Modelle verloren.[code]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 < /code> settings.py hat die App aufgelistet < /p> 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', # 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 < /code> 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.name < /code> Mein [url=viewtopic.php?t=20324]Problem[/url] ist, dass Django nicht funktioniert, da der Fehler lautet, dass Object.All () im ModelViewSet von Klassenanbieter nicht erkennbar ist. Darüber hinaus ist die Zeile von .models enthält Anbieter [/code] ist nicht genutzt. Wie korrigiere ich das?>
Ich brauche also nur die Ansichten in einem HStack , damit sie die gesamte Breite zur Verfügung nehmen, damit der Speicherplatz gleichmäßig verteilt ist und alle die gleiche Breite haben. struct...
Vor ein paar Tagen haben meine Docker -Container aufgehört, auf das Internet zuzugreifen, den Host neu zu starten, Container wieder aufzubauen, sie neu zu starten oder Docker -Dienst zu starten,...
Ich versuche Scrapy in Django implementieren. Dafür hat mir dieses Thema geholfen. Ich schrotte keine Website. myspider.py :
from scrapers.items import ScrapersItem
Ich habe eine Django-Models.py-Datei, die ich zum Speichern von Informationen in meiner Datenbank verwende. Ich speichere Informationen über Unternehmen und die Länder, in denen sie tätig sind. Die...