Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Get product color in color filter by Category wise
I am trying to get a specific category products by category slug.I have Color model,Product model and product variation model in shop app. class Colour(models.Model): title = models.CharField(max_length=100) color_code = models.CharField(max_length=50,null=True) class Product(models.Model): product_name = models.CharField(max_length=100,unique=True) slug = models.SlugField(max_length=100,unique=True) content = RichTextUploadingField() price = models.IntegerField() images = models.ImageField(upload_to='photos/products') is_available = models.BooleanField(default=True) category = models.ForeignKey(Category, on_delete=models.CASCADE,related_name="procat") created_date = models.DateTimeField(auto_now_add=True) modified_date = models.DateTimeField(auto_now=True) is_featured = models.BooleanField() class ProductVaraiant(models.Model): product = models.ForeignKey(Product,on_delete=models.CASCADE) color = models.ForeignKey(Colour,on_delete=models.CASCADE,blank=True, null=True) size = models.ForeignKey(Size, on_delete=models.CASCADE,blank=True, null=True) brand = models.ForeignKey(Brand,on_delete=models.CASCADE,blank=True, null=True) amount_in_stock = models.IntegerField() class Meta: constraints = [ models.UniqueConstraint( fields=['product', 'color', 'size','brand'], name='unique_prod_color_size_combo' In my views.py, def shop(request,category_slug=None): categories = None products = None if category_slug != None: categories = get_object_or_404(Category,slug = category_slug) products = Product.objects.filter(category=categories,is_available=True).order_by('id') variation = ProductVaraiant.objects.filter(product__category = categories) print(variation) # color = color.objects.all() products_count = products.count() else: products = Product.objects.all().filter(is_available=True).order_by('id') products_count = products.count() variation = ProductVaraiant.objects.all() print(variation) context = { 'products' : products, 'products_count' : products_count, 'variation' : variation } return render(request,'shop/shop.html',context) my category model, class Category(MPTTModel): parent = TreeForeignKey('self',blank=True,null=True,related_name='children',on_delete=models.CASCADE) category_name = models.CharField(max_length=200,unique=True) category_img = models.ImageField(upload_to='photos/categories',blank=True) slug = models.SlugField(max_length=100,unique=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def img_preview(self): return mark_safe('<img src = "{url}" width = "50" height = "50"/>'.format( url = self.category_img.url )) def __str__(self): return … -
The scheduler seems to be running under uWSGI, but threads have disabled.You must run uWSGI with the --enable-threads option for the scheduler to work
I'm deploying django app to pythonanywhere where i used APScheduler for automatically send expire mail whenever subscription end date exceed. I don't know how to enable threads, so that my web app runs perfectly on pythonanywhere. -
Comparing Django project structure to ruby on rails
After some years developing web apps using ruby on rails, I decided to give Django a try, however it seems that I'm missing something, which is how to structure large project, or any project in general. For example, in rails we have a models folder which contains model classes, each in a separate ruby file, a controllers folder which contains controller classes, again each in a separate ruby file. However, in Django it split the project into independent apps, which can be installed independently in other Django project, each app has a models.py file which contains all the models classes, a views.py file which contain all the views functions. But then how to group functions in views like rails? That is one controller per each model. In general how to structure my project when it contains one large app that can't be separated into multiple independent apps? I want for example to have a view index function for each model, but how to do this if all functions are in one file? If my project is about selling cars for example. I should have index function that maps to /cars, another index function to map to /users, etc... I searched … -
Import models from different apps to admin Django
I'm trying to create an admin page for my project including app1 and app2 myproject settings.py urls.py admin.py app1 app2 In myproject/urls.py urlpatterns = [ path('admin/', admin.site.urls), path('app1/', include('app1.urls')), path('app2/', include('app2.urls')), ] In myproject/admin.py from django.contrib import admin from app1.models import User from app2.models import Manager, Employee, Task, Template admin.site.register(User) admin.site.register(Manager) admin.site.register(Employee) admin.site.register(Task) admin.site.register(Template) Why doesn't my admin page import any models at all? Thanks! -
Cache Auto Generated Django Admin Routes
I want to cache the sql queries result in Redis DB in the django admin.AdminSite autogenerated for registered admin.ModelAdmin's I am able to cache a custom url using cache_page and add it to CustomAdminSite I have installed Django debug toolbar to view cache requests. The custom url is getting cached. I am unable to cache other auto generated admin routes. Would it be possible to cache auto generated admin routes too? -
convert python/django built-in class "calendar" to local calendar (Persian)
I created a html calendar using built-in calendar class in Django , now I have to convert it to local calendar "Persian", I tried using django-jalali-date package but couldn't get success result . and another issue is prevmonth and next month buttons which redirect user to not found page. please advice how to handle those issues in utils.py: class Calendar(HTMLCalendar): def __init__(self, year=None, month=None): self.year = year self.month = month super(Calendar, self).__init__() # formats a day as a td # filter events by day def formatday(self, day, events): events_per_day = events.filter(time_start__day=day) d = '' for event in events_per_day: d += f'<li> {event.title} </li>' if day != 0: return f"<td><span class='date'>{day}</span><ul> {d} </ul></td>" return '<td></td>' # formats a week as a tr def formatweek(self, theweek, events): week = '' for d, weekday in theweek: week += self.formatday(d, events) return f'<tr> {week} </tr>' # formats a month as a table # filter events by year and month def formatmonth(self, withyear=True): events = tb_order.objects.filter(time_start__year=self.year, time_start__month=self.month) cal = f'<table border="0" cellpadding="0" cellspacing="0" class="calendar">\n' cal += f'{self.formatmonthname(self.year, self.month, withyear=withyear)}\n' cal += f'{self.formatweekheader()}\n' for week in self.monthdays2calendar(self.year, self.month): cal += f'{self.formatweek(week, events)}\n' return cal in Urls: path('testcal/',views.CalendarView.as_view(),name="cal"), in views.py : class CalendarView(generic.ListView): model = tb_order template_name … -
Why parentheses are not used with function in html template when model method is called in django?
I would like to know while in html templating process why model method does not use parentheses like normally we use it in views and it is being called direcly like varible e.g. class Main(models.Model): value=models.BigIntegerField(null=True, blank=True) #Model field variable = 505 # model variable def fun(self): return True # model function (method) The html template {% extends 'base.html' %} {% block content %} {{user.main.value}} it's value <br> {{user.main.fun}} it's function (why no parentheses here like user.main.fun()) <br> {{user.main.variable}} it's variable <br> {% endblock %} If this question is not good then tell me to delete but please do not down vote.Thank You. -
Docker socket is not accesible in Docker.prod
I have the following docker-compose file which builds and starts 4 containers one of them is Django container for which I am mounting the /var/run/docker.sock in volumes so that Django container can access the host docker engine. version: '3.8' services: web: build: context: ./app dockerfile: Dockerfile.prod command: gunicorn hello_django.wsgi:application --bind 0.0.0.0:8000 volumes: - static_volume:/home/app/web/staticfiles - media_volume:/home/app/web/mediafiles - /var/run/docker.sock:/var/run/docker.sock expose: - 8000 env_file: - ./.env.prod depends_on: - postgresdb restart: always postgresdb: container_name: postgresdb image: timescale/timescaledb:latest-pg11 volumes: - ./:/imports - postgres_data:/var/lib/postgresql/data/ command: 'postgres -cshared_preload_libraries=timescaledb' ports: - "5432:5432" env_file: - ./.env.prod.db restart: always nginx: build: ./nginx volumes: - static_volume:/home/app/web/staticfiles - media_volume:/home/app/web/mediafiles ports: - 80:80 depends_on: - web restart: always volttron1: container_name: volttron1 hostname: volttron1 build: context: ./volttron dockerfile: Dockerfile image: volttron/volttron:develop volumes: - ./volttron/platform_config.yml:/platform_config.yml - ./volttron/configs:/home/volttron/configs - ./volttron/volttronThingCerts:/home/volttron/volttronThingCerts environment: - CONFIG=/home/volttron/configs - LOCAL_USER_ID=1000 network_mode: host restart: always mem_limit: 700m cpus: 1.5 volumes: postgres_data: static_volume: media_volume: The content of the Docker.prod for django web container is following ########### # BUILDER # ########### # pull official base image FROM python:3.9.6-alpine as builder # set work directory WORKDIR /usr/src/app # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install psycopg2 dependencies RUN apk update && apk add postgresql-dev gcc python3-dev musl-dev RUN apk add … -
Django LocMemCache not caching data
I've got my LocMemCache set up in my settings.py: 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'TIMEOUT': None, }, I have then built a function decorator: from django.core.cache import cache def cache_function(func): def cache_result(*args, **kwargs): cache_key = '{},{}'.format( func.__name__, hashlib.sha256('{},{},{}'.format(func.__name__, args, kwargs).encode()).hexdigest(), ) try: result = cache.get(cache_key) if result is not None: print('function is cached') return result result = func(*args, **kwargs) timeout = 60 cache.set(cache_key, result, timeout) return result except Exception as exc: print('CACHE ERROR:') print(exc) return func(*args, **kwargs) return cache_result Then I've got my function: @cache_function def function_to_test(): return 'this is a test value' However, it seems like the cache is never used, no matter how many times I call the function. I know this because my print statement ('function is cached') is never printed. I even put a debugger there to see what happens, and it just seems like the cache is empty What am I doing wrong? -
Saleor admin dashborad Having trouble due to cors error?
Graphql API is working fine with the storefront but is not able to work with the admin dashboard on how to disable the cors policy for a certain domain. I am using the docker configuration for that. // api docker congig environment: - JAEGER_AGENT_HOST=jaeger - STOREFRONT_URL=https://react-storefront.dingpack.com/ - DASHBOARD_URL=https://admin.dingpack.com/ - ALLOWED_HOSTS=api.dingpack.com,localhost,api,140.238.230.137,admin.dingpack.com,react-app-checkout.dingpack.com,react-app-checkout.dingpack.com - ALLOWED_CLIENT_HOSTS=admin.dingpack.com,react-storefront.dingpack.com,react-app-checkout.dingpack.com,api.dingpack.com,localhost - ALLOWED_GRAPHQL_ORIGINS=admin.dingpack.com,react-storefront.dingpack.com,react-app-checkout.dingpack.com,api.dingpack.com,localhost // nginx conf are location / { add_header 'Access-Control-Allow-Origin' '*' always; proxy_pass http://localhost:8000/; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; include /home/ashish/Downloads/projects/saleor/core-api/uwsgi_params; include /etc/nginx/snippets/cors.conf; include /etc/nginx/snippets/cors-wildcard.conf; } location = /favicon.ico { log_not_found off; access_log off; } location = /robots.txt { access_log off; log_not_found off; } location ~ /\. { deny all; access_log off; log_not_found off; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/api.dingpack.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/api.dingpack.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host = api.dingpack.com) { return 301 https://$host$request_uri; } # managed by Certbot response from admin api query [ failed ] response from store-frontend [ pass ] i am expecting that api cors error will not occur for admin dashboard as well. -
How do we solve the quotation inside of a quotation problem while using django?
I can't use the same type of string in the same type of string in HTML I have a static folder in the root dierctory of my django project and I was changing a downloaded template's link to match the django project. Here is the HTML attribute style="background-image: url(\"{% static 'assets/img/why-us.png' %}\")" as you can see I tried using backslash () to resolve the problem but it was no avail. -
Using inline formsets with manytomany relationship
I have AbstractUser and Relationship models. The user model has a manytomany field through relationship model class User(AbstractUser): username = models.CharField( verbose_name="username", max_length=256, unique=True) first_name = models.CharField(verbose_name="first name", max_length=30) last_name = models.CharField(verbose_name="last name", max_length=30) slug = models.SlugField(max_length=255, unique=True, blank=True) date_joined = models.DateTimeField( verbose_name="joined date", auto_now_add=True) friends = models.ManyToManyField('self', through='Relationship', symmetrical=False, related_name='following') is_active = models.BooleanField(default=True) is_superuser = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) def __str__(self): return str(self.username) def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.username) super().save(*args, **kwargs) class Relationship(models.Model): from_person = models.ForeignKey( User, related_name='from_people', on_delete=models.CASCADE) to_person = models.ForeignKey( User, related_name='to_people', on_delete=models.CASCADE) def __str__(self): return f"from {self.from_person} to {self.to_person}" How to create an inline formset with fields=['from_person' and 'to_person'] to assign users to each others That is what I tried to do but I couldn't have both fields because of fk_name Any help please! def staff_profile_view(request): user = User.objects.get_by_natural_key(request.user) AssignFriendsFormSet = inlineformset_factory( User, Relationship, fk_name='from_person', fields=('to_person', 'from_person',)) formset = AssignFriendsFormSet( queryset=Relationship.objects.none(), instance=user) if request.method == "POST": formset = AssignFriendsFormSet(request.POST, instance=user) if formset.is_valid(): formset.save() return render(request, 'staff_profile.html',{"formset": formset}) -
Filter data in django admin inline create view
this is my first post here and im hoping to find a solution for my situation: The thing is... I got a admin inline who show the relate info of a model. by this, i can see which contract_product belongs to current client. When im creating a new object in the inline, aka click in the following button enter image description here I cant see a list of option as follow: enter image description here The problem is... the client must see only their products, but here i see all products for all type of clients? PS: product and client has a direct relationship. Hope someone can understand my problem and helps me! Theres a kt if thing i've tried far now, but nothing succesful to talk about -
Django how to perform a query to get all occourences where object 1 has a foreign key on object 2 and a certain object 2 has a property
Okay, so I've got a question about performing queries. So, I've got one object called Job. A Job as a foreign key on StatusUpdate, meaning a single job can have many StatusUpdates. Basically, I need to get all Jobs with a LAST StatusUpdate with a certain property. I know that I can easily get all Jobs that have any StatusUpdate with a certain property like this: Job.objects.all().filter(statusupdate__status="Certain Property") But this will get jobs that have any StatusUpdate with status of certain property. I want to get only jobs with a last StatusUpdate with a status of certain property. Is it possible to do this with a single query? I read the through the Django documentation and couldn't find anything. Thank you! Diego -
How to make a queryset with a value coming from an javascript function?
When the user clicks a checkbox, the value will be sent to a javascript function that will take the value and check if has any occurrence in the database asynchronously, but I don't know if it is possible in Django, I have seen serializers, but I don't think it will work because it's not only catching data from the database, but making a query. There is a way of doing this? requisite = requisite.objects.filter(requisite__discipline__id=33) the code above will retrieve the data I want, but I need to get this number from the code below <input class="form-check-input" type="checkbox" value="{{ discipline.id }}" id="flexCheckDefault{{ discipline.name }}" onclick="checkRequisite(this.defaultValue)"> -
How do I create a view in Django to display only the images with a specific taggit tag?
I have followed this tutorial to create a website. I have expanded my page beyond the tutorial and am now trying to create a view that only uses the images of the tag 'fav'. I am trying to use the tag as a sort of favourite button, and the only display those images in a bootstrap carousel. All I have, to go by, is this different view that only uses the images of the tag you click on. class PhotoTagListView(PhotoListView): template_name = 'photoapp/taglist.html' def get_tag(self): return self.kwargs.get('tag') def get_queryset(self): return self.model.objects.filter(tags__slug=self.get_tag()) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["tag"] = self.get_tag() return context But since I don't really understand it, it isn't really any help. How do I create a view for a specific tag? Or is there even a solution to this problem entirely feasible in html or js? Tried to modify the other view, but since I don't know enough about django and python it naturally didn't work. My modification: class CarouselView(PhotoListView): template_name = 'photoapp/carousel.html' def get_queryset(self): return self.model.objects.filter(tags__slug='fav') def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["tag"] = 'fav' return context -
Django - Overwriting parent model's Meta
I am using the package django-polymorphic-tree inside of a Django application. The PolymorphicMPTTModel abstract model from said package has the following Meta: class PolymorphicMPTTModel(MPTTModel, PolymorphicModel, metaclass=PolymorphicMPTTModelBase): """ The base class for all nodes; a mapping of an URL to content (e.g. a HTML page, text file, blog, etc..) """ # ... fields class Meta: abstract = True ordering = ( "tree_id", "lft", ) base_manager_name = "objects" Here's a model I wrote that inherits from it: class MyNodeModel(PolymorphicMPTTModel): parent = PolymorphicTreeForeignKey( "self", blank=True, null=True, related_name="children", on_delete=models.CASCADE, ) # ... fields class Meta: ordering = ( "tree_id", "-lft", ) As you can see, I'm trying to overwrite the parent's Meta.ordering attribute. However, if I do this inside of an instance of MyNodeModel: print(self.Meta.ordering) it prints: ('tree_id', 'lft') which is the parent's value for that field. It appears as though the child class is failing to override that property. Why does this happen? -
Flutter WEB sending file to Django Rest Framework Backend
So in my flutter front end (WEB). I am using Image_picker and then image_cropper packages to obtain a file. I know flutter web doesn't support Dart/io so instead you have to send your image in a mulitpart request FromBYtes. Normally for an ios/android flutter app you can use fromFile. Now I send that to my backend as bytes. however, my django rest framework view isnt able to save the image to my model. here is the code and step by step: final imagetoSendToAPIasbytes = await cropImageFile.readAsBytes(); List<int> imageaslistint = imagetoSendToAPIasbytes.cast(); final response = await uploadImage(imageaslist, profileid); uploadimage function: var profilepic = await http.MultipartFile.fromBytes( "profilepic", imageaslistint); request.files.add(profilepic); http.StreamedResponse response = await request.send(); var responseByteArray = await response.stream.toBytes(); ofcourse this is not the full code. But I am able to send it to the back end. my django backend view to handle: @api_view(['PATCH', ]) @throttle_classes([updateprofileprofilepicThrottle]) @parser_classes((MultiPartParser, FormParser, JSONParser)) def updateprofileprofilepic(request,): try: user = request.user except User.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) try: if request.method == "PATCH": profileobjid= json.loads(request.data['profileid']) profileobj = Profile.objects.get(creator = user, id = profileobjid) profileobj.profilepic.delete(False) print(request.FILES['profilepic']) print(json.loads(request.data['profilepic'])) profileobj.profilepic= json.loads(request.data['profilepic']) profileobj.save() usualy (request.FILES['profilepic']) allows me to save a file (from ios/android) however thats when its sending as a mulitipart request.fromPATH. So now (json.loads(request.data['profilepic'])) im … -
I want to autogenerate a username in django
I want to create my own username for users in django from django.contrib.auth import get_user_model from datetime import date from django.dispatch import receiver from django.db.models.signals import pre_save from django.db import models User = get_user_model() # auto username @receiver(pre_save, sender=User) def set_username(sender, instance, created, **kwargs): if created: instance.username = 'User-' + str(date.year) + '-' + str(instance.id) instance.save() so I created this signals.py file and I added this signals file to the app.py file in the app context but still it is not making any progress can someone help me to generate an username while filling the form. -
How to PREVENT AWS EB from running migration
I have a Python/Django app and I'm trying to get it deployed to AWS Elastic Beanstalk. I'm using the EB CLI. What I've run into is similar to others (e.g. Deploying Django to Elastic Beanstalk, migrations failed). But I can't get past the migration failure that is blocking a successful eb deploy. I removed the .ebextensions/db-migrate.config file from my project, but it seems like it's cached somewhere since the logs still show this: ... 2022-12-01 22:14:21,238 [INFO] Running config postbuild_0_ikfplatform 2022-12-01 22:14:21,272 [ERROR] Command 01_migrate (source /var/app/venv/*/bin/activate && python3 manage.py migrate) failed 2022-12-01 22:14:21,272 [ERROR] Error encountered during build of postbuild_0_ikfplatform: Command 01_migrate failed ... How can I prevent EB from somehow magically running the migration command (which is no longer in my project)? FYI: I can successfully migrate the RDS DB from my local computer which is fine for now. -
How to generate plaintext files from an HTML template?
Getting plaintext files from an HTML using python code. Like Django, using jinja templating from the jinja2 library to display data parsed into the context from the view function. I'll like to know all the different ways in which I can get the plaintext version of the jinja template, and most of all "it should be formatted". Example Jinja template <div>{{ book.name }}</div> <p> The author of the book is {{ book.author }}.</p> <p> For more description, go to "{{ book.url }}"</p> <div> <p>Some important notions on the book</p> <ol> {% for items in points %} <li>{{ items }}</li> {% endfor %} </ol> </div> </div> Plaintext version Python For Beginners The author of the book is John Doe. For more description, go to "https://mybooks.example.com/book1" Some important notions on the book - Variable - Strings - File R/W operations - Loops - Conditions what different options can I have to do this in Django or python and getting over a 100 of such files from the database. -
Loader pops up and hangs when there is a form error on page submission
I am currently using this javascript to popup a loader when I click the submit button. The loader works fine when there is no form error and shows the response after waiting. However, the loader keeps spinning when there is a form input error and the request does not get submitted to backend but loader keeps spinning infinitely. $('#submitBtn').click(function () { $('#loader').removeClass('hidden') // $('#loader').html('Loading').addClass('loadcontent') // $("#loading").html("Loading"); }) </script>``` How can I make this loader script run only when there is no form input error? I am using Django, Javascript, html and I am a beginner in JS. -
Django project to show list of categories as list then the category url displays all posts in that category
I am working on a Django project where I would like to display list of all categories on the homepage as links. When one clicks a category, they are taken to a page whereby all the posts under that field are displayed. Inside the list of posts page, I would like to show the title as the name of the category. Also I would like the url to have the name of the category. My code is working fine in rendering those pages, but my issue is that it uses id instead of the slug field. When I replace .id with .slug, I get the error: ValueError at /category/electricals Field 'id' expected a number but got 'electricals` Here is my Models.py: class Category(models.Model): title = models.CharField(max_length=100) image = models.ImageField(null=True, blank=False) slug = models.SlugField(unique=True, null=True) def __str__(self): return self.title class Service(models.Model): category = models.ForeignKey('Category', on_delete=models.CASCADE) title = models.CharField(max_length=100) image = models.ImageField(null=True, blank=False) description = models.TextField(null=False, blank=False) service_id = models.UUIDField(default=uuid.uuid4, primary_key=True, unique=True, editable=False) slug = models.SlugField(unique=True, null=True) def __str__(self): return self.title And here is my views.py; def landing_page(request): categorys = Category.objects.all() context = {'categorys':categorys} return render(request, 'users/homepage.html', context) def categories(request, cats): category_services = Service.objects.filter(category=cats) context = {'cats':cats,'category_services':category_services } return render(request, 'users/categories.html', context) … -
How can get products for active owners (users) only with Django Rest Framework?
I'm creating an e-commerce API with DRF. I would like to retrieve and display only active products from active owners (users) using a ModelViewSet How can I do this? Here is my code : views.py class ProductViewSet(viewsets.ModelViewSet): serializer_class = ProductSerializer parser_classes = (MultiPartParser, FormParser) search_fields = ['title', 'description'] ordering_fields = ['price', 'last_update'] permission_classes = [permissions.IsAuthenticatedOrReadOnly, IsVendorOrReadOnly, IsOwnerOrReadOnly] def get_queryset(self): return Product.objects.filter(is_active=True) # WHEN I'M USING THIS COMMENT CODE, I CAN'T RETRIEVE ONE PRODUCT BY PK # products = Product.objects.all() # new_products = [] # for p in products: # if p.owner.is_active and p.is_active: # new_products.append(p) # return new_products def perform_create(self, serializer): serializer.save(owner=self.request.user) -
Django Serializer - how to check if a ListField is valid?
I'm currently working on a practice social media app. In this app, current users can invite their friends by email to join the app (specifically, joining a 'channel' of the app, like Discord). I'm working on unit tests to ensure that emails are valid. I'm working with serializers for the first time and I'm trying to move past some issues I've been having. Functionality: the user enters in a friend's email address. For the purposes of this test, the email address needs to be at least 6 characters long. So something like "a@a.co" (6 char) would be acceptable, but "a@a.c" (5 char) would not be accepted. Users can enter up to 10 emails at a time. What I'm currently struggling with is what function to use for "is_valid"? I know Django forms has something for this, but I haven't found a satisfactory method for serializers. Here is what's currently in serializers.py. from django.core.validators import MinValueValidator, MaxValueValidator from rest.framework.fields import ListField from rest.framework import serializers class EmailList(ListField): """Will validate the email input""" def to_internal_value(self, data): # if the EmailList is not valid, then a ValidationError should be raised--here's where I'm wondering what to put raise serializers.ValidationError({"invalid_email": "Email is invalid, please recheck".}) …