Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use model functions in Views for multiple instances in Django?
I have a Blog Post Model and I have defined a function to calculate the no of likes. The Model is as follows -> class Post(models.Model): user = models.ForeignKey(User, on_delete=models.PROTECT) title = models.CharField(max_length=255) description = models.CharField(max_length=1000,null=True) Tags = models.CharField(max_length = 255,null=True,blank=True) Created_date = models.DateTimeField(auto_now_add=True) Updated_date = models.DateTimeField(auto_now=True) category = models.ForeignKey(Category, on_delete=models.PROTECT) Likes = models.ManyToManyField(to=User, related_name='Post_likes') def __str__(self): return self.title def likesCount(self): return self.Likes.count() Now I am querying the Post Model from the DB to get all the Posts as follows -> posts = Post.objects.select_related().prefetch_related('images_set','comments_post').annotate(Count('comments_post')).all() Here when I loop over the posts I can call the likesCount function and it gives me the correct result as well but I want to return the No of likes to the template. How can I do that? -
React vs Django : Which framework shall I learn
I am front end developer[React]. I also want to learn the backend. I am confused due to contradictory statement in different blogs etc. Some says that node may be out of date after some time. So says node is better to learn than Django. Can someone help me by providing the authentic information. So learn the framework. Thanks in advance. -
How add 0 when TruncWeek's week no result in Django Query?
I want query the issue's count of group by weekly. query1 = MyModel.object.filter(issue_creator__in=group.user_set.all()).\ annotate(week=TruncWeek('issue_creat_date')).values('week').annotate(count=Count('id')).order_by('week')) the query result is OK. the queryset result: [ {'week': datetime.datetime(2022, 1, 3, 0, 0, tzinfo=<DstTzInfo 'Europe/Stockholm' CEST+2:00:00 DST>), 'count': 9}, {'week': datetime.datetime(2022, 1, 10, 0, 0, tzinfo=<DstTzInfo 'Europe/Stockholm' CEST+2:00:00 DST>), 'count': 12}, {'week': datetime.datetime(2022, 1, 17, 0, 0, tzinfo=<DstTzInfo 'Europe/Stockholm' CEST+2:00:00 DST>), 'count': 10}, {'week': datetime.datetime(2022, 2, 7, 0, 0, tzinfo=<DstTzInfo 'Europe/Stockholm' CEST+2:00:00 DST>), 'count': 1}, {'week': datetime.datetime(2022, 2, 14, 0, 0, tzinfo=<DstTzInfo 'Europe/Stockholm' CEST+2:00:00 DST>), 'count': 6}, {'week': datetime.datetime(2022, 2, 21, 0, 0, tzinfo=<DstTzInfo 'Europe/Stockholm' CEST+2:00:00 DST>), 'count': 11}, {'week': datetime.datetime(2022, 2, 28, 0, 0, tzinfo=<DstTzInfo 'Europe/Stockholm' CEST+2:00:00 DST>), 'count': 1} ] but 20220101-20220301 has 9 weeks: [ datetime.datetime(2022, 1, 3, 0, 0, tzinfo=<DstTzInfo 'Europe/Stockholm' CEST+2:00:00 DST>), datetime.datetime(2022, 1, 10, 0, 0, tzinfo=<DstTzInfo 'Europe/Stockholm' CEST+2:00:00 DST>), datetime.datetime(2022, 1, 17, 0, 0, tzinfo=<DstTzInfo 'Europe/Stockholm' CEST+2:00:00 DST>), datetime.datetime(2022, 1, 24, 0, 0, tzinfo=<DstTzInfo 'Europe/Stockholm' CEST+2:00:00 DST>), datetime.datetime(2022, 1, 31, 0, 0, tzinfo=<DstTzInfo 'Europe/Stockholm' CEST+2:00:00 DST>), datetime.datetime(2022, 2, 7, 0, 0, tzinfo=<DstTzInfo 'Europe/Stockholm' CEST+2:00:00 DST>), datetime.datetime(2022, 2, 14, 0, 0, tzinfo=<DstTzInfo 'Europe/Stockholm' CEST+2:00:00 DST>), datetime.datetime(2022, 2, 21, 0, 0, tzinfo=<DstTzInfo 'Europe/Stockholm' CEST+2:00:00 DST>), datetime.datetime(2022, 2, 28, 0, 0, tzinfo=<DstTzInfo 'Europe/Stockholm' CEST+2:00:00 DST>) ] I want add zero … -
get multiple times or filter id__in on a queryset which is more efficient in django?
Which of the following is more efficient in django? items = [item for item in queryset.filter(id__in=ids)] items = [queryset.get(id=id) for id in ids] -
what is difference between these two
I have checkboxes in my view for filtering the data i have two different fileds implemented like this in my ListAPIView what's the difference between field 1 and field_2 field_1 = request.GET.get('field_1', 'true') == 'true' field_2 = request.GET.get('field_1', False) -
How to get .env to pre-commit + mypy + django-stubs
I try to configurate start mypy + django-stubs cheking before commiting. I use pre-commit for it. When I try to commit, I have error django.core.exceptions.ImproperlyConfigured: Set the POSTGRES_DB environment variable. This variable is in .env file, I export variables from .env to Django config using django-environ. And of course .env in .gitignore. So, as far as I understand: pre-commit starts with its own virtual environment, and it doesn't know about my .env file. Above all, do I correct to understand my situation? If I'm right, how to get variables from .env file to pre-commit enviroment? My .pre-commit-config.yaml (part) - repo: https://github.com/pre-commit/mirrors-mypy rev: '' hooks: - id: mypy exclude: "[a-zA-Z]*/(migrations)/(.)*" args: [--config=setup.cfg, --no-strict-optional, --ignore-missing-imports] additional_dependencies: [django-stubs, django-environ] my setup.cfg [mypy] python_version = 3.9 allow_redefinition = True check_untyped_defs = True ignore_missing_imports = True incremental = True strict_optional = True show_traceback = True warn_no_return = False warn_unused_ignores = True warn_redundant_casts = True warn_unused_configs = True plugins = mypy_django_plugin.main show_column_numbers = True [mypy.plugins.django-stubs] django_settings_module = config.settings.local [mypy_django_plugin] ignore_missing_model_attributes = True [mypy-*.migrations.*] # Django migrations should not produce any errors: ignore_errors = True -
(django_mysql.E016) MySQL 5.7+ is required to use JSONField
I am getting following error: (django_mysql.E016) MySQL 5.7+ is required to use JSONField HINT: At least one of your DB connections should be to MySQL 5.7+ My current MySQL version is 5.7.37 mysql Ver 14.14 Distrib 5.7.37, for Linux (x86_64) using EditLine wrapper my Django version is: 2.2.16 my Django-mysql version is: 3.2.0 Can someone let me know what is the issue? -
How do I redirect from a view to a root URL in Django?
I'm trying to add a link to my django site that redirects from the catalog1 view to the catalog2 page. So basically, I want to go from .../catalog1 to .../catalog2/other-page. All the other answers that I've seen require redirecting to http://127.0.0.1:8000/ first, and then redirecting to catalog2, but I've set up the site so that http://127.0.0.1:8000/ automatically redirects to catalog1, so this isn't working. Any help would be appreciated. Thanks, FluffyGhost -
Apache can't return secrets from AWS secrets manager
How do I set apache to run aws configure before running my application? ERROR LOG : [Tue Mar 01 04:30:32.202853 2022] [wsgi:error] [pid 54523:tid 139982691088128] [remote 68.234.152.211:50306] File "/home/ubuntu/env/lib/python3.8/site-packages/django/conf/init.py", line 71, in _setup [Tue Mar 01 04:30:32.202857 2022] [wsgi:error] [pid 54523:tid 139982691088128] [remote 68.234.152.211:50306] self._wrapped = Settings(settings_module) [Tue Mar 01 04:30:32.202867 2022] [wsgi:error] [pid 54523:tid 139982691088128] [remote 68.234.152.211:50306] File "/home/ubuntu/env/lib/python3.8/site-packages/django/conf/init.py", line 179, in init [Tue Mar 01 04:30:32.202872 2022] [wsgi:error] [pid 54523:tid 139982691088128] [remote 68.234.152.211:50306] mod = importlib.import_module(self.SETTINGS_MODULE) [Tue Mar 01 04:30:32.202882 2022] [wsgi:error] [pid 54523:tid 139982691088128] [remote 68.234.152.211:50306] File "/usr/lib/python3.8/importlib/init.py", line 127, in import_module [Tue Mar 01 04:30:32.202898 2022] [wsgi:error] [pid 54523:tid 139982691088128] [remote 68.234.152.211:50306] return _bootstrap._gcd_import(name[level:], package, level) [Tue Mar 01 04:30:32.202910 2022] [wsgi:error] [pid 54523:tid 139982691088128] [remote 68.234.152.211:50306] File "", line 1014, in _gcd_import [Tue Mar 01 04:30:32.202921 2022] [wsgi:error] [pid 54523:tid 139982691088128] [remote 68.234.152.211:50306] File "", line 991, in _find_and_load [Tue Mar 01 04:30:32.202931 2022] [wsgi:error] [pid 54523:tid 139982691088128] [remote 68.234.152.211:50306] File "", line 975, in _find_and_load_unlocked [Tue Mar 01 04:30:32.202942 2022] [wsgi:error] [pid 54523:tid 139982691088128] [remote 68.234.152.211:50306] File "", line 671, in _load_unlocked [Tue Mar 01 04:30:32.202952 2022] [wsgi:error] [pid 54523:tid 139982691088128] [remote 68.234.152.211:50306] File "", line 848, in exec_module [Tue Mar 01 04:30:32.202963 2022] … -
django dynamic forms setting max_length property
I am creating a 'Forms Management' system for my application. I am creating a forms dynamically using a custom form 'factory' method. Form data is in a json file. I can create a forms.CharField and set the label, required, initial and help_text properties. When I try to set the max_length property I do not get any error message, but the resulting HTML does not contain the max_length attribute. In static forms defined as class SearchAccountForm(forms.Form): provider_code = forms.CharField( label='Provider:', max_length=100, required=True, widget=forms.TextInput(attrs={'class': 'form-control'})) The resulting HTML contains the max_length attribute. <label for="id_provider_code">Provider:</label> </th><td><input type="text" name="provider_code" class="form-control" maxlength="100" required id="id_provider_code"> So what's up with max_length?? Json file { "form1": [ { "fld_name": "customer_name", "fld_type": "CharField", "fld_label": "Cust Name", "fld_required": "False", "fld_maxLength": 5, "initial": "Dr John" }, { "fld_name": "customer_number", "fld_type": "CharField", "fld_label": "Cust #", "fld_required": "True", "fld_maxLength": 15, "help_text": "Enter account number" }, { "fld_name": "customer_type", "fld_type": "CharField", "fld_label": "Customer Type", "fld_required": "False" } ] } and the forms.py factory method from django import forms import json def dynfrm(): f = open('blog/frmJson/frm1.json') data = json.load(f) fields = {} for i in data['form1']: ## form1 = form name in json file print(i) ## add to fields list if i['fld_type'] == 'CharField': fields[i["fld_name"]] … -
How to fix ERROR: Failed building wheel for psycopg2?
I am using ubuntu 20.04 and want to install django project dependencies using requirements.txt file. The project is using python3.9. and I've installed python3.9 and postgresql already. I already tried to install dependencies using pipfile, but it failed locking dependencies. installing dependencies give this error: Building wheels for collected packages: psycopg2 Building wheel for psycopg2 (setup.py) ... error ERROR: Command errored out with exit status 1: command: /usr/bin/python3 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-fu9m38m8/psycopg2/setup.py'"'"'; __file__='"'"'/tmp/pip-install-fu9m38m8/psycopg2/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /tmp/pip-wheel-rqzwqrsw cwd: /tmp/pip-install-fu9m38m8/psycopg2/ Complete output (38 lines): running bdist_wheel running build running build_py creating build creating build/lib.linux-x86_64-3.8 creating build/lib.linux-x86_64-3.8/psycopg2 copying lib/sql.py -> build/lib.linux-x86_64-3.8/psycopg2 copying lib/_json.py -> build/lib.linux-x86_64-3.8/psycopg2 copying lib/_range.py -> build/lib.linux-x86_64-3.8/psycopg2 copying lib/__init__.py -> build/lib.linux-x86_64-3.8/psycopg2 copying lib/pool.py -> build/lib.linux-x86_64-3.8/psycopg2 copying lib/errorcodes.py -> build/lib.linux-x86_64-3.8/psycopg2 copying lib/extras.py -> build/lib.linux-x86_64-3.8/psycopg2 copying lib/extensions.py -> build/lib.linux-x86_64-3.8/psycopg2 copying lib/errors.py -> build/lib.linux-x86_64-3.8/psycopg2 copying lib/tz.py -> build/lib.linux-x86_64-3.8/psycopg2 copying lib/_ipaddress.py -> build/lib.linux-x86_64-3.8/psycopg2 running build_ext building 'psycopg2._psycopg' extension creating build/temp.linux-x86_64-3.8 creating build/temp.linux-x86_64-3.8/psycopg x86_64-linux-gnu-gcc -pthread -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -g -fwrapv -O2 -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -DPSYCOPG_VERSION=2.9.1 (dt dec pq3 ext lo64) -DPSYCOPG_DEBUG=1 -DPG_VERSION_NUM=120009 -DHAVE_LO64=1 -DPSYCOPG_DEBUG=1 -I/usr/include/python3.8 -I. -I/usr/include/postgresql -I/usr/include/postgresql/12/server -I/usr/include/libxml2 -I/usr/include/mit-krb5 -c psycopg/psycopgmodule.c -o build/temp.linux-x86_64-3.8/psycopg/psycopgmodule.o … -
How to get class values in static method
I want to get the field value like we use self in Django models. class UserModel(Model): id = IDField() uid = TextField() @classmethod def get_user(cls): return cls.uid The class method, keep returning NONE instead of the string value of the uid field. Did I miss something? This is from the Firestore Python wrapper https://octabyte.io/FireO/quick-start/ -
No module named 'guardian.backends'?
i am deploying a django project, the uwsgi & nginx & mysql are already set, and the 127.0.0.1:8000 url went well, but occured an ModuleNotFoundError when i went into the 127.0.0.1:8000/admin url, it's like: ModuleNotFoundError: No module named 'guardian.backends' i don't understand this error. -
Finding the nearest observation station from National Weather Service API in Python/Django
So after finding the coordinates for the closest station, I need to extract the name of the station. This is an example of the response I'm working with: https://api.weather.gov/gridpoints/OKX/34,39/stations The station data is in the 'features' property. How do I go about extracting the name of the station based on the coordinates. -
Apscheduler stopped working randomly without any exception
I build a django webset and use apscheduler to do some scheduled tasks. Everything was alright at startup. But after some time, the scheduler refused to work and left nothing in log. The log just stopped without exception. Below is the framework of how I run the scheduler: from rpyc.utils.server import ThreadedServer class Command(BaseCommand): help = "Runs apscheduler." def handle(self, *args, **options): scheduler = BackgroundScheduler(timezone=settings.TIME_ZONE) scheduler.add_jobstore(DjangoJobStore(), "default") scheduler.start() server = ThreadedServer(SchedulerService(scheduler), port=settings.MY_RPC_PORT, protocol_config=protocol_config) try: # logging.info("Starting thread server...") server.start() except (KeyboardInterrupt, SystemExit): pass finally: scheduler.shutdown() And here are the dependencies: dependencies: - python=3.8.3=hcff3b4d_2 - apscheduler=3.6.3=py38_1 - django=3.2=pyhd3eb1b0_0 - pip: - django-apscheduler==0.6.0 - rpyc==5.0.1 What's more, while apscheduler was refusing to work, the rpyc server could still be connected and leave message in log. Can anyone help me to figure out what was wrong here? You have my gratitude. -
Django model with value as a special HTML character code
I am confused on how to implement a Django model with the value being a special html character code for making a chessboard. As a reference I'm looking at a sudoku board model: class Board(models.Model): name = models.CharField(max_length=4, primary_key=True) value = models.SmallIntegerField() The value for sudoku is easy, since the table will only be filled with numbers. For reference here's a snippet from the sudoku page_data dictionary in views.py giving each table cell its appropriate value: {"r1c1": 6, "r1c2": 7, "r1c3": 0, ...} I don't know what to put for my model's value variable: class Board(models.Model): name = models.CharField(max_length=2, primary_key=True) value = Here's a snippet of where I assign the name/value pairs in my views.py with the special HTML chess piece character codes in my own page_data dictionary: {"a8": html.unescape('&#9814;'), "b8": html.unescape('&#9816;'), "c8": html.unescape('&#9815;'), ...} Any help is appreciated. -
Streaming json data from POST request
I have a scenario that I need to upload an zip file. In the zip file, there are lots of image files which will upload to AWS S3. Because of the large amount of files in that zipfile, I want to get the information of upload process. In my opinion, the way I can get information is by using streaming response. Once server uploaded a file, respon a json to client. example for json streaming response: { "file_name": "imgae1.jpg", "s3_url": "http://s3.url/key/to/file", "other_key": "key for this uploaded file" } I'm trying to achieve this approach by using vue(cdn version) + axios(cdn version). The code bellow which is how I upload my zip file. function upload() { var file = document.querySelector("#upload_file") if (file.files.length <= 0) return var formData = new FormData(); formData.append("file", file.files[0]); formData.append("form_data", "form_data"); axios({ method: 'post', url: "http://127.0.0.1:8000/", headers: { 'Content-Type': 'multipart/form-data' }, responseType: 'stream', data: formData }).then(function (response) { if (response.status >= 200 && response.status < 300) { alert("Complete!") } }) } but those examples I found are using axios npm package which I can't use. Is there any recommend method or any resources that I can search? Thanks for helping! -
Intermittent server error when submitting forms using Django
I am getting the following 500 server error when I deploy my Django web application to google app engine: Error server error the server encountered an error and could not complete your request please try again in 30 seconds Simply refreshing the page solves this issue and renders the page. However, this isn't ideal and I want the page to load correctly the first time tried. This error does not occur on my localhost, it only occurs on the deployed site and typically during form submissions and rendering detail pages. I've researched the HTTP status codes in Django extensively from their documentation. It does not matter if the app is set in DEBUG mode or not. The same error appears. This is happening for both GET and POST requests. I have also tried to use a try-except block to retry the request multiple times before accepting failure. My configuration: Django: 3.2.9 Browser: Chrome 98.0.4758.80 I know this is not a lot of information to go off here, but any ideas or guidance would be much appreciated. -
Django Encrypt FileField with Fernet object has no attribute '_committed' occurred
I am passing multiple pdf uploads into the view from a form. (using Uppy.XHRUpload) I want to encrypt them before saving them in the model. When i test the files they can be encrypted and saved to a file and then read and decrptyped just fine. But when I try to add to the model I get: 'bytes' object has no attribute '_committed' occurred. I can download enctryped file, re-read and then save but that would be a waste. I thought it would be as simple as: if request.method == 'POST' and request.FILES: files = request.FILES.getlist('files[]') for index, file in enumerate(files): f = Fernet(settings.F_KEY) pdf = file.read() encrypted = f.encrypt(pdf) PDF_File.objects.create( acct = a, pdf = encrypted ) The Model. class PDF_File(models.Model): acct = models.ForeignKey(Acct, on_delete=models.CASCADE) pdf = models.FileField(upload_to='_temp/pdf/') Thanks for your help. -
Cannot access or find django many to many object after creating
I have had to merge two functions in my Django app due to an API upgrade. Formerly had one function create all of the objects, and the second function access said objects via .get() and .filter() etc. Now, I've had to merge the two, and I've run into issues accessing those created objects. order = Order.objects.create( user=user, date_created=datetime.datetime.now(), ) item = Item.objects.create( info=info, order=order, ) item.save() print(order.item_set.all()) #this is a blank array, where it used to be an array of items print(Items.objects.filter(order=order)) #this is a blank queryset, where I would expect it to be full of created items Any idea what I can do to make the print statement have items in it once again? I have tried to do order.item_set.add(item) but it did not work. -
Django ORM filter by lowercase only
How do I use Django ORM to filter objects that only show the lowercase only? For example in my case, I want to update all emails that has "non-lowercase" objects to "lowercase". from django.db.models.functions import Lower User.objects.exclude(email__islower=True).update(email=Lower("email")) /|\ | -
how to replace gunicorn with Nginx
I have an existing project that use G-unicorn because its deployed on lynx . but when I install on my windows local machine some of the API calls doesn't work due to Cors_allowedstrong text not allowed which I assume is caused because there is no G-unicorn any suggestion how to fix this on windows ? -
django channels , rejected request from client when added new header to the request
I need to add new header to the websocket request, but it get rejected and disconnect before even execute the connect method in the WebSocketConsumer class : class RecordConsumer(WebsocketConsumer): def connect(self): user = self.scope["user"] print(user.is_authenticated) header_name, header_value = self.scope["headers"][-1] print(header_name, header_value) print(header_name.decode("utf-8") == "issurvey" and header_value.decode("utf-8") == "true") if user.is_authenticated: self.room_group_name = "test" async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() elif header_name.decode() == "issurvey" and header_value.decode() == "true": self.room_group_name = "test" async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() else: self.close() I have custom middleware for authenticating using token to be able to connect from mobile device : from channels.auth import AuthMiddlewareStack from channels.db import database_sync_to_async from django.contrib.auth.models import AnonymousUser from rest_framework.authtoken.models import Token from urllib.parse import parse_qs @database_sync_to_async def get_user(token_key): try: token = Token.objects.get(key=token_key) return token.user except Token.DoesNotExist: return AnonymousUser() except KeyError: return AnonymousUser() class TokenAuthMiddleware: def __init__(self, inner): self.inner = inner def __call__(self, scope): return TokenAuthMiddlewareInstance(scope, self) class TokenAuthMiddlewareInstance: """ Yeah, this is black magic: https://github.com/django/channels/issues/1399 """ def __init__(self, scope, middleware): self.middleware = middleware self.scope = dict(scope) self.inner = self.middleware.inner async def __call__(self, receive, send): decoded_qs = parse_qs(self.scope["query_string"]) if b'token' in decoded_qs: token = decoded_qs.get(b'token').pop().decode() self.scope['user'] = await get_user(token) return await self.inner(self.scope, receive, send) def TokenAuthMiddlewareStack(inner): return TokenAuthMiddleware( AuthMiddlewareStack(inner)) I added this middleware … -
Python Deployment in google cloud platform
My django app using sendgrid for sending mail. Its work locally fine. After deploy it in cloud. It shows import error sendgrid -
Django Operational Error : No Such Column
I have a test case using Django MigratorTestCase. Previously the test case was working fine but then I had to add a column called updated and I made migrations to the project but ever since then the unit test case has been failing and I am not sure why. When ddebugging the code I have realized that the error is from the line assign_perm("delete_dataset", self.user1, self.d1) in Unit Test Case I apologize if I posted a bunch of unnecessary info. Thanks in advance guys. Unit Test Case: class DatasetPermissiontestCase(MigratorTestCase): migrate_from = [ ("guardian", "0002_generic_permissions_index"), ("project", "0037_dataset_public"), ] migrate_to = ("project", "0038_update_dataset_permission") def prepare(self): Dataset = self.old_state.apps.get_model("project", "Dataset") ctype = get_content_type(Dataset) ctype.save() Permission.objects.bulk_create( [ Permission(codename="change_dataset", content_type=ctype), Permission(codename="delete_dataset", content_type=ctype), Permission(codename="view_dataset", content_type=ctype), ] ) self.user1 = User.objects.create_user(username="a") self.d1 = Dataset.objects.create(name="d1") assign_perm("delete_dataset", self.user1, self.d1) def test_permission_updated(self): self.assertSetEqual( set(["delete_dataset"]), set(get_perms(self.user1, self.d1)), "permission should get updated after migration", ) Exception Stack Trace: E ====================================================================== ERROR: test_permission_updated (project.tests.DatasetPermissiontestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Users\admin\Anaconda3\envs\project\lib\site-packages\django\db\models\query.py", line 573, in get_or_create return self.get(**kwargs), False File "C:\Users\admin\Anaconda3\envs\project\lib\site-packages\django\db\models\query.py", line 431, in get self.model._meta.object_name guardian.models.models.UserObjectPermission.DoesNotExist: UserObjectPermission matching query does not exist. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\admin\Anaconda3\envs\project\lib\site-packages\django\db\backends\utils.py", line 84, in _execute …