Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django race condition in simultaneous ModelForm submission
My model has a field working_hour which is IntegerField, I am using ModelForm and django-crispy-forms.Assume tow different people has rendered form with working_hour value 20 and both of them want to increase working_hour by 10 and they updates the working_hour form field from 20 to 30.When they both submit the form, updated working_hour becomes 30 in database, but it should be 40. models.py class OverallHour(models.Model): working_hour = models.PositiveIntegerField() forms.py class OverallHourForm(ModelForm): class Meta: model = OverallHour def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.add_input(Submit('submit', 'UPDATE')) overall_hour_form.html {% extends "base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="row justify-content-center"> <div class="col-md-8"> <div class="card bg-light"> <div class="card-body"> {% crispy form %} </div> </div> </div> </div> {% endblock content %} Can you please advice me how to fix this problem? -
I Wagtail how to disable certain admin menu items for the certain users?
For the group of users I want to disable some menu items. I thought I will use the following: from wagtail.contrib.modeladmin.options import ModelAdmin as WModelAdmin class WPartnerAdmin(WModelAdmin): ... def get_menu_item(self, order=None): menu_item = super().get_menu_item(order=order) # if (user_discrimination_logic): # menu_item.is_shown = lambda *a: False return menu_item But it seems that I don’t have access to the request object in the ModelAdmin, therefore don’t know how to extract the user data. Is there a way? -
Django __init__() takes at least 2 arguments (1 given)
Im getting this error when I try to login to my django app. I dont know what is happening, it worked 30 minutes ago and I havent touched anything since then. views.py def login_page(request): form = LoginForm(request.POST or None) context = { "form": form } next_ = request.GET.get('next') next_post = request.POST.get('next') redirect_path = next_ or next_post or None if form.is_valid(): username = form.cleaned_data.get("username") password = form.cleaned_data.get("password") user = authenticate(request,username=username,password=password) if user is not None: login(request,user) try: del request.session['guest_email_id'] except: pass if is_safe_url(redirect_path,request.get_host()): return redirect(redirect_path) else: request.notifications.add('Hello world.') messages.add_message(request, messages.INFO, 'Hello world.') return redirect("/") else: print("Error") return render(request, 'accounts/login.html',context) forms.py class LoginForm(forms.Form): username = forms.CharField(widget=forms.TextInput(attrs={"class":"form-control","placeholder":"Your Username"})) password = forms.CharField(widget=forms.PasswordInput(attrs={"class":"form-control","placeholder":"Your Password"})) Traceback File "/usr/lib/python2.7/dist-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/usr/lib/python2.7/dist-packages/django/core/handlers/base.py" in _legacy_get_response 249. response = self._get_response(request) File "/usr/lib/python2.7/dist-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/usr/lib/python2.7/dist-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/django/django_project/accounts/views.py" in login_page 42. user = authenticate(request, username=username,password=password) File "/usr/local/lib/python2.7/dist-packages/lockout/decorators.py" in wrapper 43. result = function(*args, **kwargs) File "/usr/lib/python2.7/dist-packages/django/contrib/auth/init.py" in authenticate 68. for backend, backend_path in _get_backends(return_tuples=True): File "/usr/lib/python2.7/dist-packages/django/contrib/auth/init.py" in _get_backends 29. backend = load_backend(backend_path) File "/usr/lib/python2.7/dist-packages/django/contrib/auth/init.py" in load_backend 23. return import_string(path)() Exception Type: TypeError at /login/ Exception Value: init() takes at least 2 … -
Django pass parameter when using urls include
In urls.py I dynamically create objects and want to create urls for each of them. I can iterate over them and include another urls file into my main urls.py like this: urlpatterns = [path(object.url, include('bar.urls')) for object in objects] However, in my application I want to pass the variable object to bar.urls that can be passed to the views afterward. I wonder if I can do something like this: urlpatterns = [path('foo', include('bar.urls', my_var=object)) for object in objects] and in bar: # bar.urls (got my_var somehow) urlpatterns = [path('foo', views.foo, object=my_var)] # bar.views def foo(request, object) # use object -
Django store foreign then submit form
How to use foreign key to create a new value and use that to submit the form before failing the if form.is_valid(). Issue is the foreign key is doesn't exit, want use to input the data and which like to use that as foreign key value and submit the form. MODEL: class AirportCode(models.Model): name = models.CharField(max_length=4, default=None, blank=True, unique=True) class AddData(models.Model): airportcode = models.ForeignKey(AirportCode, on_delete=models.SET_NULL, null=True) FORM: class Airportcode_Form(forms.ModelForm): class Meta: model = AirportCode fields = ('name',) class AddData_Form(forms.ModelForm): class Meta: model = Pull fields = ('airportcode',) def __init__(self, *args, **kwargs): super(AddData_Form, self).__init__(*args, **kwargs) self.fields['airportcode'].queryset = CODE.objects.none() if 'airportcode' in self.data: c = self.data.get('airportcode') self.fields['code_pull'].queryset = CODE.objects.filter(name=c) VIEW: def save(request): if request.method == 'POST': if form.is_valid(): add = form.save(commit=False) add.airportcode = form.cleaned_data['airportcode'] add.save() return redirect(save) else: messages.error(request, form.errors) context = {'form': form } return render(request, template_name, context) Getting error when submitting form, as the field Airportcode is not selected. Thanks for the help in advance -
Django. REST Framework. Rename SerializerMethodField()
In the django rest framework, I have a serializer, it takes fields from the model, combines it under one tag, and displays it in xml. Everything is simple. I understand how it works. But what I don’t understand is how to rename the parent tag. I will show: #serializers.py class kvSerializerLivingSpace(serializers.ModelSerializer): unit = serializers.CharField(default='qm') class Meta: model = kv fields = ['unit', 'value'] class kvSerializer(serializers.ModelSerializer): living_space = serializers.SerializerMethodField() class Meta: model = kv fields = ['living_space'] def get_living_space(self, obj): return kvSerializerLivingSpace(obj).data I need living_space through a hyphen. To make it look like living-space I know that i can rename tags as follows: def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields.update({ 'living-space': kvSerializerLivingSpace() }) But this does not work for serializers.SerializerMethodField() Thank! -
Why is GET and POST request converting to OPTIONS request for cross-origin request for django rest framework and reactjs frontend?
I was looking to run my django and reactjs web application on mobile by connecting it to mac via hotspot, and changing the host to the ipaddress of the mobile. Thus, I changed my localhost to 192.168.43.19 in /etc/hosts/, and thus, my code is easily shared between mobile and mac, and I am able to run the localhost app on my mobile which is connected to mac via hotspot. The backend is created in django rest framework. The problem is that all the get and post calls to the api created in the backend in django is being converted to options calls, and thus there are no returns, and the code is not working properly. While searching online, it said that the issue is because by default Access-cross-origin-policy is not allowed. To try handling the issue, I added the frontend url in CORS_ORIGIN_WHITELIST in the settings file of the django app, but it didnt work. It will be really helpful, if someone could recommend me the correct way to handle this? -
Django request nonexistent permissions for User creation
In my Django project I have a custom User model named Employee, which is configured in the settings as follows: AUTH_USER_MODEL = 'employees.Employee' When I try to add a new Employee via the admin interface, everything works as expected if I am logged in as a superuser. However, if I do not have the superuser roll, Django responds: Your user does not have the "Change user" permission. In order to add users, Django requires that your user account have both the "Add user" and "Change user" permissions set. Both "Change employee" and "Add employee" permissions have been granted to the user; "Change user" and "Change user" permissions do not exist, since the original User model does not exist (is replaced with Employee) How to solve this issue? -
When running the server the image,tittle and price didn't display on the webpage. I've just started learning programming 5 months ago. Help me please
from django.shortcuts import render def index(request): products = [ {'title': 'Fuct "playboy" pocket tee', 'price': 30, 'image': 'https://instagram.fmkz1-1.fna.fbcdn.net/vp/a6d3c0ce1196c2613b202f5c6917b2a7/5DF11D66/t51.2885-15/e35/s1080x1080/69037434_409676526336836_2753352954002356161_n.jpg?_nc_ht=instagram.fmkz1-1.fna.fbcdn.net'}, {'title': 'Levis big E 507XX type 2 selvedge jacket', 'price': 90, 'image': 'https://instagram.fmkz1-1.fna.fbcdn.net/vp/d3f3c4e7e0e44158e48ce3ac0cc92fd5/5E0D553F/t51.2885-15/e35/s1080x1080/61871643_497887490776394_4216653965002551874_n.jpg?_nc_ht=instagram.fmkz1-1.fna.fbcdn.net'}, {'title': 'vintage nike big swoosh', 'price': 40, 'image': 'https://instagram.fmkz1-1.fna.fbcdn.net/vp/f396f9a17e49ae57d862620cefae2bd6/5DF7D52A/t51.2885-15/e35/s1080x1080/67370121_563369154199572_8476318391380511268_n.jpg?_nc_ht=instagram.fmkz1-1.fna.fbcdn.net'}, ] context = { 'products': products, } return render(request, 'webapp/index.html', context) -
Creating a simple multiplayer game, currently working on mitigating latency, does this sound right?
I'm essentially making this game multiplayer: http://jsfiddle.net/PxpVr/16/embedded/result/ You can check it out at apollius.com To mitigate latency, I'm sending out the game state to both clients every time a player turns. Should I be updating the state periodically instead? I've gotten a lot of advice that is all over the place. Please help -- thanks in advance apollius -
Factory_boy - implicitely generate random values based on field type
I'm new to Factory_boy. I need it to generate data to my Django project so I'm using DjangoModelFactory. class UserFactory(DjangoModelFactory): class Meta: model = 'user.User' User.objects.last().__dict__ {'_state': <django.db.models.base.ModelState at 0x7f788c3aed30>, 'id': 67, 'password': '', 'last_login': None, 'is_superuser': False, 'username': '', 'first_name': '', 'last_name': '', 'email': '', 'is_staff': False, 'is_active': True, 'date_joined': datetime.datetime(2019, 8, 30, 18, 50, 9, 104838, tzinfo=<UTC>), 'is_office_user': False} Is there a way it tries to generate random data based on field type? I have a huge models and I don't want to explicitely define each field. -
What pythonic solution to use when creating a task to run in the background?
I am using Django (1.11) for an API. The endpoint that I am working on creates an excel document from DB data, but will often take over a minute to process (the hosting site will timeout the request if it takes over 1 minute). I want to have a request that starts a background/subprocess/async task/etc... that does the processing in the background and saves to a shared storage location, while the response hands back a "ticket number" for the front-end to use to check back periodically to see if the task is done or not. (thereby not triggering the one minute timeout) The problem I am having is that I'm not sure what to use for the background process part. I have used threading and subprocessing in the past, and more recently I have heard good things about asyncio. I don't care about what the background process returns, I only care that it completes its task (which can be checked through searching the shared storage). I also don't want the background processes to accumulate, so I need something that will self-close as soon as it's done with processing the data. What is the best way to tackle this issue? Thanks! -
ModuleNotFoundError: No module named 'tzwhere'
In my windows 10 os When i run my python project i got error ModuleNotFoundError: No module named 'tzwhere' I've tried to install tzwhere pip install tzwhere ERROR: Command errored out with exit status 1: command: 'c:\users\raj\envs\py1\scripts\python.exe' -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\temp\pip-install-3lryfis_\shapely\setup.py'"'"'; file='"'"'C:\temp\pip-install-3lryfis_\shapely\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' egg_info --egg-base pip-egg-info cwd: C:\temp\pip-install-3lryfis_\shapely\ Complete output (9 lines): Traceback (most recent call last): File "", line 1, in File "C:\temp\pip-install-3lryfis_\shapely\setup.py", line 80, in from shapely._buildcfg import geos_version_string, geos_version, \ File "C:\temp\pip-install-3lryfis_\shapely\shapely_buildcfg.py", line 200, in lgeos = CDLL("geos_c.dll") File "c:\users\raj\appdata\local\programs\python\python37\Lib\ctypes__init__.py", line 356, in init self._handle = _dlopen(self._name, mode) OSError: [WinError 126] The specified module could not be found ---------------------------------------- ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. from tzwhere import tzwhere tzwhere = tzwhere.tzwhere() I need to install tzwhere in my windows command prompt -
Annotate QuerySet using raw SQL
In case I am asking the wrong question, let me first state the end goal: I need to allow users to filter a ListView by a field that's not in the primary model (Salesleadquote), but instead the field comes from a model (Salesleadbusinessgroup) with a FK to a related model (Saleslead). The way I am trying to approach this is by annotating a field on Salesleadquote. The models: class Salesleadquote(models.Model): salesleadquoteid = models.AutoField(db_column='SalesLeadQuoteId', primary_key=True) salesleadid = models.ForeignKey(Saleslead, models.DO_NOTHING, db_column='SalesLeadId') ... class Saleslead(models.Model): salesleadid = models.AutoField(db_column='SalesLeadId', primary_key=True) ... class Salesleadbusinessgroup(models.Model): salesleadbusinessgroupid = models.AutoField(db_column='SalesLeadBusinessGroupId', primary_key=True) salesleadid = models.ForeignKey(Saleslead, models.DO_NOTHING, db_column='SalesLeadId') businessgroupid = models.ForeignKey(Businessgroup, models.DO_NOTHING, db_column='BusinessGroupId') The desired result (queryset), in SQL: SELECT slq.*, slbg.BusinessGroupId FROM crm.SalesLeadQuote slq LEFT JOIN (SELECT SalesLeadId, BusinessGroupId FROM crm.SalesLeadBusinessGroup ) slbg ON slbg.SalesLeadId = slq.SalesLeadId WHERE slbg.BusinessGroupId IN (5,21) I know I can get a RawQuerySet by doing something like Salesleadquote.objects.raw("SELECT salesleadquote.*, \ salesleadbusinessgroup.businessgroupid \ FROM salesleadquote \ LEFT JOIN salesleadbusinessgroup \ ON salesleadquote.salesleadid = salesleadbusinessgroup.salesleadid \ WHERE salesleadbusinessgroup.businessgroupid IN (5,21)") But I need the functionality of a QuerySet, so my idea was do annotate the desired field (businessgroupid) in Salesleadquote, but I've been struggling with how to accomplish this. -
django: db: what is the diff between connections vs connection
In Django database queries: i found two ways to get the last query: from django.db import connections connections['default'].queries[-1] Or from django.db import connection connection.queries[-1] What is the difference between connections['default'] and connection when to use what. -
Overriding Django's DurationField display
My model has a DurationField which is editable in Django Admin. I don't like how Django (inheriting its behavior from Python) displays negative durations, so I've tried to monkey patch it: test = lambda: duration.duration_string(datetime.timedelta(seconds=-5)) == \ '-00:00:05' if not test(): _duration_string = duration.duration_string def duration_string(duration): if duration.days < 0: return '-' + _duration_string(-duration) return _duration_string(duration) duration.duration_string = duration_string assert test() This code gets run as part of my AppConfig.ready() method. However, in Admin, the field still displays values formatted the default way. Is there some other way to customize how a DurationField's value is rendered in Admin? -
Celery shared data
I have implemented websocket in Django app using Django-channels, now the front-end send some data through the websocket and i want the current running celery task to be able to read it. I tried creating shared memory static object, but not working. SimulationInputs.add(simulation_id=simulation.id, init_data=init_inputs) return InteractiveSimulationTask.delay_or_fail( simulation_id=simulation.id ) class SimulationData: data = '' class SimulationInputs: data = None @classmethod def init_manager(cls, manager): manager = Manager() cls.data = manager.dict() @classmethod def add(cls, simulation_id, init_data): cls.data[simulation_id] = init_data @classmethod def write(cls, simulation_id, simulation_data): if cls.data.get(simulation_id): cls.data[simulation_id] = simulation_data @classmethod def read(cls, simulation_id, simulation_data): simulation_data.data = cls.data.get(simulation_id) # manage.y if __name__ == "__main__": SimulationInputs.init_manager() class InteractiveSimulationTask(JobtasticTask): def calculate_result(self, simulation_id, **kwargs): while True: SimulationInputs.read(simulation_id=self.simulation.id, simulation_data=simulation_data) The task always throw exception cls.data.get(simulation_id): NoneObjectType has no method get I need to share data between the celery task and the main process. Any hint? -
ModuleNotFoundError --- Exception Value: No module named 'cart.contexts'
def add_to_cart(request, id): """Add a quantity of the specified product to the cart""" quantity=int(request.POST.get('quantity')) cart = request.session.get('cart', {}) if id in cart: cart[id] = int(cart[id]) + quantity else: cart[id] = cart.get(id, quantity) request.session['cart'] = cart return redirect(reverse('index')) -
Inconsistent results with queries of JSONFields in Django
I have a model like this: class Task(models.Model): data = JSONField(encoder=DjangoJSONEncoder) and data is populated with either {deleted: true} or {}, but in the future might also have {deleted: false}. I'm trying to find how many Tasks are not deleted, but I get inconsistent results depending on what type of query I use. If I use Task.objects.exclude(data__deleted=True), I get 0, which is incorrect. If I use Task.objects.exclude(data__deleted='true'), I get 58, which is incorrect. If I use Task.objects.filter(data__deleted__isnull=False), I get 29, which is correct but only happens to works since I don't have any {deleted: false} in the database currently. Calculating manually like this: count = 0 for task in Task.objects.all(): if not task.data.get('deleted'): count += 1 also works because count is 29. What is the proper query to use to filter the results correctly? -
How to clear all Django migrations from CMD in Windows?
On Unix operating systems, you can simply run: find . -path "*/migrations/*.py" -not -name "__init__.py" -delete find . -path "*/migrations/*.pyc" -delete from your root project folder in order to clear migrations and cache. What is the equivalent to this on Windows? -
Two languages, one view, different url path
I have a django project with two languages. What I want to achieve is to have different url path depend on current language. Not very nice but working solution is: urls.py urlpatterns = [ ... url("strefa-klienta/", views.client_zone, name="strefa_klienta"), url("client-zone/", views.client_zone, name="client-zone"), ... ] vievs.py def client_zone(request): return render(request, "client_zone.html") template.html {% load i18n %} {% get_current_language as LANGUAGE_CODE %} {% if LANGUAGE_CODE == 'pl-PL' %} <a href="{% url 'strefa_klienta' %}">{% trans 'Client zone' %}</a> {% else %} <a href="{% url 'client_zone' %}">{% trans 'Client zone' %}</a> {% endif %} The result is ok, I got urls: domain.com/strefa-kleinta/ - for Polish language domain.com/client-zone/ - for rest languages which renders same view, but... It's not flexible. Maybe you can help and suggest a little more elegant solution? -
How to change the label for username to 'username/email' in login page in Django
I am building a car rental website with Django. Currently working on user authentication.The user can either use his/her username/email and password to login.It's working fine. My question is, how will I change the label for username field to "username/email" so that the user can understand that either username or email can be entered. I cannot make changes in the login.html template because I have used there {{ form.as_p }} tag and the concerned portion in my forms.py file has: class LoginForm(forms.Form): username = forms.CharField() password = forms.CharField(widget=forms.PasswordInput) I am not able to understand where to make changes. Please help. -
Apache2 not showing website after adding djoser, Internal Server Error 500
Adding djoser to my Django app and doing all tests on localhost it works fine. Yet after restarting apache2 (app was already added to apache and working fine), it is giving Internal Server Error 500. Have looked around of what is going on and following these instructions to get an actual error. The following is produced Traceback (most recent call last): File "<path_to_app>/wsgi.py", line 21, in <module> application = get_wsgi_application() File "<path_to_app>/env/lib/python3.6/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application django.setup(set_prefix=False) File "<path_to_app>/env/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "<path_to_app>/env/lib/python3.6/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "<path_to_app>/env/lib/python3.6/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked ModuleNotFoundError: No module named 'djoser' mod_wsgi (pid=7989): Target WSGI script '<path_to_app>/wsgi.py' does not contain WSGI application 'application'. mod_wsgi (pid=8126): Target WSGI script '<path_to_app>/wsgi.py' does not contain WSGI application 'application'. I have no idea why it is saying no module named 'djoser', python/pip tells me it is installed and it is working on localhost. -
Django serializer giving AttributeError int object has no atribute _meta
I was trying to call a django view through ajax call and that django view calls a third party API and returns the response given by the third party API to ajax call. But after getting reponse I'm getting the follwoing error File "/home/sachinmukherjee/Coading/Developement/MovieRecommender/recommender/lib/python3.5/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/sachinmukherjee/Coading/Developement/MovieRecommender/recommender/lib/python3.5/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/sachinmukherjee/Coading/Developement/MovieRecommender/recommender/lib/python3.5/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/sachinmukherjee/Coading/Developement/MovieRecommender/recommender/lib/python3.5/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "apps/apirequest/views.py", line 20, in trendingenglish return JsonResponse(serializers.serialize('json', data), safe=False) File "/home/sachinmukherjee/Coading/Developement/MovieRecommender/recommender/lib/python3.5/site-packages/django/core/serializers/__init__.py", line 128, in serialize s.serialize(queryset, **options) File "/home/sachinmukherjee/Coading/Developement/MovieRecommender/recommender/lib/python3.5/site-packages/django/core/serializers/base.py", line 94, in serialize concrete_model = obj._meta.concrete_model AttributeError: 'int' object has no attribute '_meta' Here is the code for the view function in view.py file from django.shortcuts import render, redirect from django.http import HttpResponse, JsonResponse from django.views.decorators.csrf import csrf_exempt from django.conf import settings import http.client from django.core import serializers # Create your views here. URL = settings.TMDB_URL API_KEY = settings.TMDB_API_KEY @csrf_exempt def trendingenglish(request): request_url = URL + "trending/all/day?api_key=" + API_KEY conn = http.client.HTTPSConnection("api.themoviedb.org") payload = "{}" conn.request("GET", request_url, payload) res = conn.getresponse() data = res.read() return JsonResponse(serializers.serialize('json', data), safe=False) The json reponse from the third party API looks like … -
How do I fix my Django "ValueError: Found wrong number (0) of constraints" migration error?
I'm using Python 3.7 and Django. I tried this solution -- Received "ValueError: Found wrong number (0) of constraints for ..." during Django migration, but still got the same error. I'm having trouble with one of my migrations. I recently updated my unique constraint of my model ... class ArticleSumStatByHour(models.Model): total_score = models.DecimalField(default=0, max_digits=12, decimal_places=2, null=False) total_seconds_to_reach_fp = models.DecimalField(default=0, max_digits=12, decimal_places=2, null=False) num_articles = models.IntegerField(default=0, null=False) hour_of_day = IntegerField( null=False, validators=[ MaxValueValidator(23), MinValueValidator(0) ] ) index = models.FloatField(default=0) website = models.ForeignKey(website, on_delete=models.CASCADE, related_name='articlesumstatbyhoursub') class Meta: unique_together = ("hour_of_day","website") This is my migration, ... class Migration(migrations.Migration): dependencies = [ ('articlesum', '0032_auto_20190808_1452'), ] operations = [ migrations.AlterField( model_name='articlesumstatbyhour', name='website', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='articlesumstatbyhoursub', to='articlesum.website'), ), migrations.AlterUniqueTogether( name='articlesumstatbyhour', unique_together={('hour_of_day','website')}, ), ] but when I run the migration I get this baffling error complaining about "ValueError: Found wrong number (0) of constraints" ... (venv) localhost:articlesum_project davea$ python manage.py migrate articlesum Operations to perform: Apply all migrations: articlesum Running migrations: Applying articlesum.0033_auto_20190830_1128...Traceback (most recent call last): File "manage.py", line 21, in <module> execute_from_command_line(sys.argv) File "/Users/davea/Documents/workspace/articlesum_project/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/Users/davea/Documents/workspace/articlesum_project/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/davea/Documents/workspace/articlesum_project/venv/lib/python3.7/site-packages/django/core/management/base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "/Users/davea/Documents/workspace/articlesum_project/venv/lib/python3.7/site-packages/django/core/management/base.py", line 353, in execute output = self.handle(*args, **options) File "/Users/davea/Documents/workspace/articlesum_project/venv/lib/python3.7/site-packages/django/core/management/base.py", …