Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python allauth disable mail confirmation for oauth apps
I'm new into python and django and I'm developing an app liked to a django server that works as oauth provider. I've set this on settings.py file: ACCOUNT_DEFAULT_HTTP_PROTOCOL = 'https' ACCOUNT_EMAIL_VERIFICATION = 'none' ACCOUNT_EMAIL_REQUIRED = True But if I did not add the verified flag on the mail section in django I cannot login into the app. What should I do in order to remove the verification step? -
Files are being downloaded at pythonanywhere server and user laptop/pc too. How to restrict to write at pythonanywhere server
Problem is i have hosted at pythonanywhere using django.Video is downloaded at pythonanywhere server and user/client system too.Thats why i used os. remove(path).After downloading it removes from server. Is there any ways files donot write on pyhtonanywhere server. so that i donot use os.remove(path). How to restrict to write at pythonanywhere server. Only to download at user system. def fb_download(request): link = request.GET.get('url') html= requests.get(link) try: url= re.search('hd_src:"(.+?)"',html.text)[1] except: url= re.search('sd_src:"(.+?)"',html.text)[1] path=wget.download(url, 'Video.mp4') response=FileResponse(open(path, 'rb'), as_attachment=True) os.remove(path) return response -
ER-Diagram for Users, Images and Likes
I'm looking to create a database (using Django) where: A user uploads photos. A user upvotes/downvotes photos of other users. I came up with this ER diagram: My questions are: Is a vote better as an entity or as an attribute of the photo? If a vote should remain an entity, how do I show in its attributes that the primary key of the vote is the combined foreign keys of the user and the photo? Any constructive comments/recommendations are also welcome. -
Django values method fields param dynamically
How can i pass fields to values method dynamically ? https://github.com/django/django/blob/0c7e880e13b837dd76276c04ebdc338bb76d1379/django/db/models/query.py#L838 Thanks in advance -
how to have multiple forms in a class based view
I have a simple blog app that you can post news and blog on it. I wanted to show the latest posts on the main page, so I created this class like this: class MainListView(TemplateView): template_name = 'Blog/Home.html' def get_context_data(self, **kwargs): context = super(MainListView, self).get_context_data(**kwargs) context['news'] = NEWS.objects.order_by('-published')[:2] context['posts'] = POSTS.objects.order_by('-published')[:3] return context and it works great. however, I wanted to add two additional forms to the main page too. so I added these two functions to the class: def get(self, request, *args, **kwargs): return self.render_to_response({'aform': HomeGholakForm(prefix='aform_pre'), 'bform': HomeContactForm(prefix='bform_pre')}) def post(self, request, *args, **kwargs): aform = _get_form(request, HomeGholakForm, 'aform_pre') bform = _get_form(request, HomeContactForm, 'bform_pre') if aform.is_bound and aform.is_valid(): aform.save() return redirect('Home-Page') elif bform.is_bound and bform.is_valid(): bform.save() return redirect('Home-Page') return self.render_to_response({'aform': aform, 'bform': bform}) and above this class I created a _get_form function in order for it to work: def _get_form(request, formcls, prefix): data = request.POST if prefix in request.POST else None return formcls(data, prefix=prefix) in the final stage I added the forms to my template like this: <form action=""> {% csrf_token %} {{bform.email}} <input type="submit" name="{{bform.prefix}}" class="btn" /> </form> <form action=""> {% csrf_token %} {{aform.info}} <input type="submit" name="{{aform.prefix}}" class="btn" /> </form> After I did this, the problem is neither the … -
Django one sided one-to-many relationship
I guess my understanding in django models are too shallow and I couldn't come up with a solution even with searching for in the internet. Here is the problem: I have a MAC Address model that holds mac addresses. Also I have many models that is related to this MAC Address model like PCs, Access Points, Swtiches etc. Since all these models can have multiple network interfaces (ex. A Desktop can have LAN and WLAN interfaces that has different MAC Addresses) I decided to make a seperate model for MAC Addresses. But I don't really need to see which mac address is related to which asset. So is there a way to make bidirectional one-to-many relationship in django? class MACAddress(models.Model): addr = models.CharField(_('MAC Address'), max_length=17) class AccessPoint(models.Model): #... # This property must be in a form of list or array. mac_addresses = models.OneToMany(MACAddress) Something like that is possible? I saw some Many-to-one relationship examples but all of them shows just how to get related model data. (ex. In a User, Contact model relationship, examples shows how to get User model from Contact model. Which I need the other way around) -
IntegrityError at /api/addorderitem (1048, "Column 'user_id' cannot be null") in Postman in Django Rest Framework
I have added raw data in postman and put JSON format instead of text. But when I call addorderitem api, I am getting error user_id cannot be null. I have posted the picture here. My models: class OrderItem(models.Model) : user = models.ForeignKey(User,on_delete=models.CASCADE, blank=True) ordered = models.BooleanField(default=False) item = models.ForeignKey(Product, on_delete=models.CASCADE,blank=True, null=True) quantity = models.IntegerField(default=1) def __str__(self): return f"{self.quantity} items of {self.item} of {self.user.email}" class Order(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True) items = models.ManyToManyField(OrderItem,blank=True, null=True,related_name="order_items") start_date = models.DateTimeField(auto_now_add=True) ordered_date = models.DateTimeField() ordered = models.BooleanField(default=False) #billing_details = models.ForeignKey('BillingDetails',on_delete=models.CASCADE,null=True,related_name="order") def __str__(self): return self.user.email My serializers: class OrderItemSerializer(serializers.ModelSerializer): class Meta: model = OrderItem fields = ['id','user','ordered','item', 'quantity'] depth = 1 class OrderSerializer(serializers.ModelSerializer): order_items = OrderItemSerializer(many=True) class Meta: model = Order fields = ['id','user','start_date', 'ordered_date', 'ordered', 'order_items'] depth = 1 def create(self, validated_data): order_items = validated_data.pop('order_items') order = Order.objects.create(**validated_data) for order_items in order_items: OrderItem.objects.create(order=order,**order_items) return order My view: class AddtoOrderItemView(ListCreateAPIView): permission_classes = [IsAuthenticated] queryset = OrderItem.objects.all() serializer_class = OrderSerializer My url: path('api/addorderitem', views.AddtoOrderItemView.as_view(), name='api-add-orderitem'), I have given the user id as shown in postman raw data, but still says, user_id is null. Here, I am trying to create an order object by creating order_items objects in the process using nested serailizers. -
How to use percentage sign in annotate key
I'm trying to annotate a result column name with string that includes a percentage sign. This is the simplified code which can be run on any model basically: from django.db.models import F annotates = {'TEST %': F('id')} SomeModel.objects.annotate(**annotates)[:1] This produces error IndexError: tuple index out of range so I assumed Django is trying to do some formatting on that string and I tried putting double percentage sign 'TEST %%' to escape it which does not raise an error but it returns double spaces as column name which is not what I need. Same result in Django 2.2 and 3.1 Is this a Django bug or I'm missing some known escaping sequence here? -
How to add Category while adding product in Django form? Just like the Django admin form
So I am trying to build an inventory system. I have 2 models, Categories and Product connected through the ManyToMany field. I want to add a category while I am adding the product just like it happens in the Django admin form. How can I do that? See the below screenshots to understand what I want to do. I basically want that plus button option to add a category from the product form itself. -
ServerSelectionTimeoutError at / error for mongoclient django
This is my views.py file in django. I imported pymongo and dnspython before running the following code. originally i was able to access my database from mongo atlas. But the next day when it gave me the following error: ServerSelectionTimeoutError at / bt2102g1-shard-00-02.hckrp.mongodb.net:27017: [WinError 10061] No connection could be made because the target machine actively refused it,bt2102g1-shard-00-01.hckrp.mongodb.net:27017: [WinError 10061] No connection could be made because the target machine actively refused it,bt2102g1-shard-00-00.hckrp.mongodb.net:27017: [WinError 10061] No connection could be made because the target machine actively refused it, Timeout: 30s, Topology Description: <TopologyDescription id: 60389dfbdd7743b624b5ff6f, topology_type: ReplicaSetNoPrimary, servers: [<ServerDescription ('bt2102g1-shard-00-00.hckrp.mongodb.net', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('bt2102g1-shard-00-00.hckrp.mongodb.net:27017: [WinError 10061] No connection could be made because the target machine actively refused it')>, <ServerDescription ('bt2102g1-shard-00-01.hckrp.mongodb.net', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('bt2102g1-shard-00-01.hckrp.mongodb.net:27017: [WinError 10061] No connection could be made because the target machine actively refused it')>, <ServerDescription ('bt2102g1-shard-00-02.hckrp.mongodb.net', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('bt2102g1-shard-00-02.hckrp.mongodb.net:27017: [WinError 10061] No connection could be made because the target machine actively refused it')>]> from django.shortcuts import render from django.http import HttpResponse import pprint import re from pymongo import MongoClient # Create your views here. client = MongoClient("mongodb+srv://Group1:BT2102noice@bt2102g1.hckrp.mongodb.net/myFirstDatabase?retryWrites=true&w=majority") db = client["Library"]["Books"] def displayBookCollection(): collection = [] for book in db.find(): collection.append(book) return collection … -
Couldn't find ffmpeg or avconv on linux server
I installed ffmpeg and pydub successfully on my linux server. And test with python enviroment ok. [image run code on python env][1] [1]: https://i.stack.imgur.com/uBH6w.png But when i running my code on nginx + gunicorn + django, its alert with error "/home/www/env/lib64/python3.8/site-packages/pydub/utils.py:170: RuntimeWarning: Couldn't find ffmpeg or avconv - defaulting to ffmpeg, but may not work" Someone can help me ? -
Static files are not loading from Static folder
I am Building a BlogApp and I am stuck on an Problem. The Problem Static Files are not loading from static folder. Some files are loading but some are not loading. What have i done ? urls.py I also put static url in urls.py , it also didn't work for me. urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) settings.py os.path.join(BASE_DIR, "static", "static") STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static_cdn') my_template.html {% load static %} <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Open+Sans:400,600" /> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <title>Next Level - Gallery</title> <!-- Next Level CSS Template https://templatemo.com/tm-532-next-level --> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Open+Sans:400,600" /> <script src="{% static 'comments/all.min.css' %}"></script> <script src="{% static 'comments/bootstrap.min.css' %}"></script> <script src="{% static 'comments/templatemo-style.css' %}"></script> </head> <div class="row tm-welcome-row"> <div class="col-12"> <div class="tm-welcome-parallax tm-center-child" data-parallax="scroll" data-image-src="static/images/blooming-bg.jpg" > <div class="tm-bg-black-transparent tm-parallax-overlay"> <h2>Our Gallery</h2> <p>this is a parallax background image</p> </div> </div> </div> </div> <div class="tm-page-col-right"> <div class="tm-gallery" id="tmGallery"> <div class="tm-gallery-item category-1"> <figure class="effect-bubba"> <img src="static/comments/gallery/gallery-item-01.jpg" alt="Gallery item" class="img-fluid" /> </figure> </div> </div> </div> </div> </section> <script src="{% static 'comments/jquery.min.js' %}"></script> <script src="{% static 'coments/parallax.min.js' %}"></script> <script src="{% static 'comments/imagesloaded.pkgd.min.js' %}"></script> <script src="{% static 'comments/isotope.pkgd.min.js' %}"></script> <script src="{% static … -
Tables in database are not creating in Databas after migrations and migrate in Django
I have a project with multiple apps. In one of the app named as App1 I have an existing model in this app. I want a new model in this app. But the table of new model is not creating in the Database after applying migrations. Followings are the things I have tried: I have deleted the file from migrations folder. python manage.py makemigrations App1 python manage.py migrate --fake APP1 zero but still table in Database of new model is not creating. -
Javascript module management in Django
I am working on a project that has multiple .js file for containing different functions. I want to use the function from M1.js in M2.js and what I am doing is exporting the function from M1.js and importing in M2.js. The export works fine, but the issue is when I import function. M1.js --export {function} M2.js --import {function} from './M1.js' <script type="module" href="{% static 'myapp/M1.js'%} <script type="module" href="{% static 'myapp/M2.js'%} Above is the code that generate following error on import Loading module from “app.com/static/Invoicing/exif_js” was blocked because of a disallowed MIME type (“text/html”). My directory structure is -Project |--project |--Invoicing (App) |--static |--Invoicing |--M1.js |--M2.js |--templates |--etc |--static |--etc -
how to remain original content after updated the post django
I'm working on a project which i need to keep track of activities users , when an existing post will be updated , then i have to still be able to look the original content , similar to facebook posts , when someone edit his/her post , still s/he be able to see the original content ! thank you class Invoice(models.Model): seller = models.ForeignKey(User,on_delete=models.CASCADE) customer = models.CharField(max_length=50) model = models.ManyToManyField(Item,through='InvoiceItem') #others class Item(models.Model): products = models.ForeignKey(Products,on_delete=models.CASCADE) invoice = models.ForeignKey(Invoice,on_delete=models.CASCADE) #others i just want to keep track the admins activity best regards .. -
How to assign the attribute of SubFactory instead of the SubFactory itself
I need the attribute of the SubFactory instead of the object created by it. # models.py class User: pass class UserProfile: user = models.OneToOneField(User) class Job: user = models.ForeignKey(User) # factories.py class UserFactory(factory.django.DjangoModelFactory): class Meta: model = User class UserProfileFactory(factory.django.DjangoModelFactory): class Meta: model = UserProfile user = factory.SubFactory(UserFactory) class JobFactory(factory.django.DjangoModelFactory): class Meta: model = Job # for certain reasons, I want to use UserProfileFactory here but get the user generated from it user = factory.SubFactory(UserProfileFactory).user # doesn't work but you get the idea -
user not getting active after pressing verification link in django
Login and registration page working fine.. But my verification link have some error Views.py from django.shortcuts import render from userprofileinfo.forms import UserForm from django.urls import reverse from django.contrib.auth.decorators import login_required from django.http import HttpResponseRedirect, HttpResponse from django.contrib.auth import authenticate, login, logout from django.views.decorators.csrf import csrf_exempt,csrf_protect from django.views import View from django.contrib import messages from django.core.mail import send_mail from django.contrib.sites.shortcuts import get_current_site from django.utils.encoding import force_bytes, force_text, DjangoUnicodeDecodeError from django.core.mail import send_mail from django.contrib.sites.shortcuts import get_current_site from django.utils.http import urlsafe_base64_decode, urlsafe_base64_encode from django.template.loader import render_to_string from .utils import account_activation_token from django.urls import reverse from django.contrib import auth @login_required def special(request): return HttpResponseRedirect("You are logged in, Nice!") @login_required def userlogout(request): logout(request) return HttpResponseRedirect(reverse('careforallapp:base')) def register(request): registered = False if request.method == "POST": user_form = UserForm(data=request.POST) if user_form.is_valid(): user = user_form.save() user.set_password(user.password) user.is_active = False user.save() email = UserForm('email') current_site = get_current_site(request) email_body = { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), } link = reverse('userprofileinfo:activate', kwargs={ 'uidb64': email_body['uid'], 'token': email_body['token']}) email_subject = 'Activate your account' activate_url = 'http://'+current_site.domain+link send_mail( email_subject, 'Hi '+user.username + ', Please the link below to activate your account \n'+activate_url, 'settings.EMAIL_HOST', [user.email], fail_silently=False ) return HttpResponseRedirect(reverse('careforallapp:base')) else: print(user_form.errors) else: user_form = UserForm() return render(request,'userprofileinfo/registration.html', {'user_form':user_form, 'registered':registered}) class VerificationView(View): … -
Django - how to reuse code in function-based view with decorators
I've got some code that I have to re-use for several views, so I would like to create a decorator so that I don't have to copy and paste many lines of code. So the code I need to re-use in different views is: @login_required def add_custom_word_song(request, target_word, source_word, pk): """ Add new word """ if request.method == 'POST': form = WordForm(request.POST) if form.is_valid(): deck_name = form.cleaned_data['deck_name'] source_word = form.cleaned_data['source_word'] target_word = form.cleaned_data['target_word'] fluency = form.cleaned_data['fluency'] user = request.user Word.objects.create(user=user, target_word=target_word, source_word=source_word, deck_name=deck_name, fluency=fluency) return HttpResponseRedirect(reverse('vocab:list')) if request.method =="GET": user = request.user request.session['pk'] = pk form = CustomWordForm(initial={'user': user, 'target_word': target_word, 'source_word': source_word, 'deck_name': 'My Words', 'fluency': 0}) return render(request, 'vocab/add_custom_initial_song.html', {'form': form, 'pk': pk}) And the only part of the code that will change for the other views is the template part in the last line. So I tried putting everything except the last line in the decorator, but then I get: TypeError: add_custom_word() missing 3 required positional arguments: 'target_word', 'source_word', and 'pk' I tried different variations of this, but still get the same error. -
Generate a random password reset code Djagno
I am in the process of password reset. I want to use sercets in python, but I'm not really sure how to do it better. How should code be checked for correctness? And is it possible to encode the transmitted email into it and decrypt it when checking. Secrets doesn't support this, maybe there are alternatives? -
Django Exporting CSV giving error of HttpResponse
I have written code in Django to export the csv file of all the data which is stored in Django database. However while achieving this I came across this error and it is not getting solved. I am writing down all the necessary code which I edited for exporting the csv. views.py def export(request): response = HttpResponse(content_type='text/csv') writer = csv.writer(response) writer.writerow(['Item Name', 'Vendor Name', 'Date', 'Inward Registry Number']) for fields in Form1.objects.all().values_list('item', 'vendor', 'date','inward'): writer.writerow(fields) response['Content-Disposition'] = 'attachment; filename="fields.csv"' urls.py (Under my django-app) urlpatterns = [ path("export/", views.export, name='export'), ] I have made no changes in models.py still posting it here for reference models.py from django.db import models # Create your models here. class Form1(models.Model): item = models.CharField(max_length=125) quantity = models.IntegerField(default=0) vendor = models.CharField(max_length=125) inward = models.IntegerField(default=1234) date = models.DateField() def __str__(self): return self.item For testing purpose I am going to http://127.0.0.1:8000/export/ to check if excel sheet gets downloaded or not. And I am getting this error their : Let me know how to fix it and one more thing which if you know answer to you can tell, How can I make the font of excel as different, or bold so that it gets downloaded in more readable manner … -
Is there a way to return multiple json objects through django rest api?
I know, I can return a single object through Django viewsets for any method. But can I return multiple objects through the API? I have something like this: class SomeViewSet(viewsets.ModelViewset): queryset = SomeModel.objects.all() serializer_class = SomeDataSerializer filter_backends = [DjangoFilterBackend,] permission_classes = (AllowAny,) @action(methods=['GET'], detail=False, url_path='some_path') def any_function(self, request): queryset = self.filter_queryset(self.get_queryset()) result = any_function(args) return Response(result, status=status.HTTP_200_OK) Any function is defined as: def any_function(args): ... do something with args here and save it as result. ... return result This works very smoothly and I don't have any problem here. BUT can I do something like this: def any_function(args): result = some processing of args next_result = another processing of args return result, next_result And still, get the response in the API endpoint but now for two different data. Also what if the result and next_result are two different JSON objects? -
I want the Django form field to autofill the value from another field and display in the input section of forms
class Assumptions(models.Model): No_of_working_hrs_per_day=models.IntegerField('No. of working hrs. per day',default=None) Attendance_Time_hrs_perday=models.IntegerField('Attendance Time (hrs per day)') Working_minutes_per_day=models.IntegerField('Working minutes per day') No_of_working_days_per_month=models.IntegerField('No. of working days per month') Total_no_of_production_days_per_year=models.IntegerField('Total no of production days per year') No_of_shifts_per_day=models.IntegerField('No. of shifts per day') Exchange_rate=models.IntegerField() in this model the second field value should be first field+1. for eg:(No_of_working_hrs_per_day=8, then Attendance_Time_hrs_perday=9) and the value should be autofield in the form. class AssumptionForm(forms.ModelForm): class Meta: model=Assumptions fields='__all__' -
Trying to run Django and getting AttributeError: module 'secrets' has no attribute 'choice'
''' File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/core/management/init.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/core/management/base.py", line 371, in execute output = self.handle(*args, **options) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/core/management/commands/startproject.py", line 18, in handle options['secret_key'] = get_random_secret_key() File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/core/management/utils.py", line 82, in get_random_secret_key return get_random_string(50, chars) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/utils/crypto.py", line 74, in get_random_string return ''.join(secrets.choice(allowed_chars) for i in range(length)) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/utils/crypto.py", line 74, in return ''.join(secrets.choice(allowed_chars) for i in range(length)) AttributeError: module 'secrets' has no attribute 'choice' ''' -
Static Urls to images using dropbox api
So, i've this project using python(django) and I need to consume the dropbox api to display my images on the website, but I have a large Image's data and when I request a http get method it take to much time until I get a response. Obs: I'm using generate_temporary_link method, and each request the link will be generated again. My code: @staticmethod def generate_jpeg(p, psd_path): from wand.image import Image as wand_Image image_format = "jpeg" image_path = "design/temp/" if not os.path.exists(image_path): os.mkdir(image_path) try: dbx = dropbox.Dropbox(DROPBOX_OAUTH2_TOKEN, timeout=120.0) dropbox_input_path_psd = f"{DROPBOX_ROOT_PATH}{psd_path}" meta = dbx.files_get_temporary_link(f"{dropbox_input_path_psd}") response = requests.get(meta.link) code = f"{p.code} {p.color_variant}" if p.color_variant else p.code filename = f"{code}.{image_format}" image_full_path = f"{image_path}{filename}" with wand_Image(blob=bytes(response.content)) as img: if img.width > img.height: img.rotate(-90) img.save(filename=image_full_path) size = os.path.getsize(image_full_path) if size > 1417000: img.resize(1080, int(1080 * img.height // img.width)) img.save(filename=image_full_path) # upload with open(image_full_path, 'rb') as f: dbx.files_upload(f.read(), f"{DROPBOX_INPUT_PATH_SMALL}{code}.{image_format}", # mode=dropbox.files.WriteMode.overwrite ) p.image = f"{DROPBOX_INPUT_PATH_SMALL}{filename}".replace(DROPBOX_ROOT_PATH, '') p.save() try: for file in os.listdir(image_path): os.remove(f"{image_path}{file}") except Exception as e: with open("errors.txt", 'a') as f: f.write(str(e)) print('could not clear local images') logger.error('could not clear local images') except Exception as e: with open("errors.txt", 'a') as f: f.write(str(e)) print(f"_____________generate jpeg error- {e}") logger.error(f"_____________generate jpeg error- {e}") There is another solution to … -
Enforcing db ancestor relationship constraints
I have the following db structure: RST -< RS | | ^ ^ RSLT -< RSL Is there a way I can maintain integrity from RSL to RST (ie RSL.RSLT.RST == RSL.RS.RST) with a db constraint? Also, is there a terminology for this pattern? I hate that we have two routes to the same ancestor relationship, but don't believe there's a way around it, hence the desire to introduce a db constraint for it. Bonus points if you have tricks for how to define such a constraint in the Django Model meta.