Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django-filer, URL that is 'seperate' from admin
I am trying to set up django-filer on my website. I cannot figure out how to get the URLS to be separate from the admin site on the website. localhost:8000/admin/filer/folder/ Is where it wants to go now, which of course requires someone to have complete admin access in the /admin portion. I want them to have just filer access and be able to see the site. I have my base urls.py as: urlpatterns = [ path('admin/', admin.site.urls), path('accounts/', include('accounts.urls')), # new path('accounts/', include('django.contrib.auth.urls')), path('filer/', include('filer.server.urls')), ] Going to localhost:8000/filer does nothing though? I was hoping I was able to create a local little dropbox functionality with my django website where registered users can use it, though they don't have to be admin in the /admin Is this even possible? I didn't see it in the documentation for filer at all? -
Django trigger script inside multiple different popups
I am new to django and trying to run a script when a user clicks on a confirmation button located inside a popup. This button is located inside a table that contains various information, including an ID, which I would like to pass to the script. Here is the table in the index.html file {% for st in scrapestats %} <tr> <td class="text-left">{{st.market}}</td> <td>{{st.start|date:"Y-m-d H:i:s"}}</td> <td>{{st.end|date:"Y-m-d H:i:s"}}</td> <td>{{st.finished_count}}/{{st.total_count}}</td> <td><a href="#"><span class="badge">{{st.ads}}</span></a></td> <td><a href="#"><span class="badge">{{st.ads_feedback}}</span></a></td> <td><a href="#"><span class="badge">{{st.user}}</span></a></td> <td><a href="#"><span class="badge">{{st.seller_feedback}}</span></a></td> <td><button type="button" name={{st.process_id}} class="btn btn-danger btn-xs confirm" data-toggle="modal" data-target="#Modal-{{st.process_id}}"> Revert </button> <!-- Modal --> <div class="modal fade" id="Modal-{{st.process_id}}" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h3 class="modal-title" align='left' id="delete-server-{{st.process_id}}">Are you sure you want to delete process id {{st.process_id}} ?</h5> </div> <div class="modal-body" align='left'> This might be dangerous ! </div> <div class="modal-footer"> <!-- <form action="#" method="POST" id="call_delete_server"> --> <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button> <button type="button" id="confirm_deletion" data-id={{st.process_id}} class="btn btn-primary">Delete</button> <!-- </form> --> </div> </div> </div> </div> </tr> {% endfor %} And the script, also in the index.html <script> $("#confirm_deletion").click(function (e) { console.log($(this).attr("data-id")); }); </script> What happens is that when I click on the last button in the {% for st in scrapestats %} loop, it correctly outputs … -
Django: Could not parse the remainder: ': "cht"' from 'chart_list|load_charts: "cht"'
I want to embed graphs into my django project and I am now trying out chartit. It looks promising, especially because it can be modified inside the view. views.py from chartit import DataPool, Chart from .models import SalesReport def sales(request): sales = DataPool( series= [{'options': { # 'source': SalesReport.objects.all()}, 'source': SalesReport}, #'source': SalesReport.objects.filter(sales__lte=10.00)}, 'terms': [{'month': 'month', 'sales': 'sales'}] }, ]) def monthname(month_num): names = {1: 'Jan', 2: 'Feb', 3: 'Mar', 4: 'Apr', 5: 'May', 6: 'Jun', 7: 'Jul', 8: 'Aug', 9: 'Sep', 10: 'Oct', 11: 'Nov', 12: 'Dec'} return names[month_num] #Step 2: Create the Chart object cht = Chart( datasource = sales, series_options = [{'options':{ 'type': 'column', 'stacking': False}, 'terms':{ 'month': [ 'sales'] }}], chart_options = {'title': { 'text': 'Sales Amounts Over Months'}, 'xAxis': { 'title':{'text': 'Sales Total'}}, 'yAxis': { 'title': {'text': 'Month Number'}}, 'legend': { 'enabled': True}, 'credits': { 'enabled': True}}, x_sortf_mapf_mts=(None, monthname, False)) #Step 3: Create a second chart object cht2 = Chart( datasource = sales, series_options = [{'options':{ 'type': 'pie', 'plotBorderWidth': 1, 'zoomType': 'xy', 'legend':{ 'enabled': True, }}, 'terms':{ 'month': [ 'sales'] }}], chart_options = {'title': { 'text': 'Sales Amounts Over Months - Pie Chart'}, 'xAxis': { 'title':{'text': 'Sales Total'}}, 'yAxis': { 'title': {'text': 'Month Number'}}, 'legend': … -
Get model name for absoulte url in django 2
Im newi in django and tried to showing absolute path and pass to my template in django I have model and want use one of field to user by loop in template Models.py calss KPI(models.Model): name=models.Charfield(max_length=100) category=models.ForeignKey(category,related_name='categorys' , one_delete=models.CASCADE) Views.py def dashbaords(request): category_list = category.objects.all() category_url = request.build_absolute_uri() return render (request,Dashboard.html,{'category_list':category_list,'category_url',category_url} urls.py urlpattern:[ path{'<int:pk>/',views.dashboards,name='dashbaords'), ] template: {% for category in domain.categorys.all %} <li> <a href={{category_url}}></li> {{category.name}} </a></li> Now url shown 127:0.0.1/dashbaord1 But get error page not found and not shown dashbaord.html after im going to absolute url for them -
As maintain a new post responding only on one button, "Save"?
On the page of adding a post there are fields and buttons to select the relief / background. But when you click on any button is saving the post. How to implement the creation of posts, reacting only to one button "Save"? If now when you press any button in ... the post is saved. It is necessary that when you click other buttons, there was a change in the Iframe without reloading the page {% load static %} <head> <meta charset="UTF-8"> <link rel="shortcut icon" type="image/x-icon" href="https://static.codepen.io/assets/favicon/favicon-8ea04875e70c4b0bb41da869e81236e54394d63638a1ef12fa558a4a835f1164.ico" /> <link rel="mask-icon" type="" href="https://static.codepen.io/assets/favicon/logo-pin-f2d2b6d2c61838f7e76325261b7195c27224080bc099486ddd6dccb469b8e8e6.svg" color="#111" /> <title>Creating presentations</title> <script src="https://aframe.io/releases/0.7.0/aframe.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <link href="https://fonts.googleapis.com/css?family=Arya" rel="stylesheet"> <link rel="stylesheet" type="text/css" href="../static/css/cssmenu.css"/> <link rel="stylesheet" href="{% static 'css/cssmenu.css' %}"> <style> body { font-family: "Arya", sans-serif; display: flex; } body #left { text-align: left; } body #left h2 { margin: 15px 0px 0; } body #left #select { display:inline-block; } body #left #select #color , body #left #select #picture { display:inline-block; flex-direction: column; padding: 0px 0px; } body #left #select #color button, body #left #select #picture button { font-family: "Arya", sans-serif; padding: 18px 18px; outline: none; cursor: pointer; border: none; border-radius: 5px; box-shadow: 0 0px #95a5a6; margin: 8px 0px; font-size: 12px; display: inline; } body #left #select … -
Django PostgreSQL - Fuzzy Searching on single words
I'm using Django's builtin trigram_similar lookup and TrigramSimilarity class to create a fuzzy searching using a PostgreSQL database. This way, I filter titles of articles. The problem is, this filters based on the whole title. I want to filter it also on parts on title. Example: Title of Article: "We are the world | This is the best article ever". My search: "we" In this example, my function returns nothing, but I want it to return this article. How can I do that? This is the code I use: def search(qs, term, fields=["title"], treshold=.3): if len(fields) >= 2: return qs.annotate( similarity=Greatest( *[TrigramSimilarity(field, term) for field in fields] ) ).filter(similarity__gte=treshold).order_by("-similarity") return qs.filter( **{"{}__trigram_similar".format(fields[0]): term} ) -
Display data in tabular format from database in web page for more than 100,000
I have more than 100,000 transactions in the Database on a daily basis. I want to display it in tabular format on the client-side(e.g web site). Q1: Which javascript or python library should I use? Q2: Can javascript or python library display the data, What if data exceeds more than 1 million. Q3: Can javascript or python library display the data, if data exceeds more than 1 million like after 10 days e.g if the user is interested in the last two to 3 days transaction history. -
How to loop through a list of dictionaires in another file on a block code on an html file?
This is kinda hard to explain. I'm building a web app using Django and I created a template in which a for loop loops through a list of dictionaires on the views.py file. Then when I run the website is a blank page. I'm using PyCharms and I've tried to inject a language on the block of code, Python and Html, but when injecting python it says that list is not defined and when using Html the website is just blank. If I don't inject a language it says that there is a typo on the word endfor. #list on views.py file posts = [ { "author": "Telmo Antunes", "title": "Blog post 1", "content": "First Post Content", "date_posted": "September 9th, 2019"}, { 'author': "Telmo Antunes", 'title': "Blog post 2", 'content': "2nd Post Content", 'date_posted': "September 9th, 2019"} ] #template <body> {% for post in posts %} <h1>{{ post.title }}</h1> <p>By {{ post.author }} on {{ post.date_posted }}</p> <p>{{ post.content }}</p> {% endfor %} </body> I was expecting the output on the website to be Blog post 1 By Telmo Antunes on September 9th, 2019 First Post Content Blog post 2 By Telmo Antunes on September 9th, 2019 2nd Post Content -
How get the Engine value of my server when this dont included in the django default settings
i am new in programation web with python, and have a problem with the connection to my database, i have already the values of name, user, pass, host, but for the connection requires too Engine value, the database dont belongs to any server predeterminates , like mysql, sqlLite, postgre etc ... i i dont know how get this value, the documentation says configure to a fully qualified path(mypackage.bakend.whaterver). Anyone know? Regards django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details. -
Django Rest API's sub routes are not accessible on AWS Elastic Beanstalk
I have a Rest API developed with Django Rest Framework. It is completely functional when running locally with: python manage.py runserver All requests work as expected: 127.0.0.1:8000/ 127.0.0.1:8000/projects/ Now the issues arise when deploying from a cloud service such as AWS Elastic Beanstalk or Google App Engine. The defaut route works fine as shown below. The projects route however does not load. The request code received varys by platform. App Engine give a 502 Bad Gateway code and Beanstalk gives a 504 Gateway Timeout. With Beanstalk, running eb logs reveal no errors. projects-restapi-dev.us-west-2.elasticbeanstalk.com/ projects-restapi-dev.us-west-2.elasticbeanstalk.com/projects I'm certain the issue has something to do with how i'm routing my views. Here's my urls.py from django.contrib import admin from django.conf.urls import url from django.urls import path, include from projects.views import ProjectView from rest_framework import routers router = routers.DefaultRouter() router.register(r'projects', ProjectView) urlpatterns = [ path('', include(router.urls)), path("projects/", ProjectView), path("admin/", admin.site.urls), path("api-auth/", include('rest_framework.urls')) ] Also, here's a link to the github repo if you need to see any other files. -
What is the difference between using Python's Request library and Django's APICient from a unit test
I am trying to write unit tests for an Django OAuth2 API. I am using Django's APIClient library. if I use it from a Django shell. it works perfectly, but if I use is in a unit test, the POST request to the view works fine (200 OK), however the post inside of the view's function, fails with 400 bad request. If the user already exists in the database, the Unit test works fine and an access code is returned. if not, it fails. The API POST request to the view works from Postman. it works inside a unit test using Python's Requests library. All requests from a Django shell work (APIClient, Requests, RequestsClient, APIRequestFactory). For this reason, I am guessing that it is a Middleware issue? However, why does unit test using Requests work, yet all the other libraries fail? I understand that unit tests run on a different database to the application server, but even when I change the SETTINGS so that the Tests use the same SQLite database as the application server, the results are the exact same. ### This works perfectly in a Django Shell from rest_framework.test import APIClient client = APIClient() response = client.post('http://127.0.0.1:8000/authentication/register/',{"username": "testuser17", … -
Authentication credentials were not provided drf
when i trying to access api i'm getting this error: "detail": "Authentication credentials were not provided." i have included this in settings.py: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES':( 'rest_framework.authentication.TokenAuthentication', ), 'DEFAULT_PERMISSION_CLASSES':( 'rest_framework.permissions.IsAuthenticated', ) } my app api urls.py: from django.urls import path,include from . import views from rest_framework import routers router = routers.SimpleRouter() router.register(r'',views.UserViewSet, 'user_list') urlpatterns = router.urls my views.py: class UserViewSet(viewsets.ModelViewSet): queryset = User.object.all() serializer_class = serializers.UserSerializers my main urls.py: urlpatterns = [ path('admin/', admin.site.urls), path('',include(urls)), path ('', include(user_urls)), path('api/',include(api_urls)), when i running localhost:8000/api i'm getting the error -
Django-select2 selects pk (IntegerField) instead of username (CharField) and fails
My goal is to create a form to add a rental for a device including a user. Device and user are implemented with a ForeignKey, and for the user i want to use django-select2 , because of the heavy amount of users. models.py class Device(models.Model): name = models.CharField( verbose_name = "Gerätename", max_length = 128, unique = True, ) def __str__(self): return self.name class ldap_data(models.Model): username = models.CharField(max_length=1024, unique=True) class Meta: ordering = ('username',) def __str__(self): return self.username class Rental(models.Model): user = models.ForeignKey(ldap_data, on_delete=models.CASCADE) device = models.ForeignKey(Device, on_delete=models.CASCADE) date_start = models.DateField() date_end = models.DateField() class Meta: ordering = ('date_start',) def __str__(self): return self.device forms.py class RentalForm(forms.ModelForm): user = forms.ChoiceField( widget=ModelSelect2Widget( model=ldap_data, search_fields=['username__icontains'] ) ) date_start = forms.CharField(label="Datum Ausleihe", help_text="", widget=forms.TextInput(attrs={'id': 'datepicker', 'class': 'form-control form-control-sm', 'placeholder': '01.01.2019' })) date_end = forms.CharField(label="Datum Rückgabe", help_text="", widget=forms.TextInput(attrs={'id': 'datepicker2', 'class': 'form-control form-control-sm', 'placeholder': '01.01.2019' })) class Meta: model = Rental fields = ['device', 'user', 'date_start', 'date_end',] The form works so far, but if i select a user from the django-select2 field user, the form complains, Select a valid choice. 1 is not one of the available choices. It looks like the form tries to validate the pk (=1) of the selected user, instead of the username … -
How to fix "AttributeError: 'Settings' object has no attribute 'ROOT_URLCONF'"
I have a coding interview tomorrow (my first ever! Super excited/nervous) and am working to bring an old project of mine back to life and updated: a producthunt clone built in Django/Python. Everything used to run fine with it and now, after git cloning it into a ubuntu virtualbox and bringing things up to date in its virtualenv, I'm stuck with the following error and have come up empty handed after hours of troubleshooting and researching similar issues on stackoverflow. Any help is appreciated. The error: 'AttributeError: 'Settings' object has no attribute 'ROOT_URLCONF'' Settings and output: settings.py """ Django settings for producthunt project. Generated by 'django-admin startproject' using Django 1.10.5. For more information on this file, see https://docs.djangoproject.com/en/1.10/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.10/ref/settings/ """ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '@(b=ndac@9k%w#y7(h5p!^a!)6y_p2&oln@lsz6x61=wyusg4(' import os import django django.setup() # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/ # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ROOT_URLCONF = 'producthunt.urls' ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'compressor', … -
django-extensions: graph_models: What is the meaning of double circle dots indicate
I have created a model_graph by python manage.py graph_models -a -o basic_django_models.png This is a small part of it What is the meaning of line with double circular dots (i.e circular dot on each ends). Between Group and Permission in the above diagram. I understood single dot as foriegn key like between Content_type and Permission -
Adding a scheduled task (cron) on the save action of model object
I have a model object which has day of month and time of that day stored in it. On the save action I want to create a cron job to execute on that day and time. I am using apscheduler (https://github.com/agronholm/apscheduler) and django-apscheduler (https://github.com/jarekwg/django-apscheduler) libraries. Unfortunately, when I save the object, I get following lines in debug: DEBUG:apscheduler.scheduler:No jobs; waiting until a job is added If I save the same object once again then the scheduler picks it up. The reason I deduced is that my code exits before the job is added to the scheduler. I tried may ways but now I am clueless how to implement is. scheduler.py import logging from apscheduler.schedulers.background import BackgroundScheduler from django_apscheduler.jobstores import DjangoJobStore, register_events, register_job from django.conf import settings # Create scheduler to run in a thread inside the application process scheduler = BackgroundScheduler() scheduler.add_jobstore(DjangoJobStore(), 'djangojobstore') def start(): if settings.DEBUG: # Hook into the apscheduler logger logging.basicConfig() logging.getLogger('apscheduler').setLevel(logging.DEBUG) register_events(scheduler) scheduler.start() models.py def save(self, *args, **kwargs): # ToDo: check and update the scheduler for JMR from portal.scheduler import scheduler from django_apscheduler.jobstores import register_events from portal.functions import generate_jmr job_id= f'c_{self.company.id}_generate_jmr' job = scheduler.get_job(job_id=job_id) if job is not None: scheduler.remove_job(job_id=job_id) jmr_day = self.jmr_generation_date jmr_time: datetime.time = … -
How can I use a fieldset with a custom form?
I am trying to make a collapsible fieldset in a model. When I apply the fieldset it create a problem with some of the fields above. The problem is because I have some fields that are foriegn keys with a custom autocomplete form. And when I add these feilds to the fieldset they do not have the form which is needed. I have tried: fieldsets = ( (None, { 'fields': ('autocomplete_field_1', 'autocomplete_field_2', 'field_3'), }), ('advanced', { 'classes': ('collapse',), 'fields': ('field_4', 'field_5'), }), ) And I have tried only having the advanced fieldset, but that will not display autocomplete_field_1, autocomplete_field_2 or field 3. -
How to display details from database to html template in Django?
I am making a registration form with the help of medium.com. Admin display some information from database to html template using some syntax. But how to display email, portfolio site ? -
Advice on how to parse large and dynamic json results
I am looking for some advice on how to best automatically parse and display a large, dynamic json result to my Django app. The data comes from a variety of server hosts and it has a similar but content each time. The user would simply like to see the entire file in a nice, readable format. I am thinking tables. I don't want to create and manage template tags for each item in the file, but rather have them auto-created based on the contents. Note: I do have the data available as a {{ context }} tag in Django template, and the view, template parts are all working fine. For example, the following is just a snippet of the output coming from the json output, and I would like to create tables from this data auto-magically. "processes": [ { "id": "daq-emd", "status": "EXEC", "process_id": 6828, "started": "2019-08-20T05:20:26", "last_updated": "2019-09-09T16:53:09", "parameters": { "isExecuting": "1", "isRunning": "1", "physicalMemoryUsageMb": "162.48", "virtualMemoryUsageMb": "152.14" } }, { "id": "daq-extipxml", "status": "EXEC", "process_id": 7124, "started": "2019-08-20T05:20:24", "last_updated": "2019-09-09T16:53:09", "parameters": { "clientConnected": "1", "clientDisconnectedEvent": "1", "clientDisonnectedEvent": "0", "dataOutageEvent": "0", "incorrectMessages": "34876", "isExecuting": "1", "isRunning": "1", "lastAcknowledgedMessage": "30256", "lastAcknowledgedMessageSent": "4709086", "lastKeepAlive": "2019-09-09T16:52:36Z", "lastReceivedData": "2019-09-09T16:53:01Z", "last_Flightplan": "2019-09-09T16:53:00Z", "last_FlightplanUpdate": "2019-09-09T16:53:01Z", … -
How to solve horizontal scroll on Django admin pages
The problem is that on pages with long text in some fields list table becomes too wide and there is only one way to scroll it - you have to scroll to the bottom where you will find horizontal scroller. So if you need to see something on the right of the first row you will scroll down, right and back to top. This is very annoying. Is there a way to avoid scrolling without truncating data? Is there a way to add horizontal another scroller on top of the table? -
How can I insert data into the database using django form?
I am trying to use django form to insert some information into the database, but the insert is now working properly. This is for form page with some inputs that I am using. > <!DOCTYPE html> <html lang="en"> > <head> <!-- /Css --> <link rel = "stylesheet" type = "text/css" href = "../static/survey.css" /> <!-- /Css --> > <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>Preencha a pesquisa de satisfação</title> > > <style> > * { > box-sizing: border-box; > } > > input[type=submit] { > background-color: #4CAF50; > color: white; > padding: 10px 10px; > border: none; > border-radius: 4px; > cursor: pointer; > float: right; > } > > input[type=submit]:hover { > background-color: #45a049; > } > > .col-25 { > float: left; > width: 50%; > margin-top: 6px; > } > > .col-75 { > float: left; > width: 100%; > margin-top: 5px; > } > > /* Clear floats after the columns */ > .row:after { > content: ""; > display: table; > clear: both; > } > </style> <!-- /Fonts --> <link href='https://fonts.googleapis.com/css?family=Comfortaa' > rel='stylesheet'> <link > href="https://fonts.googleapis.com/css?family=Poppins:100,100i,200,200i,300,300i,400,400i,500,500i,600,600i,700,700i,800,800i,900" > rel="stylesheet"> <!-- /Fonts --> </head> <body> > > <h2>Pesquisa de satisfação</h2> … -
How to filter posts by a specific user in Django?
I want to set up a newsfeed website for my college. There must be tabs in the navbar like, Current News, Literary Society, Clubs, Placement News etc. How do I go about making those tabs functional? For e.g., Current News will be the homepage, Literary Society will show the posts by a user named 'Literary Society' and so on.I'm a beginner and all this is just overwhelming me. Please help me out. -
Make a Django post request to ManyToManyField
This is my List in the HTML document I have a Django post view, when I hit send I want the selected users to be posted to the students field. As you can see I have tried to do the instance and user thing from this url but I can't figure it out! HTML: {% for elev in elever %} <div class="custom-control custom-checkbox"> <span class="d-flex align-items-center"> <div style="margin-right: 10px"> <div class="circle" style="background-color: {{ elev.color }}"> <span class="initials" , style="color: #ffffff"> {{ elev.user|capfirst|first }} </span> </div> </div> <div style="width: 300px"> <span class="h6 mb-0" data-filter-by="text">{{elev.user|capfirst}}</span> </div> <div class="checkboxx"> <input type="checkbox" name="Studyplan-Canview" value= "{{ student.name }}"> <style> .checkerName { margin-left: 10px } .checkboxx { align-content: flex-end; margin-left: 300px } </style> </div> </span> </label> </div> {% endfor %} The View: #post request checker @login_required def skapa_studieplan(request): if request.method == 'POST': name = request.POST.get('Studyplan-Name') description = request.POST.get('Studyplan-Description') parent_assignment = Assignment.objects.get(pk=request.POST.get('Studyplan-PAID')) users = UserProfile.objects.all() instance = Studyplan.objects.create(request.POST.get('Studyplan-Canview')) for user in users: instance.canview.add(user) studyplan = Studyplan(name=name, description=description, parent_assignment=parent_assignment, canview=instance) studyplan.save() return redirect('allaStudieplaner') -
How to prepopulate an each formset line from select option?
I am using Django for an project. The target is to implement an invoice table using Django formset. I want now when i will select an option, the other fields of a formset line will be prepopulated. For dynamic adding and deleting formset row, i use jquery.formset.js found on github. It is difficult to realize it simply for me because formset structure is not so clear for me and i have not the level in javascript. I would want help about how to prepopulate other fields from selecting option. Reminding that for table, i use django formset employing jquery.formset.js script. -
Django constraints: if foreignkey is empty, then field must be true
I'm reading Django's documentation on CheckConstraint to avoid overriding the .save() method to achieve this behavior: MyModel(models.Model): user = models.ForeignKey(User, null=True) is_default = models.BooleanField() if m.user is None and m.is_default -> valid if m.user is None and not m.is_default -> invalid if m.user is not None and m.is_default -> invalid if m.user is not None and not m.is_default -> valid Basically, I want is_default to be true only if user is assigned. Can I do this with CheckConstraint or am I forced to override the .save() method?