Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django annotate by sum of two values with multiple relations
I have 4 models: class App(models.Model): ... class AppVersion(models.Model): app = models.ForeignKey(App) ... class Apk(models.Model): version = models.OneToOneField(AppVersion) size = models.IntegerField() class Obb(models.Model): version = models.ForeignKey(AppVersion) size = models.IntegerField() AppVersion version always has one Apk, but may have 0, 1 or 2 Obb's I want to annotate QuerySet by total size of the App (which is Apk.size + sum of all Obb.size for given AppVersion). My App QuerySet looks like this: qs = App.objects.filter(is_visible=True) and versions subquery is: latest_versions = Subquery(AndroidApplicationVersion.objects.filter(application=OuterRef(OuterRef('pk'))).values('pk')[:1]) This subquery always gives the latest AppVersion of the App. So what subquery should I use to annotate qs with size attribute calculated as shown above? -
ElasticBeanstalk trying to connect local postgres database
Elasticbeanstalk autcreated a postgres database when I changed the env configuration . I tried supplying the RDS_* parameters. Still it is connecting to localhost and failing django.db.utils.OperationalError: could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?. container_command 04_migrate in .ebextensions/django.config failed. For more detail, check /var/log/eb-activity.log using console or EB CLI. this is my config container_commands: 02_upgrade_pip: command: ". /home/ec2-user/setup.sh && python -m pip install --upgrade pip" leader_only: true 03_upgradde_setuptools: command: "python -m pip install --upgrade setuptools" leader_only: true 04_migrate: command: "source /opt/python/run/venv/bin/activate && python /opt/python/current/app/manage.py migrate --noinput" leader_only: true 05_createsu: command: "source /opt/python/run/venv/bin/activate && python /opt/python/current/app/manage.py createsu" leader_only: true 06_collectstatic: command: "source /opt/python/run/venv/bin/activate && python /opt/python/current/app/manage.py collectstatic --noinput" files: "/opt/python/run/venv/pip.conf": mode: "000755" owner: root user: root content: | [global] no-cache-dir=false "/home/ec2-user/setup.sh": mode: "000755" owner: root group: root content: | #!/bin/bash #exported RDS variables here option_settings: "aws:elasticbeanstalk:application:environment": DJANGO_SETTINGS_MODULE: "project.settings" "PYTHONPATH": "/opt/python/current/app:$PYTHONPATH" "ALLOWED_HOSTS": ".elasticbeanstalk.com" "aws:elasticbeanstalk:container:python": WSGIPath: /opt/python/current/app/project/wsgi.py NumProcesses: 3 NumThreads: 20 "aws:elasticbeanstalk:container:python:staticfiles": "/static/": "/opt/python/current/app/static/" I think it should have taken by itself when I do ssh to ec2 I cannot echo $RDS_HOSTNAME either. What may be the problem here -
SQL identifier substitution - Using a list of column names
I am trying to run a query of the form: SELECT {} from TABLE where foo = VALUE But I want to be able to provide a list to replace the {} According to the psycopg docs, in order to do this safely, you need to use the sql.Identifier function, in order to properly escape the parameter, and then do something like this: SQL = sql.SQL( "SELECT {} FROM foo WHERE bar = %s" ).format(identifier) cursor.execute(SQL, [VALUE]) This works, when identifier is a single element, but I need it to be an arbitrary number. For example if: identifier = ["abc", "def"] and VALUE = 4 SQL = SELECT abc def FROM foo WHERE bar = 4 I've tried running sql.Identifier(x) for every member of identifier, but that gave "abc""def", which is clearly not correct. -
django social media apps ManyToManyField population issue
I am writing a social media apps, I design a model, when i try to populate it, it throws me this error: ValueError at /admin/social/group/add/ "<Group: Group object (None)>" needs to have a value for field "id" before this many-to-many relationship can be used. this is my models: from django.db import models class Person(models.Model): name = models.CharField(max_length=20) class Group(models.Model): admin = models.ForeignKey( Person, on_delete=models.CASCADE, related_name='group_admin' ) members = models.ManyToManyField( Person, related_name='group_members', blank=True ) def save(self, *args, **kwargs): self.members.add(self.admin) super(Group, self).save(*args, **kwargs) I want an admin also will be a group members when i keep the save method like below this: def save(self, *args, **kwargs): super(Group, self).save(*args, **kwargs) self.members.add(self.admin) it doesn't throws any error but the problem is, the members filed don't populate. I want, I will just submit admin during create a Group, and memebrs field will be filled automatically with same foreignkey of admin. I mean, an admin will be a members of the same group too. can anyone help me to achieve this? -
django admin customise changelist with hyperlink actions in each row
I am using django admin to do a reporting application. and I already add a custom search form in changlist by overriding the 'changlist_view.html' template, there is an element called 'company'. <form action="" method="POST" class="form-inline"> {% csrf_token %} <select name="company"> {% for c in company_list %} <option value="{{c.key}}" {% if company_keep == c.key %} selected="selected"{% endif %} >{{c.value}}</option> {% endfor %} </select> <button type="submit" >Search</button> </form> In the list display, there is hyperlink 'report' in each row, the backend code as below: class myAdminModel(admin.ModelAdmin): ...... def report_link(self, obj): url = f"/%d/%d/report/" % (***company-key***, ***obj.pk-id***,) return mark_safe( "<a target='blank' href='{url}'>Report</a>" ) ...... now my headache question is here, the obj.pk I can easily get except company-key, I know it is a form element from the page request, so is there any solution to get form elements in this situation?? -
Accessing elements of updating form in JavaScript
I've got a form for updating a found item. The form extends Django's UpdateView through the views. The forms for updating a lost item and for updating a found item use the same template but have separate views and forms. They share the same template as majority of the fields are the same. I am trying to add some custom form validation for the form for updating a found item in particular. This validation is specific to the found item and does not apply to a lost item. I have validation in a clean function in the FoundUpdateForm that checks to see if the needed conditions have been met and raises a ValidationError if a condition is not met. Even though there is validation here, I want to add it in a JavaScript file as well. I've tried creating variables in the JavaScript file tied to the elements on the form but have been unsuccessful. I've tried using var staff_type = document.getElementById('staff_type'), var staff_type = document.getElementById('FoundUpdateForm').elements.namedItem('staff_type') and a few other variations of this. The main issue that I'm dealing with is how to grab the form when it does not have an ID. I've looked into assigning the form an … -
django i want to restrict pages with the user types
As I am new to django, i am getting stuck in many places. I am working on some project for my company, where the users are divided in to three category. In my User model, i have added three boolean files with name category1, category2 & category3, with any one True out of three fields. Now i dont want category1 user to access category2 and category3 templates. i am trying to check through function in views.py with below codes def user_check(request): if not request.user.category1: if request.user.category2: return redirect('/category2') elif request.user.category3: return redirect('/category3') Currently this is not helping me with the desired output. Request to help me out with proper solution on this -
Popen doesn't accept me an image as an input. Django
I have a web application that asks the user to upload an image. That is working, I think. Now I want to pass the image to my python script. So, I have this function in views.py: def external(request): inp = request.FILES['uploadedImage'] with Popen([sys.executable, 'ROUTE_WHERE_I_HAVE_THE_SCRIPT', inp], stdout=PIPE, shell = False) as out: for line in out.stdout: print(line.decode('utf-8')) return render(request,'uploadPhoto.html',{'data1':out.stdout}) So the problem I receive is: TypeError: sequence item 114: expected str instance, bytes found The script works if I don't pass an image, but of course the behaviour isn't what I've expected. Do you know how can I "send" the image (saved in inp) to my python script? -
Multi db and unmanged models - Test case are failing
I have mutlidb setup with unmanaged (read-only) models. There's no migrations for these models. I was trying to test the functionality of the view.py. In sqlite3 database these schema of the test table is not creating a causing an issue in failing the test case. In the view.py I have imported the unamanaged (read-only) model is failing. Mentioned the Multi-db setup test_runner.py from django.test.runner import DiscoverRunner class DisableMigrations(object): def __contains__(self, item): return True def __getitem__(self, item): return None class UnManagedModelTestRunner(DiscoverRunner): def setup_test_environment(self, *args, **kwargs): from django.apps import apps # app_name = apps.get_app_config('core_esp') self.unmanaged_models = [m for m in apps.get_models() if not m._meta.managed and m._meta.app_label is 'core_esp'] for m in self.unmanaged_models: m._meta.managed = True super(UnManagedModelTestRunner, self).setup_test_environment(*args, **kwargs) def teardown_test_environment(self, *args, **kwargs): super(UnManagedModelTestRunner, self).teardown_test_environment(*args, **kwargs) # reset un managed models for m in self.unmanaged_models: m._meta.managed = False settings.py if 'test' in sys.argv or 'test_coverage' in sys.argv: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'db.sqlite3', }, 'test_db': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'db.sqlite3', } } INSTALLED_APPS = ['test'] # Skip the migrations by setting "MIGRATION_MODULES" # to the DisableMigrations class defined above # MIGRATION_MODULES = DisableMigrations() # Set Django's test runner to the custom class defined above TEST_RUNNER = 'apps.settings.test_runner.UnManagedModelTestRunner' DATABASE_ROUTERS = ('apps.tests.test_dbrouter.TestApiRouter', … -
Two django forms : one not showing
I'm currently working on my first Django app and i need to show some forms The first one work like a charm(outil form) but i have trouble with the second one(client form) I looked one Django tutorial / MDN and stack overflow but nothing seems wrong :( forms.py from django import forms class AjoutOutil(forms.Form): NomOutil = forms.CharField(label='Nom de l\'outil', max_length='250') class AjoutClient(forms.Form): nomDuClient = forms.CharField(label='Nom du client', max_length='200') domaineDuClient = forms.CharField(label='Domaine activite', max_length='200') views.py from django.http import HttpResponse from django.shortcuts import render, get_object_or_404 #Import des modèles de données from .models import collaborateurs, experiences, outils, competences #import des formulaires import collab.forms #The working one (GET and POST) def ajout_outil(request): form = AjoutOutil() return render(request, 'collab/ajout_outil.html', {'form':form}) #POST du formulaire d'ajout d'outil def ajoutOutilReponse(request): #Si le formulaire est posté if request.method == 'POST': AjoutOutilFormulaire = AjoutOutil(request.POST) if AjoutOutilFormulaire.is_valid(): NomOutil = AjoutOutilFormulaire.cleaned_data['NomOutil'] q = outils(nomOutil=NomOutil) q.save() return render (request, 'collab/ajout_outil_valide.html', {'NomOutil': NomOutil,} ) else: form = AjoutOutil() return render(request, 'ajout_outil_valide.html', {'form':form}); #The non working one (i'm currently stuck on just showing the form i din't even try to develop the POST before succeed in showing it def ajout_client(request): form = AjoutClient() return render(request, 'ajout_client.html', {'form':form}) The HTML of the not-working form (ajout_client.html) {% … -
How can I create a separate page according to a specific id in django?
I am attempting to create a website using django in which people can fill out a form, which will create an instance of the "Person" model. I want to create a separate page for each "Person". I was wondering if it would be possible to assign a specific id to each person, for example 123456, and access that person's page by going to mysite.com/123456. How can I make this happen? -
Compare two lists with different objects and create new object in one of the lists if values doesn't match
Let's say that I have two lists, both of them has objects. list1 has 5 objects and list2 has 6. I want to compare them both and create new object in list1, with the checkin and checkout times, which is extra in list2. trie comparing them as a sets. but no luck. Thank you list1 = [{'checkin': 12/10/2019, 'checkout':13/10/2019}, {'checkin': 13/10/2019, 'checkout':14/10/2019}, {'checkin': 14/10/2019, 'checkout':15/10/2019}, {'checkin': 15/10/2019, 'checkout':16/10/2019}, {'checkin': 16/10/2019, 'checkout':17/10/2019}] list2 = [{'checkin': 12/10/2019, 'checkout':13/10/2019}, {'checkin': 13/10/2019, 'checkout':14/10/2019}, {'checkin': 14/10/2019, 'checkout':15/10/2019}, {'checkin': 15/10/2019, 'checkout':16/10/2019}, {'checkin': 16/10/2019, 'checkout':17/10/2019} {'checkin': 20/10/2019, 'checkout':20/10/2019}] -
really broken django migrations
I get the following output when I run makemigrations and then migrate: (roundwellenv) ruben@ruben-H81M-D2V:~/roundwell$ ./dev_migrations.sh No changes detected in apps 'contenttypes', 'parents', 'admin', 'tips', 'tutors', 'login', 'auth', 'quiz', 'sessions' Operations to perform: Apply all migrations: admin, auth, contenttypes, login, parents, quiz, sessions, tips, tutors Running migrations: Applying contenttypes.0001_initial... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0001_initial... OK Applying auth.0002_alter_permission_name_max_length... OK Applying auth.0003_alter_user_email_max_length... OK Applying auth.0004_alter_user_username_opts... OK Applying auth.0005_alter_user_last_login_null... OK Applying auth.0006_require_contenttypes_0002... OK Applying auth.0007_alter_validators_add_error_messages... OK Applying auth.0008_alter_user_username_max_length... OK Applying auth.0009_alter_user_last_name_max_length... OK Applying auth.0010_alter_group_name_max_length... OK Applying auth.0011_update_proxy_permissions... OK Applying login.0001_initial... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying admin.0003_logentry_add_action_flag_choices... OK Applying parents.0001_initial... OK Applying quiz.0001_initial... OK Applying sessions.0001_initial... OK Applying tips.0001_initial... OK Applying tutors.0001_initial... OK (roundwellenv) ruben@ruben-H81M-D2V:~/roundwell$ python manage.py createsuperuser You have 21 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, login, parents, quiz, sessions, tips, tutors. Run 'python manage.py migrate' to apply them. I know something is really wrong because even if I delete pycache content and the conent from migration folders and a clean sqlite3 db it actually doesn't find any migrations it needs to apply unless I specify the apps I would like to create migrations for. Any clue as … -
Django imagefield in form being ignored
I have a simple django model and form that should allow for images to be uploaded. The form is working correctly, but no image is ever uploaded. Before I set the image to not be required, the form would not submit correctly, with the error being given that the image field was required (even though an image was selected). Outputting form.errors returns nothing, nor do the log files indicate any error. My form will submit correctly, but the imagefield is empty despite an image being selected. My MEDIA_URL and MEDIA_ROOT variables are set correctly in settings.py, and I know they are fine as I have other apps with forms that allow images to be uploaded and they all work fine. I don't seem to have done anything different with this form but for some reason images are just not being accepted. my model: class StoreItem(models.Model): item_name = models.TextField(null='true',blank='true') description = models.TextField(null='true',blank='true') manufacturer = models.TextField(null='true',blank='true') price = models.DecimalField(max_digits=6, decimal_places=2, null='true') item_pic = models.ImageField(upload_to = 'store_photos/', null='true', blank='true') items_in_stock = models.IntegerField(default=0) relevant section from views.py: def additems(request): form = StoreItemForm(request.POST, request.FILES or None) if request.method == 'POST': if form.is_valid(): item_pic = request.FILES.get('item_pic', False) newitem = form.save() template = loader.get_template('/myapp/my_site/main_page/templates/main_page/thankyoumsg.html') return HttpResponse(template.render({'newitem':newitem}, request)) … -
is traversing many relationships lazy or does that trigger many SQL queries in django
I'm trying to avoid excessive SQL queries for performance in Django. I need to traverse several relationships to get to the data I need though. Do I need to manually create a queryset or is Django smart enough to do that for me? My preference would be to do this: if entry.blog.owner.address.zip_code == 10001: return My concern is that it will run a sql query to get the blog data and instantiate a blog object, run a query to get the owner data and instantiate an owner object, run a query to get the address data and instantiate an address object, then return me the zip_code. An alternative would be to do this: if Entry.objects.filter(entry_id=entry.id, entry__blog__owner__address__zip_code=10001).exists() return This is a lot less readable in my opinion but I'm pretty sure it executes only one query. Can I do it the first way or do I need to do it the second way to avoid a bunch of queries being fired? -
Not allow specific word on a field
I have a char field on drf model which i want to restrict it to only allow lower case letters/number and also not allow the word 'All' . I found the way for the letters/numbers but what about the word 'All' or 'all' c = models.CharField(unique=True, max_length=32, validators=[ RegexValidator( regex='^[a-z][a-z0-9_]*$', message='Only lowercase letters and numbers are allowed ' 'and first character cannot be a number' )]) -
Static files not rendering in Django 2.2 when debug disabled
In Django 2.2, when I have DEBUG=True, all my static files render fine. But when I set DEBUG=False to test my production settings, all static file URLs suddenly return 404 errors. I have a project structure like: myproject/ myproject/ settings.py urls.py manage.py static/ thumbnails/ image.png My relevant static settings in settings.py: STATIC_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', 'static')) INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ) ROOT_URLCONF = 'myproject.urls' STATIC_URL = '/static/' DEBUG = False And my urls.py looks like: import os from django.contrib import admin from django.conf.urls.static import static from django.conf import settings urlpatterns = [ path('admin/', admin.site.urls), ] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) Why does a url like http://localhost:8000/static/thumbnails/image.png work fine when debug is on, but return a 404 when debug is off? -
Django doesnt see cyrillic folder names and files
Django doesnt send out images with cyrillic names from static folder and templates. Is there any setting that will enable support for non-ascii file names? -
ForeignKey reverse look up not showing in templates : Django
How can I display the comments of each ChatGroup respectively by doing a ForeignKey reverse lookup from the codes below? Not sure why it is not working. models.py class ChatGroup(models.Model): name = models.CharField(max_length=250, blank=False) host = models.ForeignKey(User, on_delete=models.CASCADE, related_name='hosts') active = models.BooleanField(default=True) class Comment(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user_comments') group = models.ForeignKey(ChatGroup, on_delete=models.CASCADE, related_name='group_comments') body = models.TextField() active = models.BooleanField(default=True) I have tried below in the HTML but it does not seem to work. HTML {% for comment in chatgroup.group_comments.all %} <div class="comment"> <p class="info"> Comment {{ forloop.counter }} by {{ comment.author }} {{ comment.created }} </p> <b>{{ comment.body|linebreaks }}</b> </div> {% empty %} <p>There are no comments yet.</p> {% endfor %} -
How to create online video editor?
I wanna to make online video editor, to do following: crop, rotate, cut, trim ... adding logo, text, images, audio, video adding animation & transition adding filters In front-end i wanna use vue js framework and back-end is python (django) I think I can do step one with ffmpeg, right? adding logo and watermark is possible with ffmepg, right? I wanna adding images, audio, text in video timeline and i can drag them, but i don't know how to that and in which format or type i can add it? Another problem is if i added images or ... how can i send them to server to manipulate video and publish it? And what about animation and transition and filters? what should i do? these are my questions, and i wanna help for front-end and back-end programming. my problem is i don't know what should i do and which libraries i use and from where i should start? -
Django POST 405 method not allowed unless rule comes first
My Django (2.2.5) app has the following urls.py: from django.urls import path from django.urls.conf import re_path from django.views.generic.base import TemplateView from django.contrib.staticfiles.urls import staticfiles_urlpatterns from . import views urlpatterns = [ re_path('^$|signin', TemplateView.as_view(template_name='signin.html'), name='signin'), path('forgot', TemplateView.as_view(template_name='forgot.html'), name='forgot_pass'), path('app', TemplateView.as_view(template_name='core.html'), name='core'), path('try_signin', views.try_signin, name='try_signin'), ] + staticfiles_urlpatterns() The first 3 rules work fine and serve up the respective HTML content. The 4th rule is for a POST request, but the request causes the following error: Method Not Allowed (POST): /try_signin Method Not Allowed: /try_signin [30/Sep/2019 14:20:38] "POST /try_signin HTTP/1.1" 405 0 However if I reorder the URL rules so that the POST rule comes first, then it works fine. There's no conflict in the rules that I can see. I'm new to Django and still learning but I'd like to understand why re-ordering the rules avoids the error, or if there's something else I'm doing/not doing that caused the error. -
In django, return redirect not giving me the required output
I am new to django, I have created a page where only authenticated user should be able to view. Below is my function which i have made in views.py to check and redirect to login page views.py def auth_check_manager(request): if not request.user.is_authenticated: return redirect('/') below is the snapshot of url.py urlpatterns = [ path('', views.login, name='login'), ] -
Ensure the most specific subcategory is selected in a chained dependent dropdown selection
I am implementing chained dependent combobox selection, so you start with one combobox for main category and once you select main category, another <select> appears for selecting a subcategory, and so on until the innermost (most specific) subcategory is selected. This currently works like as follows: whenever a value is changed in a combobox, an AJAX request is fired which calls a view that renders another <select> if a category has children, otherwise returns an HttpResponse which stops attaching the listener. I am using django-mptt to model my categories. So, I have a view for adding products and I want to ensure that the most specific subcategory (it has to be a leaf node) is selected and assign that category to my Product instance. Here is the view: @login_required def product_create_view(request): if request.method == 'POST': create_product_form = CreateProductForm(request.POST) else: create_product_form = CreateProductForm() return render(request, 'products/product_create.html', {'form': create_product_form}) Here is the form: from django.forms import ModelForm from .models import Product, Category class CreateProductForm(ModelForm): class Meta: model = Product fields = ( 'title', 'description', 'price', 'year', 'category', ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['category'].queryset = Category.objects.filter(parent=None) Here is products/product_create.html: {% extends 'pages/base.html' %} {% block content %} <h1>Create a product</h1> <form … -
Django - Update/refresh table data in html with jQuery and ajax every x seconds
I am having a problem with automatically updating the table data and updating the date every x seconds using the jQuery and ajax code below. I am trying to look at another view (get_more_tables) and then append this data to the table without the need for a manual refresh, but i cant get it to update. If i check the console log the data is there and updating every 10 secs. I am new to programming, django, python etc, so i apologize for any poor programming techniques! I have attempted to add a few parts to the end of the ajax call such as the $alms_list = data; but i cant find the correct syntax to use. I have done some research and i think i need to loop through the rows, and use the .append? But i cant get this to work. Any help would be greatly appreciated. views.py '''python def home(request): #alms_list = data.objects.filter(date__gt=myDate).order_by('-date') myDate = timezone.localtime(timezone.now()) # Get Current Time formatedDate = myDate.strftime("%d-%m-%Y %H:%M:%S") alms_list = data.objects.filter(alm_date__gt=myDate).order_by('alm_date') return render(request, 'home.html', {'alms_list' : alms_list, 'date': formatedDate }) def get_more_tables(request): myDate = timezone.localtime(timezone.now()) # Get Current Time formatedDate = myDate.strftime("%d-%m-%Y %H:%M:%S") alms_list = data.objects.filter(alm_date__gt=myDate).order_by('alm_date') return render(request, 'get_more_tables.html', {'alms_list' : … -
How to make the a database field accept just one value for an user
I'm trying to associate a user with a paypal account, and just one. Which means that if there is a value on that field, the post request should return "There is already a value there" or simply don't work (Return status code 400). I've tried using the UniqueTogetherValidator in the serializer and use and ID as well. The problem with this approach is that it requires an 'id' field in the post request which is not generated yet (The id is auto-generated by the framework). Here is what I'm trying with my serializer implementation class PaypalAffiliateSerializer(serializers.ModelSerializer): # id = serializers.ReadOnlyField(required=False) class Meta: model = PaypalAffiliate validators = [ UniqueTogetherValidator( queryset=PaypalAffiliate.objects.all(), fields=['paypal', 'id'] ) ] fields = ('paypal', 'id') and here is my model class PaypalAffiliate(models.Model): paypal = models.EmailField() affiliate = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.paypal class Meta: unique_together = ('paypal', 'affiliate') How can I make the PayPal email field accept just one value for every user?