Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Reverse for 'department-detail' ....'{'department_id': 2}' not found. 1 pattern(s) tried: ['(?P<deraptment_id>[^/]+)\\Z']
) Подскажите, пожалуйста, что я сделал не так? При переходе на http://127.0.0.1:8000/deraptment/ получаю ошибку: Reverse for 'department-detail' with keyword arguments '{'department_id': 2}' not found. 1 pattern(s) tried: ['(?P<deraptment_id>[^/]+)\Z'] Вот все поля ошибки: image urls.py from main import views urlpatterns = [ path('<deraptment_id>', views.department_detail, name='department-detail'), path('deraptment/', views.departments, name='departments'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) views.py def departments(request): departments = Department.objects.all() return render(request, 'departments.html', {'departments': departments}) def department_detail(request, department_id): department = get_object_or_404(Department, id=department_id) return render(request, 'department_detail.html', {'departments': departments}) base.html <span class="text-uppercase"></span> <a href="{% url 'departments' %}" class="list-group-item {% if request.path == department %} active {% endif %}">Departments</a> department_detail.html {% extends 'base.html' %} {% block title %} Department {{ department.name }} {% endblock%} {% block page %} <a href="{% url 'departments' %}">Departments</a> <div> <h2>{{ department.name }}</h2> <div>{{ department.description }}</div> </div> {% endblock %} department.html (В нём отдаёт ошибку) {% extends 'base.html' %} {% block title %} Departments {% endblock%} sd {% block page %} {% for department in departments %} <div> <h2>{{ department.name }}</h2> <a href="{% url 'department-detail' department_id=department.id %}">{{ department.name }}</a> <div>{{ department.description }}</div> </div> {% endfor %} {% endblock %} -
Django Rest Framework: Create List Model with custom data
Assume that I want to create multiple model objects and I want to add some generated unique data to all of them when saving. So if post something like this to an endpoint: [ { "createDate":"now" }, { "createDate":"now" } ] The response should be something like: [ { "createDate":"now", "uid":"1" }, { "createDate":"now", "uid":"2" } ] I have created a ViewSet for this and generate the necessary fields in the perform_create ovveride method: def perform_create(self, serializer): unique_ids = ReleModuleConfig.objects.values_list('uid', flat=True) uid = generate_random_id(unique_ids) serializer.save(added_by=self.request.user, updated_by=self.request.user, uid=uid) However when I save this, the same uid is set for all of the objects. So the response is: [ { "createDate":"now", "uid":"1" }, { "createDate":"now", "uid":"1" } ] How could I generate unique fields and inject it into the serializer if I have multiple objects? I know that there is already an ID unique field by default on most tables, but I have to generate QR codes and other things as well, I just removed that from this example to make it easier to understand. -
about movie ticket booking in django
from django.shortcuts import render from . models import Movie Create your views here. def index(request): movies=Movie.objects.all() return render(request,'index.html',{ "movies":movies }) from django.urls import path from . views import index app_name='movies' urlpatterns = [ path('',index,name="home") -
Retrieve list of employees in a company model in Django
I have set up the two following models: Model "User" class User(AbstractBaseUser, PermissionsMixin): username = models.CharField('username', max_length=30, blank=True) email = models.EmailField('Adresse mail', unique=True) first_name = models.CharField('Prénom', max_length=30, blank=True) last_name = models.CharField('Nom', max_length=30, blank=True) date_joined = models.DateTimeField('date joined', auto_now_add=True) company = models.OneToOneField(Customer, on_delete=models.CASCADE, blank=True, null=True) is_active = models.BooleanField('active', default=True) is_staff = models.BooleanField('staff status',default=False) is_superuser = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] class Meta: verbose_name = 'user' verbose_name_plural = 'users' def get_full_name(self): ''' Returns the first_name plus the last_name, with a space in between. ''' full_name = '%s %s' % (self.first_name, self.last_name) return full_name.strip() def get_short_name(self): ''' Returns the short name for the user. ''' return self.first_name def email_user(self, subject, message, from_email=None, **kwargs): ''' Sends an email to this User. ''' send_mail(subject, message, from_email, [self.email], **kwargs) Model "Customer" class Customer(models.Model): name = models.CharField(max_length=200, blank=False) transporters = models.ManyToManyField(Transporter, blank=True) def __str__(self): return self.name class Meta: verbose_name = "Company" verbose_name_plural = "Companies" I'm trying to get the list of all employees belonging to one company. I want to display this list in the django admin. My guess was to go with employees = models.ManyToManyField(User, blank=True). But it does not work because I have the following message: employees = models.ManyToManyField(User, blank=True) … -
Django template, send two arguments to template tag and return safe html value?
Is there a way to pass 2 arguments through django template tag and get a safe html value? -
Django: How to clean data when list_editable in admin page?
I have a model which has a field 'keywords'. When I use a form to create/modify records, I am able to clean this field and then save it. class ILProjectForm(forms.ModelForm): class Meta: models = ILProject fields = '__all__' def clean_keywords(self): k = self.cleaned_data.get('keywords') if k: k = ','.join([a.strip() for a in re.sub('\\s+', ' ', k).strip().split(',')]) return k However, I am not sure how to run clean() to update the data when I am using the list_editable option in the admin page. I tried something like this bit I get an error saying I cannot set an attribute. What is the correct way to update the data after it has been cleaned? class MyAdminFormSet(BaseModelFormSet): def clean(self): print(type(self.cleaned_data)) recs = [] for r in self.cleaned_data: if r['keywords']: r['keywords'] = ','.join([a.strip() for a in re.sub('\\s+', ' ', r['keywords']).strip().split(',')]) print(r['keywords']) recs.append(r) self.cleaned_data = recs <-- this part is problematic. class ILProjectAdmin(...) ... def get_changelist_formset(self, request, **kwargs): kwargs['formset'] = MyAdminFormSet return super().get_changelist_formset(request, **kwargs) -
Django Heroku collectstatic --noinput Not uploading all assets to S3 Bucket
I have a Django project I am deploying to Heroku. I am using AWS S3 to store and serve static assets. In my project assets folder, I have these folders and files: However, when python manage.py collectstatic --noinput gets run, only two folders (admin and rest_framework) and all other files are being copied to s3 (see screenshot below in s3) Can someone point out what could be the issue? Here are my settings.py STATIC_URL = config('AWS_URL') + '/staticfiles/' MEDIA_URL = config('AWS_URL') + '/media/' DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3StaticStorage' AWS_ACCESS_KEY_ID = config('AWS_ACCESS_KEY', 'default') AWS_SECRET_ACCESS_KEY = config('AWS_SECRET_KEY', 'default') AWS_STORAGE_BUCKET_NAME = config('AWS_S3_BUCKET') AWS_S3_BUCKET_CNAME = config('AWS_S3_BUCKET_CNAME') AWS_URL = config('AWS_URL') AWS_PRELOAD_METADATA = True AWS_DEFAULT_ACL = config('AWS_DEFAULT_ACL', 'public-read') AWS_S3_REGION_NAME = config('AWS_S3_REGION_NAME', 'eu-west-2') AWS_S3_SIGNATURE_VERSION = config('AWS_S3_SIGNATURE_VERSION', 's3v4') -
Gunicorn - [CRITICAL] WORKER TIMEOUT when hitting HttpResponseredirect view
I am building an api with Django Rest framework , Below is my view class UrlRedirectView(RetrieveAPIView): queryset = AwsConsoleAccess.objects.all() def get(self, request, *args, **kwargs): request_id = self.kwargs['request_id'] redirect_id = self.kwargs['redirect_id'] aws_console_access = get_object_or_404(AwsConsoleAccess,request_id=request_id, redirect_id=redirect_id) aws_console_access.increment_access_count() # Increment the click event for each clicks aws_console_access.save() return HttpResponseRedirect(redirect_to=aws_console_access.federated_link_url) I am running the app with gunicorn gunicorn chilli.wsgi gunicorn chilli.wsgi -t 0 Using above two commands it gives me the following error 2022-04-19 21:31:45 +0100] [6168] [INFO] Starting gunicorn 20.1.0 [2022-04-19 21:31:45 +0100] [6168] [INFO] Listening at: http://127.0.0.1:8000 (6168) [2022-04-19 21:31:45 +0100] [6168] [INFO] Using worker: sync [2022-04-19 21:31:45 +0100] [6169] [INFO] Booting worker with pid: 6169 [2022-04-19 21:33:19 +0100] [6168] [CRITICAL] WORKER TIMEOUT (pid:6169) [2022-04-19 20:33:19 +0000] [6169] [INFO] Worker exiting (pid: 6169) [2022-04-19 21:33:19 +0100] [6204] [INFO] Booting worker with pid: 6204 This issue happens only when I hit this endpoint all the other endpoint works fine. -
Django ORM Queries differences
What is the difference between these queries? Output looks the same. 1) >>> Movie.objects.all() <QuerySet [<Movie: Film 1>, <Movie: Film 2>, <Movie: Film 3>]> >>> Movie.objects.prefetch_related('projection_set').all() <QuerySet [<Movie: Film 1>, <Movie: Film 2>, <Movie: Film 3>]> >>> Movie.objects.prefetch_related('projection_set') <QuerySet [<Movie: Film 1>, <Movie: Film 2>, <Movie: Film 3>]> -
How to run a Django + NextJs app from Heroku?
I have been working on a Django + NextJs project since the last week and i want to deploy it on Heroku, since i'm using the django-nextjs library, they say i should run two ports on the same server but as long as i have read, it's not possible to do it in Heroku, I think it is possible to activate the node server trough the Procfile but I'm not sure of how to do it exactly. -
Django messages framework with Proxy
I have a django application running on heroku. I'm having a problem with the django message framework. messages.success(request,"Foo") all users are shown this warning message when this code runs. I think this is because of heroku's proxy. Because when I print the client's IP address on the screen, I get a constantly changing IP address. When I use HTTP_X_FORWARDED_FOR I can get the real IP address of the client. But how do I set it up with django messages framework? A message alert is shown to all users (different device, different IP though) -
Django model entries not showing up in a table
The problem is that the data I want to display is not showing up, the slicing part does work because it will show 5 table rows only containing the pre-defined image. The Amount_of_tweets and demonstrations do show the correct count. Thank you in advance Models.py: class demonstrations(models.Model): data_id: models.IntegerField() event_id: models.IntegerField() event_date: models.DateField() year: models.IntegerField() event_type: models.CharField() sub_event_type: models.CharField() region: models.CharField() country: models.CharField() province: models.CharField() location: models.CharField() latitude: models.FloatField() longitude: models.FloatField() text: models.CharField() translation: models.CharField() fatalities: models.IntegerField() sentiment_score: models.FloatField() View.py @login_required(login_url="/login/") def index(request): latest_tweets = tweets.objects.all()[:5] amount_of_tweets = tweets.objects.all().count() latest_demonstrations = demonstrations.objects.all()[:5] amount_of_demonstrations = demonstrations.objects.all().count() context = { 'segment': 'index', 'latest_tweets' : latest_tweets, 'amount_of_tweets': amount_of_tweets, 'latest_demonstrations': latest_demonstrations, 'amount_of_demonstrations': amount_of_demonstrations, } html_template = loader.get_template('home/index.html') return HttpResponse(html_template.render(context, request)) index.html {% for demo in latest_demonstrations %} <tr class="unread"> <td><img style="width:40px;" src="/static/assets/images/icons/image.png" alt="activity-user"></td> <td> <h6 class="mb-1">{{ demo.location }}</h6> <p class="m-0">{{ demo.event_type }}</p> </td> <td> <h6 class="text-muted">{{ demo.event_date }}</h6> </td> <td><a href="#!" class="label theme-bg text-white f-12">View</a></td> </tr> {% endfor %} -
Drf: Getting related posts by ManyToMany category and a tags field
I'm trying to get all related posts by getting the id of the current post and filtering through the DB to find posts that are either in a similar category or have similar tags. this is the model for the posts: class Post(models.Model): .... author = models.ForeignKey( "users.User", on_delete=models.CASCADE, related_name='blog_posts') tags = TaggableManager() categories = models.ManyToManyField( 'Category') .... status = models.IntegerField(choices=blog_STATUS, default=0) def __str__(self): return self.title this is the views.py file: class RelatedPostsListAPIView(generics.ListAPIView): serializer_class = PostsSerializer queryset = BlogPost.objects.filter( status=1)[:5] model = BlogPost def get(self, pk): post = self.get_object(pk) qs = super().get_queryset() qs = qs.filter( Q(categories__in=post.categories.all()) | Q(tags__in=post.tags.all()) ) return qs with this code I get a RelatedPostsListAPIView.get() got multiple values for argument 'pk' error, I don't think I am actually getting the object with the id, any help would be much appreciated. -
unsupported operand type(s) for +: 'WindowsPath' and 'str' issue
I am working on a group project for college using django and python, however I am running into an issue. I am following a newsletters tutorial from a youtube playlist and while he has no errors this is the error I am receiving. Here is an image of the error Here is the code. def newsletter_signup(request): form = newsletterUserSignUpForm(request.POST or None) if form.is_valid(): instance = form.save(commit=False) if newsletterUser.objects.filter(email = instance.email).exists(): messages.warning(request, 'Your email already exists in our database', 'alert alert-warning alert-dismissible') else: instance.save() messages.success(request, 'Your email has been signed up to our Newsletter!', 'alert alert-success alert-dismissible') subject = "Thank you for joining our Newsletter" from_email = settings.EMAIL_HOST_USER to_email = [instance.email] with open(settings.BASE_DIR + "/templates/newsletters/sign_up_email.txt") as f: sign_up_message = f.read() message = EmailMultiAlternatives(subject=subject, body=signup_message, from_email = from_email, to_email = to_email) html_template = get_template("/templates/newsletters/sign_up_email.html").render() message.attach_alternative(html_templae, "text/html") message.send() context = { 'form': form, } template = "newsletters\sign_up.html" return render(request, template, context) I realise the video may be outdated a tad as its from 2017 so any help would be appreicated. -
Have a datatable that is populated on the page and wish to edit the datatable dynamically
Like the question states. The datatable is in Django. I know that Ajax is used to refresh portions of the page dynamically. The trouble is our mysql database was created such that the columns for the database aren't populated with a JSON response. I realize that JSON is used to populate the table dynamically. Currently, it's being done statically. I would like to be able to edit inline. <!doctype html> <html lang="en"> <head> <link rel="stylesheet" href="./static/api/rep_home.css"> <link href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet" /> <link href="https://cdn.datatables.net/buttons/1.4.2/css/buttons.dataTables.min.css" rel="stylesheet" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script> <script src="https://cdn.datatables.net/buttons/1.4.2/js/dataTables.buttons.min.js"></script> <script src="https://cdn.datatables.net/buttons/1.4.2/js/buttons.colVis.min.js"></script> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"> <meta charset=utf-8 /> <title>REP Data</title> </head> <body> {% block content %} {% block search_input %} {% endblock %} <form method='POST'> <div class='container'> <div class='row '> {% csrf_token %} {% for field in form %} <div class = 'row'> <div style="margin: 6px" class='col'> <b>{{ field.label_tag }}</b> {{ field }} </div> </div> {% endfor %} <div class='row'> <div class = 'col'> <button type='submit' class='btn btn-primary' name='filter' style="margin: 5px">Filter</button> <button type='submit' class='btn btn-danger' name='reset' style="margin: 5px">Reset Filters</button> </div> </div> </div> </div> <div class = 'container-fluid'> <table id="example" class="display nowrap" width="100%"> <thead> <tr> <th scope="col"> <input id='check-all' type='checkbox' checked='checked'> </th> <th scope="col">REP Name</th> {% for characteristic in … -
Python Django how to share a foreign key?
In models.py, when I define a unique key on a model and then call it by another model under different variable names, it will not add those columns to the Sqlite table. Please, how to solve? In my case, I want to define unique locations (location_id), then define movements between those locations (location_from, location_to). This is my code: # models.py class Locations(models.Model): location_id = models.CharField(max_length = 10, unique=true) class Movements(models.Model): blabla = models.CharField(max_length = 10, unique=true) location_id = models.ForeignKey(Locations, on_delete=models.CASCADE, related_name='location_from') location_id = models.ForeignKey(Locations, on_delete=models.CASCADE, related_name='location_to') After makemigrations and migrate, the table Movements in db.sqlite3 does not contain the fields location_from and location_to. What happened? My language is clearly wrong. Please, how to make it right? -
Django ORM filter by group with where clause
I have a model of students and options. Each study can change their opinion over time. What I ultimately want to do is create a plot showing the number of students with each opinion on a given day. My model is as follows (abbreviated for brevity): class Student(models.Model): first_name = models.CharField(max_length=30, null=True, blank=True) surname = models.CharField(max_length=30, null=True, blank=True) class Opinion(models.Model): student = models.ForeignKey('Student', on_delete=models.CASCADE,null=True) opdate = models.DateField(null=True, blank=True) sentiment_choice = [ ('Positive', 'Positive'), ('Negative', 'Negative'), ] sentiment = models.CharField( max_length=40, choices=sentiment_choice, default="Positive", null=True, blank=True ) My approach is to loop over all the dates in a range, filter the opinion table to get all the data upto that date, find the latest opinion per student, count these and load the results into an array. I know how to filter the opinion table as follows (where start_date is my iterator): Opinion.objects.filter(opdate__lte=start_date) I also know how to pickup the latest opinion for each student: Opinion.objects.values('student').annotate(latest_date=Max('opdate')) How would I combine this so that I can get the latest opinion for each student that is prior to my iterator? I'm working on Django 3.2.12 with an SQL Lite DB -
Django DestroyModelMixin dosnt delete and works as get
I have my api view set and the GET, POST and PATCH methods works as it is sopoused to, but delete doest not works, and besides of that, works a if I send a GET request -
Can`t insert json request to Django model with foreign keys
I have Main table with some data including Foreign keys to another models. I`ve got a problem with adding data to this model from JSON request. Some of fields in request can be 'None', some may be absent. models.py from django.db import models class Systems(models.Model): class Meta: db_table = 'systems' system = models.CharField(max_length=100, unique=True) active = models.BooleanField(default=True) def __str__(self): return self.system class Location(models.Model): class Meta: db_table = 'location' location = models.CharField(max_length=100, unique=True) active = models.BooleanField(default=True) def __str__(self): return self.location class RepairPlace(models.Model): class Meta: db_table = 'repair_place' place = models.CharField(max_length=100, unique=True) active = models.BooleanField(default=True) def __str__(self): return self.place class Equipments(models.Model): class Meta: db_table = 'equipments' equipment = models.CharField(max_length=100, unique=True) equipment_system = models.ForeignKey(Systems, on_delete=models.RESTRICT) active = models.BooleanField(default=True) def __str__(self): return self.equipment class Employees(models.Model): class Meta: db_table = 'employees' unique_together = ('last_name', 'first_name', 'middle_name') last_name = models.CharField(max_length=100) first_name = models.CharField(max_length=100) middle_name = models.CharField(max_length=100, null=True, blank=True) organization = models.CharField(max_length=100, null=True, blank=True) active = models.BooleanField(default=True) def __str__(self): result = self.last_name + ' ' + self.first_name + ' ' + self.middle_name return result class Main(models.Model): class Meta: db_table = 'main' object = models.ForeignKey(Location, on_delete=models.RESTRICT, related_name="location_name"') name = models.ForeignKey(Equipments, on_delete=models.RESTRICT, related_name="equipment_name") serial = models.CharField(max_length=100, null=True, blank=True) system = models.ForeignKey(Systems, on_delete=models.RESTRICT, related_name="system_name") accepted_dt = models.DateField(null=True, blank=True) shipped_repair_dt = … -
How to setup django admin panel to edit a record in a model?
I have a django project created with django 4.0. I'm new to djnago, so if I'm asking a silly question, please forgive me! I can't figure out a way by which I can edit a record in my model through the admin panel. Below is the model Products that has some products added. Suppose I want to edit the fields' data (eg. Name of product), then how can I achieve that from the admin panel itself? The admin panel is just showing to delete the selected record currently. Below is the code that is present in the admin.py file: from django.contrib import admin from .models import ( Customer, Product, Cart, OrderPlaced ) @admin.register(Customer) class CustomerModelAdmin(admin.ModelAdmin): list_display = ['id', 'user', 'name', 'locality', 'city', 'zipcode', 'state'] @admin.register(Product) class ProductModelAdmin(admin.ModelAdmin): list_display = ['id', 'title', 'selling_price', 'discounted_price', 'description', 'brand', 'category', 'product_image'] @admin.register(Cart) class CartModelAdmin(admin.ModelAdmin): list_display = ['id', 'user', 'product', 'quantity'] @admin.register(OrderPlaced) class OrderPlacedModelAdmin(admin.ModelAdmin): list_display = ['id', 'user', 'customer', 'product', 'quantity', 'ordered_date', 'status'] Thanks in advance! -
'max_length' is ignored when used with IntegerField
I have this model class MyUser(AbstractBaseUser): ##username =models.U email=models.EmailField( verbose_name='email address', max_length=255, unique=True, ) date_of_birth=models.DateField() picture =models.ImageField(upload_to='images/users',null=True,verbose_name="") is_active =models.BooleanField(default=True) phone_number = models.IntegerField(max_length=12,unique=True,null=False,verbose_name='phone') is_admin = models.BooleanField(default=False) #credits =models.PositiveIntegerField(default=100) linkedin_token=models.TextField(blank=True ,default='') expiry_date=models.DateTimeField(null=True, blank=True) objects=UserManger() when i run python manage.py makemigrations I got this error WARNINGS: Accounts.MyUser.phone_number: (fields.W122) 'max_length' is ignored when used with IntegerField. HINT: Remove 'max_length' from field It is impossible to add a non-nullable field 'phone_number' to myuser without specifying a default. This is because the database needs something to populate existing rows. can any help me ? -
Why django-unicorn doesnt update hmtl-table?
There is django-unicorn 0.44.0's component configuration. refresh.py from django.db import connection from django_unicorn.components import UnicornView from datamarket.models import Clients class RefreshView(UnicornView): clients = None count = None def get_client(self): print('---Got hh clients---') self.count = Clients.objects.all().count() self.clients = Clients.objects.all().order_by("surname")[:10] def az(self): self.clients = Clients.objects.all().order_by("surname")[:10] def za(self): self.clients = Clients.objects.all().order_by("-surname")[:10] def mount(self): print('---Got clients---') self.clients = Clients.objects.all().order_by("surname")[:10] self.count = Clients.objects.all().count() refresh.html <div> <button class="btn" unicorn:click="get_client()">Update</button> <button class="btn" unicorn:click="az()">A-Z</button> <button class="btn" unicorn:click="za()">Z-A</button> <p> All {{ count }} records</p> </div> <table> <thead> <th>Surname</th> <th>Name</th> <th>Age</th> </thead> <tbody> {% for c in clients %} <tr> <td>{{ c.surname }}</td> <td>{{ c.name }} </td> <td>{{ c.age }}</td> </tr> {% empty %} <tr> <td colspan="3">No found</td> </tr> {% endfor %} </table> The mount() function doing well when I refresh page, it changes clients value in html. Also count value updating well too when I call get_clients() by button. But it doesnt change client collection in table when I call get_clients(), az(), za() by button. Why? It's worked literally week ago and now I dont get any errors. -
I wanna learn Django after i learn python so any ideas
I learn python a quite time and i kinda doing python pretty well , but i just dont know how hard to learn Django Is learn Django harder than python ? And someone can recommend a good Django document for me ? -
Proper way of dealing with unique constraints
I'm trying to find a way to check if an user's Username or Email already exists in the database, then return a ValidationError with the appropiate error message. However i see no way of doing this without calling multiple queries or making it look weird (adding a serializer within a service)... Is there a coding practice for doing this properly? This is just one of many possible usecases: users = User.objects.filter(Q(email=email) | Q(username=username)) if users.exists(): for user in users: # There could be two if user.email == email: raise ValidationError('Email already exists.') else: raise ValidationError('Username already exists.')``` -
How to get objects which have an object in their ManyToMany field?
There's this model: class User(AbstractUser): followers = models.ManyToManyField('self', symmetrical=False, related_name='followings', null=True, blank=True) Say I have a user object called 'A'. I want to filter User objects which have 'A' as their follower. How can I do that?