Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django.db.utils.IntegrityError: Stuck with this error for days
I'm trying to make migrations in my model but stuck with this error: django.db.utils.IntegrityError: The row in table 'posts_article' with primary key '1' has an invalid foreign key: posts_article.author_id contains a value '1' that does not have a corresponding value in posts_author.id. Here's my models: from django.db import models from django.contrib.auth import get_user_model from django.utils.timezone import now User = get_user_model() # Create your models here. class Author(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, blank=True, null=True) profile_picture = models.ImageField() def __str__(self): return self.user.username class Topic(models.Model): title = models.CharField(max_length=20, blank=True, null=True) subtitle = models.CharField(max_length=20, blank=True, null=True) slug = models.SlugField(blank=True, null=True) thumbnail = models.ImageField(blank=True, null=True) def __str__(self): return self.title class Article(models.Model): title = models.CharField(max_length=100, blank=True, null=True) overview = models.TextField(null=True) content = models.TextField(null=True) author = models.ForeignKey(Author, on_delete=models.SET_NULL, blank=True, null=True) thumbnail = models.ImageField(blank=True, null=True) categories = models.ManyToManyField(Topic, blank=True, null=True) #featured = models.BooleanField(None, default=False) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return self.title class Meta: ordering = ['-updated', '-created'] I've searched the internet and tried a few solutions but it's the same. I am totally out of solutions. I am new to Django so please don't be too hard on me :) -
Aggregating Two Django Models with No Direct Relationship - Translating Pandas to Django ORM
I am currently aggregating two QuerySets by merging them based off of a key "pl_id" and grouping by two additional attributes, "zip_code" and "num_itms" with Pandas, but in production this is far too slow due to the large size of the datasets. I have tried multiple approaches with SubQueries but nothing is working, as the subqueries return multiple values. Zip codes is an ArrayField and is being unnested with the Postgres function, this seems to be complicating my goal. Is there a way to achieve this Pandas aggregation with Django ORM? result = ( pd.DataFrame.from_records( self.offer_query.annotate( partner_id=F("l__p_id"), zip_code=Func( F("l__ra__zip_codes_array"), function="unnest", ), ).values("zip_code", "p_id", "pl_id") ) .merge( pd.DataFrame.from_records( self.prices_query.values( "pl_id", "num_items", "price", ) ), on="pl_id", ) .groupby(["zip_code", "num_items"]) .agg( count=("p_id", "count"), min=("price", "min"), max=("price", "max"), ) .reset_index() ) I have already tried a subquery for each aggregation. -
OperationalError at / [Errno 111] Connection refused with Django and Celery
As the title suggest, I'm having OperationalError at / [Errno 111] Connection refused I'm using Django with Celery and Redis as Broker. The issue happens only when I'm using gunicorn with the command gunicorn --bind 0.0.0.0:8080 Lab.wsgi. Everything work with the Django internal server I've already tried this solution but it didn't work for me From the stack error it seems it's trying to use amqp when I'm using Redis with Celery. In Django on my settings.py I have REDIS_HOST = "172.20.1.2" REDIS_PORT = "6379" CELERY_BROKER_URL = "redis://" + REDIS_HOST + ":" + REDIS_PORT + "/0" CELERY_RESULT_BACKEND = 'redis://' + REDIS_HOST + ':' + REDIS_PORT + '/0' BROKER_TRASPORT_PROTOCOL = {"visibility_timeout":3600} CELERY_ACCEPT_CONTET = ["application/json"] CELERY_TASK_SERIALIZER = "json" So I can't udnerstand Error stack Internal Server Error: /celery-progress/01f2ab7b-5b25-4bda-901f-50cedb4d4a69/ Traceback (most recent call last): File "/home/lab/dashboardlab/.venv/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/home/lab/dashboardlab/.venv/lib/python3.10/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/lab/dashboardlab/.venv/lib/python3.10/site-packages/django/views/decorators/cache.py", line 62, in _wrapper_view_func response = view_func(request, *args, **kwargs) File "/home/lab/dashboardlab/.venv/lib/python3.10/site-packages/celery_progress/views.py", line 10, in get_progress return HttpResponse(json.dumps(progress.get_info()), content_type='application/json') File "/home/lab/dashboardlab/.venv/lib/python3.10/site-packages/celery_progress/backend.py", line 64, in get_info task_meta = self.result._get_task_meta() File "/home/lab/dashboardlab/.venv/lib/python3.10/site-packages/celery/result.py", line 438, in _get_task_meta return self._maybe_set_cache(self.backend.get_task_meta(self.id)) File "/home/lab/dashboardlab/.venv/lib/python3.10/site-packages/celery/backends/base.py", line 608, in get_task_meta meta = self._get_task_meta_for(task_id) AttributeError: 'DisabledBackend' object … -
I can't display the image in django admin UI
enter image description here my UI interface keep showing this url img source, meanwhile what i want is the image preview. maybe i need some additional format? what is the html tag needed to show as image in browser view? this is my source code now for **admin.py** from django.contrib import admin from .models import Categorie, Product from django.utils.html import format_html @admin.register(Categorie) class CategoryAdmin(admin.ModelAdmin): list_display = ('category_name',) @admin.register(Product) class ProductAdmin(admin.ModelAdmin): list_filter = ('category',) list_display = ('product_name', 'category','thumbnail_preview','description') def save_model(self, request, obj, form, change): obj.category_id = obj.category.id obj.save() def thumbnail_preview(self, obj): preview_html = '' for i in range(1, 6): product_photo_field = f'Photo_{i}' if hasattr(obj, product_photo_field): product_photo = getattr(obj, product_photo_field) if product_photo: preview_html += format_html('<img src="{}" style="max-height:100px; max-width:100px;" />', product_photo.url) print(preview_html) if not preview_html: return '(No Images)' return preview_html thumbnail_preview.allow_tags = True thumbnail_preview.short_description = 'Product Photos' and this is the models.py file from django.db import models **# Model for Category** class Categorie(models.Model): category_name = models.CharField(max_length=100, unique=True,default='') def __str__(self): return self.category_name **# Model for Product** class Product(models.Model): category = models.ForeignKey(Categorie, on_delete=models.CASCADE) product_name = models.CharField(max_length=200) Photo_1 = models.ImageField(upload_to='product_photos/') Photo_2 = models.ImageField(upload_to='product_photos/', blank=True, null=True) Photo_3 = models.ImageField(upload_to='product_photos/', blank=True, null=True) Photo_4 = models.ImageField(upload_to='product_photos/', blank=True, null=True) Photo_5 = models.ImageField(upload_to='product_photos/', blank=True, null=True) description = models.TextField() def __str__(self): return … -
When passing list into payload in Python requests module it is giving recursive error
I am trying to run tests like following: @patch("requests.post") # Mock the database connection def test_high_level_summary_success(self, mock_post): data = { "geo_level": "\"Global\"", "combinations": [{"product":"AAA","geo_value":"PL"}] } # Make a POST request to the endpoint url = reverse("myurl:deepdive-high-level-summary") response = self.client.post(url, data) self.assertEqual(response.status_code, status.HTTP_200_OK) However when I pass this list as combinations value ([{"product":"AAA","geo_value":"PL"}]) it is somehow giving me the following error: E RecursionError: maximum recursion depth exceeded while calling a Python object !!! Recursion detected (same locals & position) Why this might be the issue? Here is the function I want to test: @action(detail=False, methods=["post"]) def high_level_summary(self, request): try: # athenalogger.test_func1() json_payload = { "geo_level": ast.literal_eval(request.data.get("geo_level")), "combinations": ast.literal_eval(request.data.get("combinations")), } if request.data.get("months"): json_payload.update({"months": ast.literal_eval(request.data.get("months"))}) url = "{}{}".format(settings.MYURL, "api/deep_dive/high_level_summary") response = requests.post(url.replace("'", ""), json=json_payload) if response.status_code in [200, 201]: return Response({"result": response.json(), "status": "success"}, status=status.HTTP_200_OK) elif response.status_code in [400]: return Response({"result": {}, "status": "success"}, status=status.HTTP_200_OK) else: self.logger.error("error occured : {}".format(response.text)) return Response( {"error_message": "error response from sbd", "status": response.status_code}, status=status.HTTP_500_INTERNAL_SERVER_ERROR, ) except Exception as e: self.logger.error("\n Deepdive got an error: {}\n".format(traceback.format_exc())) return Response( {"error_message": "something went wrong", "status": "error"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR, ) -
Uploading audio file using react and DRF - UnicodeDecodeError: 'utf-8' codec can't decode byte 0xd6 in position 14
I have an application in which user either records an audio, or selects one from memory. Then, sends the file via this axios: const submit = () => { let params = new FormData(); params.append("exercise_id", exercise_id); params.append("answer", answer, "file.mp3"); setLoading(true); axios .post("submit_answer/", params, { headers: { "content-type": "multipart/form-data", }, }) .then((res) => { console.log(res.data); if (res.data.status === 1) { toaster(res.data.msg); } else { toaster(res.data.msg); } setLoading(false); }) .catch((err) => { setLoading(false); handleError(err); }); }; In the back-end I am using DRF, this is my serializer: class SubmitAnswerSerializer(serializers.Serializer): exercise_id = serializers.IntegerField() As you see, I am not using a serializer for the answer field, as it could be an audio, a video, an image, or even an integer number. Instead, I get it in my api: @api_view(["POST"]) def submit_answer(request): serializer = serializers.SubmitAnswerSerializer(data=request.data) if not serializer.is_valid(): return Response( {"status": 0, "msg": "submit_answer serializer invalid"}, status=status.HTTP_200_OK, ) exercise_id = serializer.validated_data.get("exercise_id") answer = request.data.get("answer") print(answer) ##########rest of the code but when i try to upload the media file using this api, I get this error: Internal Server Error: /api/submit_answer/ Traceback (most recent call last): File "~lib/python3.10/site-packages/django/core/handlers/exception.py", line 56, in inner response = get_response(request) File "~lib/python3.10/site-packages/django/core/handlers/base.py", line 220, in _get_response response = response.render() File "~lib/python3.10/site-packages/django/template/response.py", … -
Redacting files of Django project after deplo
I have deployed my Django project on my local server. Ubuntu 22.04.2 LTS Django 4.2.4 nginx 1.18.0 gunicorn 20.1.0 I use mysql-connector-python to connect with MySQL database. mysql-connector-python 8.0.33 I need to redact file with my DB queries and setting.py. I try to redact with nano and restart nginx but it doesn't work. How can I redact this files on prod? -
SystemCheckError when running makemigrations for Wagtail models
I'm trying to create migrations for my Wagtail models, but I encountered a SystemCheckError with some fields.E304 and fields.E305 errors. I'm using Django with Wagtail to build my web application, and the specific error message is as follows: SystemCheckError: System check identified some issues: ERRORS: app.HomePage.page_ptr: (fields.E304) Reverse accessor 'Page.homepage' for 'app.HomePage.page_ptr' clashes with reverse accessor for 'home.HomePage.page_ptr'. HINT: Add or change a related_name argument to the definition for 'app.HomePage.page_ptr' or 'home.HomePage.page_ptr'. app.HomePage.page_ptr: (fields.E305) Reverse query name for 'app.HomePage.page_ptr' clashes with reverse query name for 'home.HomePage.page_ptr'. HINT: Add or change a related_name argument to the definition for 'app.HomePage.page_ptr' or 'home.HomePage.page_ptr'. home.HomePage.page_ptr: (fields.E304) Reverse accessor 'Page.homepage' for 'home.HomePage.page_ptr' clashes with reverse accessor for 'app.HomePage.page_ptr'. HINT: Add or change a related_name argument to the definition for 'home.HomePage.page_ptr' or 'app.HomePage.page_ptr'. home.HomePage.page_ptr: (fields.E305) Reverse query name for 'home.HomePage.page_ptr' clashes with reverse query name for 'app.HomePage.page_ptr'. HINT: Add or change a related_name argument to the definition for 'home.HomePage.page_ptr' or 'app.HomePage.page_ptr'. I have a Django project with two Wagtail models: HomePage in the app app and HomePage in the home app. Both models inherit from the Wagtail Page model. I added some custom fields to each model, and the HomePage model has an additional field called … -
Build a backend in django from scratch without using ORM [closed]
I'm required to build a simple api but I'm not to use any ORM while using relational db. I have to do authentication as well. I am stuck even after some research and don't know how to aproach this. I have been doin django with ORM, and maybe DB first aproach is the go to here but still is there a way to create tables directly from django without getting models, involved? -
How to run a query with group by over a 'select_related' field in django ORM
I'm developing a reservations system and on my database I have Products, different Items of the products and orders related to specific items. The intention is to get the list of available items of an specific product that are not already reserved between two dates. These are my models: class Product(models.Model): # Aqui se almacenaran los modelos name = models.CharField(max_length=50, unique=True) category = models.ForeignKey(Category, on_delete=models.CASCADE) stock = models.IntegerField() def __str__(self): return self.name class Item(models.Model): # Aqui se almacenaran las matriculas especificas disponibles name = models.CharField(max_length=50, unique=True) product = models.ForeignKey(Product, on_delete=models.CASCADE) description = models.CharField(max_length=200, null=True, blank=True) def __str__(self): return f"{self.product.name} - {self.name}" class Order(models.Model): status = models.CharField(max_length=50) item = models.ForeignKey(Item, on_delete=models.CASCADE) date_created = models.DateTimeField(auto_now_add=True) start_date = models.DateTimeField() end_date = models.DateTimeField() notes = models.TextField(max_length=2000, null=True, blank=True) assigned_by = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return f"{self.item.name} - {self.start_date} - {self.end_date}" After some tests in SQL in the database, I've reached the following query that gives me the expected result: SELECT calendarapp_item.id, calendarapp_item.product_id as product, count(orders.id) AS active_orders FROM calendarapp_item LEFT JOIN (SELECT * FROM calendarapp_order WHERE start_date<='{}' AND end_date>='{}' AND status='completed') AS orders ON orders.item_id=calendarapp_item.id GROUP BY calendarapp_item.id HAVING active_orders=0 and product={} I would like to translate this query to Django ORM in order … -
Return field value when referencing model instance
If I have the following Model: class VATPercentage(models.Model): percentage = models.IntegerField(default=21) Is there anyway I can make it so that when you reference an instance of it, you actually get the value stored in the percentage field? For example, I want to be able to do: Service.vat_percentage instead of Service.vat_percentage.percentage Similar to how _ str _ would work if you called str() on the model, but I need an integer.. I tried to look for something similar like defining an _ int _ function but i dont think thats a thing.. -
Django, user confirmation with try and except
I am facing an error with a function that needs the confirmation that a user is there. Here is the code in views.py: Imports: from django.shortcuts import render, redirect, get_object_or_404 from django.contrib.auth.models import User The view: def (enclosed)View(request, creator_username): try: creator = get_object_or_404(User, username=creator_username) except User.DoesNotExist: messages.error(request, "Creator not found.") return redirect("homepage") # Redirect to some error page or homepage The error: Class 'User' has no 'DoesNotExist' member I have tried adding the "get_object_or_404" but it still doesn't work. I don't know any other way to get it to work. -
aws ssh server connect port 22: operation timed out
I am working on this tutorial (https://testdriven.io/blog/deploying-django-to-ecs-with-terraform/#nginx)and while I was following the steps, I tried to connect all of my instances via ssh by following these instructions (https://aws.amazon.com/blogs/compute/new-using-amazon-ec2-instance-connect-for-ssh-access-to-your-ec2-instances/). And by following the section where it starts by "connecting to an instance using EC2 Instance Connect", I typed in "$ aws ec2-instance-connect send-ssh-public-key --region us-east-1 --instance-id i-0989ec3292613a4f9 --availability-zone us-east-1f --instance-os-user ec2-user --ssh-public-key file://mynew_key.pub {" command on the terminal to push the public key to the instance using the send-ssh-public-key. After that, I tried to connect to the instance using the associated private key: $ ssh -I mynew_key ec2-user@ec2-34-204-200-76.compute-1.amazonaws.com". And it successfully worked out and I came to the end of the deploying Django tutorial. But when I was testing whether it properly connects to the server using the "http://(load balancer IP)" template, I kept getting a "503 service unavailable" error. So, I fixed the issue by changing the inbound rule sources to "0.0.0.0/0", but after that, it still gave me a "502 Bad Gateway" error. To find where the issue was happening, I checked whether the instances were connected properly and it gave me an error saying "ssh: connect to host xx port 22: Operation timed out". To resolve this, I … -
sqlite3 Database file is not visible in pycharm after migrate
enter image description herePycharm IDE is not generating database file I have followed all the commands correctly First I used -- > python manage.py makemigrations reels Yes it created a file like 0001_initial.py, After that I tried to migrate your text using ---> python manage.py migrate But the database file is not showing anything, I don't see anything there. Can someone please help me. -
How to create a mixin for `django_filters.FilterSet`?
I have a bunch of FilterSets to which I'd like to add the same new filters, but whenever I do something like below, I get an error saying that FilterSet.Meta must specify a model. E.G: class ModifiedAtMixin: modified_at_until = django_filters.DateTimeFilter(method="modified_until") def modified_until(self, queryset, name, value): return queryset.filter(modified_at__lte=value) class Meta: fields = ("modified_at_until",) class FooFilterSet(ModifiedAtMixin, django_filters.rest_framework.FilterSet): created_at_until = django_filters.DateTimeFilter(method="created_until") def created_until(self, queryset, name, value): return queryset.filter(created_at__lte=value) class Meta: model = Foo fields = ModifiedAtMixin.Meta.fields + ("created_at_until",) For reference, I also tried changing the order of parent classes in FooFilterSet and got nothing. How can I created a reusable mixin such as ModifiedAtMixin -
Editable frontend solution for a 2d array in a Django form
I am building a Django app, where a model "Foo" has a ManyToMany relation with "Bar" like this: Foo(Model): [field1] [field2] ... Bar(Model) [general_field1] [general_field2] ... FooBar(Model) ForeignKey(Foo) ForeignKey(Bar) [specific_field1] [specific_field2] ... The main model is Foo. I display each Foo in a template with it's fields and a 2D list of FooBars with general and specific fields (ordered list with several FooBars on each line). I need a solution to save this to the database (Problem 1) and more importantly to create a form or custom input fields for the user to populate it (Problem 2). The user should see (after the input fields for the Foo fields) some kind of blank list. There should be a search field with prerendered Bar models beneath it. As the user types in the search field the results beneath it are filtered. If the user selects a Bar a modal should open with fields to populate the "specific" fields for the actual FooBar (the general fields of the Bar are preset). After that the FooBar should appear in the list and the process continues. If the search result is blank (the user can't find the desired Foo) a "Create new Foo" option … -
Can not upload image
I try to upload an image in Django but I can't. I don't know what is the problem. The error: django.core.exceptions.SuspiciousFileOperation: Detected path traversal attempt in '/media/uploads/87176296b7b2425e81e266eaed65019b.png' Bad Request: /api/upload_file/ Bad Request: /api/upload_file/ [03/Aug/2023 17:47:52] "POST /api/upload_file/ HTTP/1.1" 400 17430 /api/upload_file: def upload_file(request): request_file = request.FILES['file'] if 'file' in request.FILES else None if request_file is None: data={ "error": "No file", } return Response(status=status.HTTP_400_BAD_REQUEST, data=data) if request_file.size > 20*1024*1024: data={ "error": "Image file too large (>20mb)", } return Response(status=status.HTTP_400_BAD_REQUEST, data=data) allowed_file_types = ['jpeg', 'jpg', 'png'] file_type = imghdr.what(request_file) if file_type not in allowed_file_types: data = { "error": "Invalid file type", } return Response(status=status.HTTP_400_BAD_REQUEST, data=data) upload = Upload(image=request_file) upload.save() data = { "upload_id": upload.id, } return Response(status=status.HTTP_200_OK, data=data) The Upload model: class Upload(models.Model): image = models.ImageField( verbose_name="Image", upload_to=path_and_rename_upload, ) patient = models.ForeignKey( "users.Patient", verbose_name="Patient", related_name="uploads", on_delete=models.SET_NULL, null=True, blank=True, ) upload_date = models.DateTimeField( verbose_name="Upload Date", auto_now_add=True, ) def __str__(self): return self.image.name @deconstructible class PathAndRename(object): def __init__(self, sub_path): self.path = sub_path def __call__(self, instance, filename) -> str: ext = filename.split(".")[-1] filename = f"{uuid4().hex}.{ext}".lower() return os.path.join(self.path, filename) path_and_rename_upload = PathAndRename("/media/uploads") I tried making the path BASE_DIR/self.path/filename but didn't make any differences. My settings.py: STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] if not DEBUG: … -
Trying to make a Roster class out of a Player class (in Django), Help! This is for a class assignment
Working on my models.py for my Team manager app and I can't figure out how to layout my class for a roster. I am new to Django so any help is greatly appreciated. The idea is to have the players on the team but then having a roster to show who is playing which game. Here's what I have so far: class Player(models.Model): player_id = models.AutoField(primary_key=True) first_name = models.CharField(max_length=45) last_name = models.CharField(max_length=45) cap_number = models.CharField(max_length=45, blank=True, default='') def __str__(self): result = '' if self.cap_number == '': result = '%s, %s' % (self.last_name, self.first_name) else: result = '%s, %s (%s)' % (self.last_name, self.first_name, self.cap_number) return result class Meta: ordering = ['last_name', 'first_name', 'cap_number'] constraints = [ UniqueConstraint(fields=['last_name', 'first_name', 'cap_number'], name='unique_player') ] class Roster(models.Model): roster_id = models.AutoField(primary_key=True) roster_name = models.CharField(max_length=45) player = models.ManyToManyField(Player) def __str__(self, data=None): return f'{self.roster_name} - {self.player}' class Meta: ordering = ['roster_name', 'player'] And this is the error I get when I try to run makemigrations: ERRORS: organizer.Roster: (models.E015) 'ordering' refers to the nonexistent field, related field, or lookup 'player'. Do I have to make another class to put the players into a list? -
Is python zipfile save to aws s3 bucket
Is anyone know that the location of zipfile created in python can be changed to aws s3 bucket? For now, my zipfile is created in my root folder. I know that I can add the directory path to the begin of the file name to change the create location, but how about s3 bucket? -
i am getting following error when i tried to create a django project ? i am using python 3.11 with pip 23.2.1 ? Any help is appreciated
i am trying to create a django project but i am not able to create it. $ django-admin startproject web Fatal error in launcher: Unable to create process using '"C:\Users\laupha\AppData\Local\Programs\Python\Python311\python.exe" "C:\Users\laupha\AppData\Local\Programs\Python\Python311\Scripts\django-admin.exe" startproject web': The system cannot find the file specified. -
AttributeError: 'Command' object has no attribute 'scriptable'
After updating Django 3->4.2.4 One of my UpdateView shows 'SomeModel' instance needs to have a primary key value before this relationship can be used. I think there could be some model need migrate ./manage.py makemigrations --dry-run File "/Users/user/Git/erp/venv/lib/python3.11/site-packages/django/core/management/commands/makemigrations.py", line 99, in log_output return self.stderr if self.scriptable else self.stdout ^^^^^^^^^^^^^^^ AttributeError: 'Command' object has no attribute 'scriptable' -
TypeError at / Field 'id' expected a number but got <SimpleLazyObject: <django.contrib.auth.models.AnonymousUser object at 0x0000025FE3733310>>
Im trying to make my openai chatbot save chats for the user that is making them, but it is giving me this error: Traceback (most recent call last): File "C:\Users\Nathan A\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\models\fields\__init__.py", line 2053, in get_prep_value return int(value) ^^^^^^^^^^ TypeError: int() argument must be a string, a bytes-like object or a real number, not 'SimpleLazyObject' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\Nathan A\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Nathan A\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Nathan A\Downloads\finalproject\finalproject\django_chatbot\chatbot\views.py", line 29, in chatbot chats = Chat.objects.filter(user=request.user) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Nathan A\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\models\manager.py", line 87, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Nathan A\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\models\query.py", line 1436, in filter return self._filter_or_exclude(False, args, kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Nathan A\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\models\query.py", line 1454, in _filter_or_exclude clone._filter_or_exclude_inplace(negate, args, kwargs) File "C:\Users\Nathan A\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\models\query.py", line 1461, in _filter_or_exclude_inplace self._query.add_q(Q(*args, **kwargs)) File "C:\Users\Nathan A\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\models\sql\query.py", line 1534, in add_q clause, _ = self._add_q(q_object, self.used_aliases) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Nathan A\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\models\sql\query.py", line 1565, in _add_q child_clause, needed_inner = self.build_filter( ^^^^^^^^^^^^^^^^^^ File "C:\Users\Nathan A\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\models\sql\query.py", line 1480, in build_filter condition = self.build_lookup(lookups, col, value) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Nathan A\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\models\sql\query.py", line 1307, in build_lookup lookup = lookup_class(lhs, rhs) ^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Nathan … -
How to solve error while running pip install mysql on MAC( Exception: Can not find valid pkg-config name)
Already tried re-installing everything. still got this message /bin/sh: pkg-config: command not found /bin/sh: pkg-config: command not found Trying pkg-config --exists mysqlclient Command 'pkg-config --exists mysqlclient' returned non-zero exit status 127. Trying pkg-config --exists mariadb Command 'pkg-config --exists mariadb' returned non-zero exit status 127. Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/pip/_vendor/pyproject_hooks/_in_process/_in_process.py", line 353, in main() File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/pip/_vendor/pyproject_hooks/_in_process/_in_process.py", line 335, in main json_out['return_val'] = hook(**hook_input['kwargs']) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/pip/_vendor/pyproject_hooks/_in_process/_in_process.py", line 118, in get_requires_for_build_wheel return hook(config_settings) ^^^^^^^^^^^^^^^^^^^^^ File "/private/var/folders/sl/r5ldvvwx13qbfft41c70zmy80000gn/T/pip-build-env-sflnewt3/overlay/lib/python3.11/site-packages/setuptools/build_meta.py", line 341, in get_requires_for_build_wheel return self._get_build_requires(config_settings, requirements=['wheel']) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/private/var/folders/sl/r5ldvvwx13qbfft41c70zmy80000gn/T/pip-build-env-sflnewt3/overlay/lib/python3.11/site-packages/setuptools/build_meta.py", line 323, in _get_build_requires self.run_setup() File "/private/var/folders/sl/r5ldvvwx13qbfft41c70zmy80000gn/T/pip-build-env-sflnewt3/overlay/lib/python3.11/site-packages/setuptools/build_meta.py", line 338, in run_setup exec(code, locals()) File "", line 154, in File "", line 48, in get_config_posix File "", line 27, in find_package_name Exception: Can not find valid pkg-config name. Specify MYSQLCLIENT_CFLAGS and MYSQLCLIENT_LDFLAGS env vars manually [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: subprocess-exited-with-error × Getting requirements to build wheel did not run successfully. │ exit code: 1 ╰─> See above for output. note: This error originates from a subprocess, and is likely not a problem with pip. -
Django constraint for "field one not in field two for any row"?
Suppose I have a Django model with two fields one and two: class MyModel(models.Model): one = models.CharField(max_length=100, unique=True) two = models.CharField(max_length=100) unique=True means if I try to put in a row with one="one" when another such row already exists, a unique constraint will be violated. How would I make a Django constraint that says if there is a row with one="one", then I can't put in a row with two="one"? This does seem related to this question and this answer, but I don't quite see the answer to my question. -
How to override the templates of `django-two-factor-auth` for Django Admin?
I'm trying to override the templates of django-two-factor-auth for Django Admin but I don't know how to do it. *I don't have frontend with Django. Instead, I have frontend with Next.js and backend with Django. This is my django project: django-project |-core | |-settings.py | └-urls.py |-my_app1 | |-models.py | |-admin.py | └-urls.py └-templates And, how I set django-two-factor-auth following the doc is first, I installed django-two-factor-auth[phonenumbers]: pip install django-two-factor-auth[phonenumbers] Then, set these apps below to INSTALLED_APPS, OTPMiddleware to MIDDLEWARE, LOGIN_URL and LOGIN_REDIRECT_URL in core/settings.py as shown below: # "core/settings.py" INSTALLED_APPS = [ ... 'django_otp', # Here 'django_otp.plugins.otp_static', # Here 'django_otp.plugins.otp_totp', # Here 'two_factor' # Here ] ... MIDDLEWARE = [ ... 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django_otp.middleware.OTPMiddleware', # Here ... ] LOGIN_URL = 'two_factor:login' # Here # this one is optional LOGIN_REDIRECT_URL = 'two_factor:profile' # Here ... TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ BASE_DIR / 'templates', ], ... }, ] Then, set the path below to core/urls.py: # "core/urls.py" ... from two_factor.urls import urlpatterns as tf_urls urlpatterns = [ ... path('', include(tf_urls)) # Here ] Finally, migrate: python manage.py migrate And, this is Login page: http://localhost:8000/account/login/ My questions: How can I override the templates of django-two-factor-auth for Django Admin? Are there …