Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django + gunicorn + nginx + supervisor -> upstream request timeout
As I mentioned in the title we use Django + gunicorn + nginx + supervisor set for our API. We have the followings configurations: nginx: server { listen 9003 default_server; server_name localhost; client_max_body_size 20G; proxy_connect_timeout 300; proxy_send_timeout 300; proxy_read_timeout 300; send_timeout 300; client_body_timeout 300; location / { proxy_pass http://unix:/tmp/app.sock; proxy_set_header Host $host; proxy_connect_timeout 300; proxy_send_timeout 300; proxy_read_timeout 300; send_timeout 300; client_body_timeout 300; } } supervisor: [program:app-gunicorn] command = gunicorn --bind unix:/tmp/app.sock app.wsgi:application --workers 2 --timeout 300 --threads 100 stdout_logfile=/dev/stdout stdout_logfile_maxbytes=0 stderr_logfile=/dev/stderr stderr_logfile_maxbytes=0 When the request taking more than ~ 15 seconds I get: response: upstream request timeout status: 504 Gateway Timeout timings: Request Timing Blocked: 0 ms DNS Resolution: 0 ms Connecting: 0 ms TLS Setup: 0 ms Sending: 0 ms Waiting: 15.12 s Receiving: 0 ms I would like to increase the timeout limit but as I can see at my configuration it is already set up to 300s. Any ideas what could help me? Cheers! PS. Locally, Django is handling requests that take longer than 15 seconds, so it is not a Django issue. -
leading and trailing flower braces in python
there was some piece of code where leading and trailing flower braces. But I can't find it. read_file = False file_extension = None if not use_meta_driver: _, file_extension = os.path.splitext(name) (status_obj, conf_file_path) = get_config_file_path(name) if Status.is_vunet_status_success(status_obj) is False: LOGGER.error("Failed to find if the config file exists or not ") return (status_obj,None) # Check if we have cached entry if not CONFIGURATION_ENTRY.get(name, None): status_obj, mod_time = FileUtils.get_file_changed_time(conf_file_path) read_file = True else: # Check if the associated file has changed in between. status_obj, mod_time = FileUtils.get_file_changed_time(conf_file_path) if Status.is_vunet_status_success(status_obj) is False: LOGGER.error("Failed to get the last modified time of file %s", conf_file_path) # If file has changed, then we read it again if mod_time != LAST_MODIFIED_TIME.get(name, None): read_file = True if read_file: (status_obj, file_fp) = FileUtils.open_file(conf_file_path, "r") if Status.is_vunet_status_success(status_obj) is False: LOGGER.error("Failed to open config file %s", conf_file_path) return (status_obj, None) (status_obj, output_json_str) = FileUtils.read_data(file_fp) if Status.is_vunet_status_success(status_obj) is False: LOGGER.error("Failed to read config file %s", conf_file_path) FileUtils.close_file(file_fp) return (status_obj, None) status_obj = FileUtils.close_file(file_fp) # read the file # Note: We currently support only yml and json formats. if file_extension == ".yml": (status_obj, output_dict) = JsonUtils.convert_yaml_to_python_dict(output_json_str) else: (status_obj, output_dict) = JsonUtils.parse_json_data(output_json_str) if Status.is_vunet_status_success(status_obj) is False: LOGGER.error("Failed to parse configuration") return (status_obj, None) Can anyone … -
How do I keep my box element from distorting or getting out of shape when shown on different size browsers
I am new to this and I want to make a place to display products which I have successfully done however when it opens on a window that is not full screen it takes the shape of that window and distorts the product image etc how can I fix this <div class="row"> {% for product in products %} <div class="col-lg-4"> <img class="thumbnail" src="{{product.imageURL}}"> <div class="box-element product"> <p><light>{{product.name}}</light></p> <hr> <button data-product="{{product.id}}" data-action="add" class="btn btn-outline-secondary add-btn update-cart">Add to Cart</button> <a class="btn btn-outline-success" href="#">View</a> <h4 style="display: inline-block; float: right"><light>${{product.price|floatformat:2}}</light></h4> </div> </div> {% endfor %} -
how to submit POST request to django using fetch in js and render a new template
I want to submit data using fetch and post as the method and after that use Django render template to return a new HTML page. Django receives the request but the user doesn't get the new HTML page! This the JS that I'm using fetch("/flightbuy", { method: 'POST',credentials: "same-origin", redirect: 'follow', headers: { "X-CSRFToken": csrftoken, } }) .then(response => { console.log(response) // HTTP 301 response }) .catch(function(err) { console.info(err + " url: " + url); }); And this is my views.py def flightbuy(request): print("received") return render(request, "index.html") how do I fix this? Thanks :) -
relation "weather_city" does not exist
When I push my django project to heroku I get "relation "weather_city" does not exist". weather is the name of the app and city is a model. models.py from django.db import models # Create your models here. class City(models.Model): name = models.CharField(max_length=25) def __str__(self): return self.name class Meta: verbose_name_plural = 'cities' -
How to do DB update in a single query in django when using an IF condition?
I have the following code - testcase = Table1.objects.filter(ID=id,serialno ='1234', condition='False').exists() if not testcase: c = Table1.objects.filter(ID=id,serialno ='1234').select_for_update().update(condition='True') Here, I am querying the same DB twice. Is there any way where I can do the filter exists and update in a single query? -
Implementing Many try statement for different models in Django
I have different models, but in my view, I want to create two try statement and reflect it in my template. Here's my code for easy understanding: Class summary (LoginRequiredMixin,View): Def get (self,*args,**kwargs): try: order=Homeorder.objects.get(user=self.request.user,ord=False) ord_men=Menorder.objects.get(user=self.request.user,ord=False) context={'object':ord, 'ord_men':ord_men} return render (self.request,'summary/summary.html',context) Except ObjectDoesNotExist: messages.error(self.request, "you've not yet order") return redirect ('/') And in my template, this is what I plan on doing {%for order in object.home_items.all %} {%for men_order in ord_men.men_items.all %} Is it possible?, Thanks -
I'm doing crud operations with vue js, axios and django restapi but i can't upload photo
I'm doing crud operations with vue js, axios and django restapi I can create an ad model. However, when I add a photo to the image of the Ad model, I'm getting an http 400 error. The interesting thing is that I created a separate model, serializer and view with only foreign key and image field and made the crud operations without any problems. I cannot create a model by uploading an image when the following list is available what could be the problem? ## Data ## profileData:{ image: null, title: "1q", description: "qqqq2qq", price: 200, square_meter: 200, number_of_rooms: 1, building_age: 1, floor: 0, number_of_floors: 2, number_of_bathrooms: 1, heating: 2, balcony_exists: false, using_status: 0, housing_shape: 2, status: 0, visibility: 0, frontal: [1], interior_feature: [1], exterior_feature: [1], locality: [1], transportation: [1], landscape: [1], suitable_for_disabled: [1] } method methods:{ advertiseCreate(){ return this.$store.dispatch('createAdvertiseDataActions',this.profileData) } } -
Django dynamic admin forms
I am having trouble with some django admin functionalities what I want to do is to have 2 fields in an admin page and I want to achieve this field_A field_B if field_A == "specific value": exclude = ("field_B",) else: fields = ("field_A","field_B") Please Help -
Data Toggle Information Passing
Hello I have django project where I list images and I want that if someone click on one image it gets bigger. It works that a new little window is appearing but because I am getting the image source via template tagging I was not able to pass the information to the window. I will post my template and hope that I was understandable. Thank you very much. html <div class="container"> <h1 style="text-align:center;">{{lecturer.lecturer}}</h1> <hr> {% for i in distribution%} <div class='img1'> <a data-toggle="modal" data-target="#exampleModalimg" href="#"> <img name="pic" src="{{ i.distribution.url }}"> --->I am clicking here </a> <p style="text-align:center;">{{i.lecture}} | {{i.semester}}</p> </div> {% endfor %} </div> <div class="modal fade" id="exampleModalimg" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-body"> <img name="pic" src="{{ i.distribution.url }}"> ---> but I could not pass i </div> </div> </div> </div> -
Django app's DB user failed authentication in AWS
Here is Django setting.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'rulings', 'USER': 'postgres', 'PASSWORD': '******', 'HOST': '', 'PORT': '', } } In AWS, when I run a server, an error message occurs. File "/home/app_admin/venv_ruling/lib64/python3.7/site-packages/psycopg2/__init__.py", line 127, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError: FATAL: Peer authentication failed for user "postgres" How can I run the server with the user name of postgres?? When I use another user name it will run without a problem, but I want to use "postgres" as a user. -
How to collect a changing variable from a views.py function to the template without reloading in django
I am creating a chatbot using django and tflearn, I have to completed the code to some extent, i have been able to post data from the template to the views.py function ('home') using javascript, but the things is i can't collect the current output from the chatbot, it is always returning the first result not the current result, although in the console it print the actual result. This are my codes. Thank you views.py from django.shortcuts import render from django.http import JsonResponse, HttpResponse from .apps import chat # Create your views here. def home(request): result = request.POST.get("data") if result == None: result = 'hi' else: result = request.POST.get("data") print (str(result)) mycontent = chat(str(result)) context = {'mycontent':mycontent} print (mycontent) return render(request, 'alice/index.html', context ) index.html <div class="col-sm-3 col-sm-offset-4 frame"> <ul></ul> <div> <form method='POST' id ='post-form'> {% csrf_token %} <div class="msj-rta macro"> <div class="text text-r" style="background:whitesmoke !important" > <input class="mytext" id='data' name="next" placeholder="Type a message"/> </div> </div> <div style="padding:10px;"> <button id="button" type= 'submit' name="button" onclick="myFunction()">send</button> <script type="text/javascript"> function myFunction() { insertChat('me',document.getElementById("data").value, 0) insertChat('you', '{{mycontent}}', 0) } </script> </div> </form> </div> </div> </body> <script type='text/javascript' src="{% static 'js/main.js' %}"></script> </html> main.js var me = {}; me.avatar = "https://lh6.googleusercontent.com/-lr2nyjhhjXw/AAAAAAAAAAI/AAAAAAAARmE/MdtfUmC0M4s/photo.jpg?sz=48"; var you = {}; … -
Error: (1062, “Duplicate entry 'search-laft_cadaveres_cni_identificados' for key 'django_content_type_app_label_model_76bd3d3b_uniq'”)
if someone can do me a favor to help with this error, I would appreciate it very much, every time I run the command python manage.py migrate search to migrate my models I get this error although it performs well migrations to my database data: Error: (1062, "Duplicate entry 'search-laft_cadaveres_cni_identificados' for key 'django_content_type_app_label_model_76bd3d3b_uniq'") Thank you very much. -
Search results aren't printed in the website, only in the command line
so I added a new page to my website to search for 'people' items. The thing is, whenever I search for an item, the result shows in my command line but it's not printed in the website, the only thing that is are the tags but with the empty result, like this: Gender: Age: Eye color: Film: So the result of the query is not printed out. Why is this happening? This is my view: from django.shortcuts import render, HttpResponse from django.views.generic import ListView import requests def people(request): people = [] if request.method == 'POST': people_url = 'https://ghibliapi.herokuapp.com/people/' search_params = { 'people' : 'name', 'people' : 'gender', 'people' : 'age', 'people' : 'eye_color', 'q' : request.POST['search'] } r = requests.get(people_url, params=search_params) results = r.json() if len(results): for result in results: people_data = { 'Name' : result['name'], 'Gender': result['gender'], 'Age' : result['age'], 'Eye_Color' : result['eye_color'] } people.append(people_data) else: message = print("No results found") print(people) context = { 'people' : people } return render(request,'core/people.html', context) This is the html: {% load static %} <!DOCTYPE html> <html> <head> <title>Ghibli Studio | People</title> <link rel="stylesheet" href="{% static 'core/people.css' %}"> </head> <body> <div class=" header"> </div> <div class="wrap"> <form action='/people' method="POST"> {% csrf_token %} <div … -
Finished making a model in django, tested in the views and tried to save form data but didn't work
I tried making a model and a modelform and tested it in the views ... Source Code models.py class FileUploads(models.Model): FILE_TYPE_CHOICES = ( ('No file type selected ...', 'No file type selected ...'), ('Stylesheets', 'Stylesheets'), ('JavaScript', 'JavaScript'), ('Documents', 'Documents'), ('Images/Pictures', 'Images/Pictures'), ('Scripts', 'Scripts'), ) user = models.ForeignKey(Profile, on_delete=models.CASCADE, verbose_name="User Profile") file = models.FileField(upload_to='storage/files/', blank=False, null=False, validators=[ FileExtensionValidator([ # Image Files "tiff", "svg", "pdf", "raw", "webp", "gif", "heif", "heic", "psd", "ind", "indt", "indd", "png", "jpg", "jpeg", "jfif", "bmp", "dib", "pdf", "arw", "cr2", "nrw", "k25", "tif", "jfi", "jpe", "jif", "ai", "eps", "svgz" "jp2", "j2k", "jpf", "jpx", "jpm", "mj2" # Stylesheet Files "css", "less", "sass", "scss", # Scripts / JavaScript Files "py", "js", "ts", # Misc: (Microsoft Word) "docx", "txt", ]) ], verbose_name="File Path") file_name = models.CharField(max_length=50, default="File name needs to be provided!") file_type = models.CharField(max_length=25, choices=FILE_TYPE_CHOICES, default="no file type selected ...") created_at = models.DateTimeField(default=timezone.now) class Meta: verbose_name_plural = "File Uploads" views.py from django.shortcuts import render from .forms import FileUploadsForm from django.http import HttpResponseRedirect from user_profiles.models import Profile from django.contrib.auth.decorators import login_required @login_required def profile_view(request): user = request.user profile = Profile.objects.get(username=user) form = FileUploadsForm(request.POST or None, request.FILES or None, instance=profile) if request.method == "POST": if form.is_valid(): instance = form.save(commit=False) instance.person = request.user instance.comment_to … -
Store value in a variable in jinja template for later use
Hello please give a solution to my problem: I want to store a value to a variable by the below method but unable to do that {% if tags %} {% for t in tags %} {% if t.job_post_one != "hide" %} "Store the value of t.job_post_one here "` later use that value at the end of the html for filtering results based on that value. -
In Django have created custom permissions and assigned permissions to group and user but @permission_required fails
I have created a custom permission in my user model: class User(AbstractUser): first_name=models.CharField(max_length=40, null=True, blank=True) actual_user = models.CharField(max_length=20, null=True, default=None) class Meta: permissions = (("can_switch_user", "Switch user"),) I have migrated the permissions in, added the permission to a group, and have assigned the user the permission and the group. When I test to see if the user has the permission it does not. @login_required def hello(request): context = { "name": request.user.username, "actual_user": request.user.actual_user, "groups": Group.objects.all(), "permissions": request.user.user_permissions.first(), "switch_user": request.user.has_perm('users.can_switch_user')} return render(request, "testapp/hello.html", context) I have also tried the permission "users.user.can_switch_user' When I display the results via hello.html I get: Hello user1 Actual user: user1 Group: Perms: users | user | Switch user Can Switch User False Why am I not getting the correct permissions? Do I need to create a check_permissions method in my user model to make this work or am I doing something else incorrectly. -
Serving static files through a view in Django
I am following this example to add Djangos template functionality to my css files. I got it all running, however during this process I encountered a problem I am not sure what to think about. I tried to redirect the created css files to the static directory, so I could still use the {% load static %} methods. However this does not seem to be possible! For example my static URL looks as follows: STATIC_URL="/static/" Now when I create my urls as following: #in urls.py path("static/", include([path('<str:filename>', views.css_renderer), ])), And my views as following: # in views.py def css_renderer(request, filename): return render(request, 'example_website/css_templates/{filename}'.format(filename=filename), content_type="text/css") And my empty template # file location: \example_website\css_templates\basic_style.css # This file is just empty Now when I try to access the file under http://127.0.0.1:8000/static/basic_style.css I get a Page not found (404) which was raised by example_website.views.css_renderer. Now if I just change the static URL in the settings to STATIC_URL="/something_else/" then the css file is found and all is fine. Why and how is that and how might I circumvent this maybe? Thanks very much! -
Is there a way to update cart and navigate to a different page with a button?
Please i have a code which when the button Get Ticket is clicked, i want it to update the cart and navigate to the Cart page here's the code: <a href="{% url 'cart' %}"><button type="button" data-post={{post.id}} data-action="add" class="btn btn-primary update-cart">Get Ticket</button></a> from the code: <button type="button" data-post={{post.id}} data-action="add" class="btn btn-primary update-cart"> this part updates the cart but doesnt allow it to navigate to cart, when i delete it, it navigate accordingly, how do i go about it please. Thank you -
Invalid Token Error : Invalid token specified: Cannot read property 'replace' of undefined
Hi I'm using Django for the Backend and Angular for the Frontend , when I try to login I receive a Invalid Token Error : Invalid token specified: Cannot read property 'replace' of undefined , Do you know what is the problem ?? here is the sode of user.service.ts import { Injectable } from '@angular/core'; import {HttpClient,HttpHeaders, HttpInterceptor, HttpRequest, HttpHandler, HttpEvent} from '@angular/common/http'; import { Observable } from 'rxjs/Observable'; import { CanActivate,Router } from '@angular/router' import { tap, shareReplay } from 'rxjs/operators'; import * as jwtDecode from 'jwt-decode'; import * as moment from 'moment'; import { environment } from '../environments/environment'; @Injectable({ providedIn: 'root' }) export class UserService { constructor(private http:HttpClient, private _router: Router) { } private setSession(authResult) { const token = authResult.token; const payload = <JWTPayload> jwtDecode(token); const expiresAt = moment.unix(payload.exp); localStorage.setItem('token', authResult.token); localStorage.setItem('expires_at', JSON.stringify(expiresAt.valueOf())); } loginUser(userData):Observable<any>{ return this.http.post('http://127.0.0.1:8000/MyProjects/auth/', userData ).pipe( tap(response => this.setSession(response)), shareReplay(), ); } } interface JWTPayload { user_id: number; username: string; email: string; exp: number; } -
Celery with Redis broker and multiple queues: all tasks are registered to each queues
I am using celery with Django and redis as the broker. I'm trying to setup two queues: default and other. My tasks are working, but the settings I have configured are not working have I am expecting them to work. I'm having two related issues: celery tasks are not respecting the task_routes setting (see below). all of the celery tasks (no matter how they are defined) are registered to each of the two queues when they are started Here are the relevant parts of my code: the celery app definition file task definitions/declarations commands to start workers celery app definition: from celery import Celery from django.conf import settings from kombu import Exchange, Queue CELERY_QUEUE_DEFAULT = 'default' CELERY_QUEUE_OTHER = 'other' app = Celery('backend') app.conf["broker_url"] = f"redis://{settings.REDIS_SERVICE_HOST}:6379/1" app.conf["result_backend"] = f"redis://{settings.REDIS_SERVICE_HOST}:6379/2" app.conf["accpet_content"] = ['application/json'] app.conf["task_serializer"] = 'json' app.conf["result_serializer"] = 'json' app.conf["task_acks_late"] = True app.conf["task_default_queue"] = CELERY_QUEUE_DEFAULT app.conf["worker_send_task_events"] = True app.conf["worker_prefetch_multiplier"] = 1 app.conf["task_queues"] = ( Queue( CELERY_QUEUE_DEFAULT, Exchange(CELERY_QUEUE_DEFAULT), routing_key=CELERY_QUEUE_DEFAULT, ), Queue( CELERY_QUEUE_OTHER, Exchange(CELERY_QUEUE_OTHER), routing_key=CELERY_QUEUE_OTHER, ), ) app.conf["task_routes"] = { 'backend.core.tasks.debug_task': { 'queue': 'default', 'routing_key': 'default', 'exchange': 'default', }, 'backend.core.tasks.debug_task_other': { 'queue': 'other', 'routing_key': 'other', 'exchange': 'other', }, } app.conf["task_default_exchange_type"] = 'direct' app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) Task definitions (defined in a file called tasks.py in an … -
Python gnupg verify detached file signature when both file and signature are in memory (Django ContentFile objects)
I have a django server to which two files are sent - a document, and a signature. These are both Django ContentField objects (FileObjects, to all intents and purposes, so seekable, readable, etc). I am trying to verify the signature using python gnupg's verify_data or verify_file methods (I've tried both). I've used all combinations of passing in the raw file object, converting it to a string first - etc, everything. Everytime, the output suggests that there is no valid signature. Is the only way to do this to write the files to disk, and then verify the signature? I'm trying to avoid this, since the intention is not to store the files if the signature doesn't check out. -
Django React multiple app Deploy to Heroku Module Error
I have a project with django for backend, django for part of the front end, and react for the rest of the front-end. yourenv -bin -lib -src --api (django) ---apps.py ---models.py ---... --frontend (react) ---build ---node_modules ---src ----App.css ----App.js ----... --frontendOld (django) ---apps.py ---models.py ---... --staticfiles --trydjango ---_pyache_ ---urls.py ---settings.py ---wsgi.py ---Procfile ---requirements.txt ---runtime.txt ---... --manage.py Before I had successfully deployed with the files in their current hierarchy and git init inside of trydjango, but when I went to the Heroku url there was an Application Error; the error included "cannot find module trydjango". I tried to make git init inside of yourenv instead of inside of trydjango, moved and returned the Procfile, requirements, and runtime files and am now getting this error after git push heroku master: App not compatible with buildpack: https://buildpack-registry.s3.amazonaws.com/buildpacks/heroku/python.tgz remote: More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure remote: remote: ! Push failed I have the heroku/python and heroku/nodejs web packs attached. Procfile: release: python3 manage.py migrate web: gunicorn trydjango.wsgi --log-file - requirements.txt: asgiref==3.2.7 beautifulsoup4==4.9.1 certifi==2020.6.20 chardet==3.0.4 click==7.1.2 coreapi==2.3.3 coreschema==0.0.4 Django==3.0.7 django-bootstrap3==14.0.0 django-bootstrap4==2.2.0 django-cors-headers==3.4.0 django-filter==2.3.0 django-jquery==3.1.0 django-rest-registration==0.5.6 django-und==0.1.1 djangorestframework==3.11.0 djangorestframework-jsonapi==3.1.0 djangorestframework-jwt==1.11.0 djangorestframework-simplejwt==4.4.0 dominate==2.5.1 Flask==1.1.2 Flask-Bootstrap==3.3.7.1 gunicorn==20.0.4 idna==2.10 inflection==0.5.0 itsdangerous==1.1.0 itypes==1.2.0 Jinja2==2.11.2 MarkupSafe==1.1.1 PyJWT==1.7.1 pytz==2020.1 requests==2.24.0 soupsieve==2.0.1 sqlparse==0.3.1 typing==3.7.4.3 uritemplate==3.0.1 urllib3==1.25.10 … -
Returning altered text after Markdown to HTML Conversion
I'm creating my own markdown-to-html converter. In this piece of code the text should be returned bolded, but it doesn't. Here is the code: def query(request, title_name): content = util.get_entry(title_name) bold_pattern = re.compile('[(\*\*|__)]{2}(?P<bold_text>[\w\s]+)[(\*\*|__)]{2}') bold_matches = re.finditer(bold_pattern, content) new = "" for match in bold_matches: pos_x = content.find(match.group()) pos_y = pos_x+len(match.group()) new = re.sub(bold_pattern, match.group("bold_text"), content[pos_x:pos_y]) content = content.replace(content[pos_x:pos_y], f'<b>{new}</b>') mark_safe(content) return render(request, ".../entry.html",{ "content": content, "title": util.get_page_name(title_name) }) Is there something im missing before returning it to HTML? Here is my simple entry.html: {% extends ".../layout.html" %} {% block title %}{{ title }}{% endblock title %} {% block body %} {{content}} <p>Edit this page <a href="{% url 'edit' title %}">here</a></p> {% endblock body %} -
Migration error on Django + django-oauth-toolkit
I have an django application with version 2.2.13 and django oauth toolkit 1.0.0. In the effort to update to Django 3.0, I need to update the django-oauth-toolkit, but every version after version 1.0.0, I run into a migration problem because my application (oauth2) extends the abstract application (AbstractApplication) model from the oauth2_provider (from django-oauth-toolkit). from oauth2_provider.models import AbstractApplication class Application(AbstractApplication): # there are more fields added here pass This custom oauth application (oauth2) has 28 migrations that were generate inside the project itself. When we try to run all migrations from scratch (we do this on our CI Server), we get an error trying to run migration 0001 for this app: ValueError: Related model 'oauth2.Application' cannot be resolved. There is an issue similar to my problem open on the project, https://github.com/jazzband/django-oauth-toolkit/issues/778, but workaround provided does not work, and I have not found other solution to it. Thanks.