Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
SIMILARITY function triggered by Django
I'm implementing TrigramSimilarity full text search on my Django app. I installed the pg_trgm extension by migrating using Django. I can see the migration in my postgres table and I can use the SIMILARITY function when I run queries directly on the database. I get this error when I try to run a search on my app. I'm at a loss for what to do because when I get the error with this: but when I run a query directly on the database I get results: Initially I was using SearchQuery string in place of 'test' but changed it because I saw another answer suggesting that may be a problem. -
Django annotate by looking up a related field value
I am working on a package sorting system in Django. I need to look up the "sort code" of a set of "barcodes" This code works: class Order(models.Model): Zip = CharField(max_length=128, null=True, blank=True) class Barcode(models.Model): barcode = CharField(max_length=50, unique=True) Order = ForeignKey(Order, on_delete=models.SET_NULL) class SortCode(models.Model): name = CharField(max_length=50, unique=True) class SortZip(models.Model): zipcode = CharField(max_length=5, unique=True) sortcode = ForeignKey('SortCode', null=True, default=None, blank=True, on_delete=models.PROTECT) sortzip = SortZip.objects.filter(zipcode=OuterRef('Order__Zip')) barcodes = Barcode.objects.annotate(sortcode_value=Subquery(sortzip.values('sortcode__name'))) However, SortZip.zipcode only stores 5-digit zip codes, and Order.Zip sometimes contains zip+4, so I need to look up the SortZip from only the first 5 digits of Order.Zip: sortzip = SortZip.objects.filter(zipcode=OuterRef('Order__Zip')[:5]) barcodes = Barcode.objects.annotate(sortcode_value=Subquery(sortzip.values('sortcode__name'))) This causes the following error: TypeError: 'OuterRef' object is not subscriptable I have tried adding the following property to the Order model and using the property: class Order(models.Model): Zip = CharField(max_length=128, null=True, blank=True) @property def Zip5(self): return self.Zip[:5] ... sortzip = SortZip.objects.filter(zipcode=OuterRef('Order__Zip5')) barcodes = Barcode.objects.annotate(sortcode_value=Subquery(sortzip.values('sortcode__name'))) However, this gives a different error: django.core.exceptions.FieldError: Unsupported lookup 'Zip5' for BigAutoField or join on the field not permitted. -
try to authenticate login, submit nothing happened
login.html in (authenticate/login.html) {% extends "events/base.html" %} {% block content %} <h1>Login</h1> <br><br> <form action="" method="POST"> {% csrf_token %} <form> <div class="mb-3"> <label for="exampleInputUserName" class="form-label">User name</label> <input type="text" class="form-control" name="username"> </div> <div class="mb-3"> <label for="exampleInputPassword1" class="form-label">Password</label> <input type="password" class="form-control" name="password"> </div> </form> <input type="submit" value="Submit" class="btn btn-secondary"> </form> <br><br> {% endblock content %} when click the submit button nothing happened urls.py in (events) from django.urls import path from . import views urlpatterns = [ path('', views.home, name='home'), ] urls.py in (members) from django.urls import path from . import views urlpatterns = [ path('login_user/', views.login_user, name='login'), ] urls.py in (myclub_webesite) rom django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('events.urls')), path('members/', include('django.contrib.auth.urls')), path('members/', include('members.urls')), ] views.py in (members) from django.shortcuts import render, redirect from django.contrib.auth import authenticate, login, logout from django.contrib import messages def login_user(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('home') else: messages.success( request, ("There Was An Error Logging In, Try Again...")) return redirect('login') else: return render(request, 'authenticate/login.html', {}) setting are put in members i have try use other code username = request.POST['username'] password = request.POST['password'] and … -
Unable to log in to Django admin panel after Railway deployment
I'm new to Django, and even newer to using Railway so please be kind. I've got a portfolio project that uses Django on the back end, and I was previously hosting on Heroku. I've attempted to move the deployment to Railway, and I've encountered a problem I can't figure out. Locally, I'm able to sign into the Django admin panel with the superuser credentials. When I attempt the same on the Railway deployment, I get a really long error that doesn't point to anything in my code. I've tried to research the error for a few days now, and I'm coming up blank. I honestly don't even have a direction to look for a solution. This is the error I see when I attempt to sign into the admin panel: (Happy to add other files, but I don't know what is relevant?) OperationalError at /admin/login/ connection to server at "localhost" (127.0.0.1), port 5432 failed: Connection refused Is the server running on that host and accepting TCP/IP connections? connection to server at "localhost" (::1), port 5432 failed: Cannot assign requested address Is the server running on that host and accepting TCP/IP connections? Request Method: POST Request URL: http://web-production-603f.up.railway.app/admin/login/?next=/admin/ Django Version: 4.0.6 … -
How to filter JSON Array in Django JSONField
How could I filter the whole row data which inventory id=2 This is the result data I want: sampleData = [ {'rate': 1, 'inventory': {'id': 1, 'name': 'inv1'}, 'inputQuantity': 4}, {'rate': 1, 'inventory': {'id': 2, 'name': 'inv2'}, 'inputQuantity': 10, 'parentInventory': 2} ] This is the sample database: inventoryList=[ [ {'rate': 1, 'inventory': {'id': 1, 'name': 'inv1'}, 'inputQuantity': 4}, {'rate': 1, 'inventory': {'id': 2, 'name': 'inv2'}, 'inputQuantity': 10, 'parentInventory': 2} ], [ {'rate': 4, 'inventory': {'id': 5, 'name': 'inv2'}, 'inputQuantity': 4}, {'rate': 3, 'inventory': {'id': 4, 'name': 'inv4'}, 'inputQuantity': 1} ], [ {'rate': 2, 'inventory': {'id': 5, 'name': 'inv1'}, 'inputQuantity': 5}, {'rate': 4, 'inventory': {'id': 6, 'name': 'inv2'}, 'inputQuantity': 10, 'parentInventory': 2} ], ] The filter be like: sampleLog.objects.filter(inventoryList__contains=[{"inventory":{'id': 2}}]) -
CSRF verification failed. Request aborted
Been working on my live server all day and just got it working, admin was working fine, i cleared cookies and suddenly i got the following error, and no fixes seem to be helping me. My website does have SSL yet so its still http(dont know if this has anything to do with it?) DEBUG = False CSRF_TRUSTED_ORIGINS = ['http://.*', 'http://example.com', 'http://www.example.com'] # HTTPS Settings SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = False SECURE_SSL_REDIRECT = False # HSTS Settings SECURE_HSTS_SECONDS = 31536000 SECURE_HSTS_PRELOAD = True SECURE_HSTS_INCLUDE_SUBDOMAINS = True This is the only form on my website that requires csrf_token and as you can see it already has it. -
Python gRPC request missing occasionally
I'm using gRPC in python with django and django-grpc-framework. And when I run the unittest, there is a piece of code in my models.py which producing weird problem: I request three gRPC requests, but only one reaches the server side. To simplified the problem, the following code explains the situation: class MyModel(models.Model): def some_method(self): for stub in [stub1, stub2, stub3]: resp = stub.RetractObject(base_pb2.RetractObjectRequest( app_label='...', object_type='...', object_id='...', exchange_id='...', remark='...', date_record='...', )) Here, the some_method is triggering under a django.test.TestCase unittest function, while the gRPC was connecting to a external running server instance. And the relating .proto files is as below: // base.proto // ... message CreditRecord { int64 id = 1; string username = 2; string app_label = 3; string flag = 4; string object_type = 5; int64 object_id = 6; int64 amount = 7; int64 balance = 8; string remark = 9; string date_record = 10; string exchange_id = 11; int64 retract_ref = 12; } message RetractObjectRequest { string app_label = 1; string object_type = 2; int64 object_id = 3; string exchange_id = 4; string remark = 5; string date_record = 6; } // ... // stub1 - stub3 has the similar structure below syntax = "proto3"; package mjtest.growth; import … -
How to return only 1 (single) record via Django Rest Framework API? (problem with many=False)
I have a simple Django Rest Framework API that I would like to return only 1 record. However, when I set many=False, it no longer works. How can I fix this? Here's the API: (serializer & model below) class Expense_View_API(APIView): permission_classes = [IsAuthenticated, ] def get(self, request): param_xid = request.GET.get('id','') if param_xid != "": expenses_recordset = Expenses.objects.filter(xid=param_xid) serializer = Expenses_Serializer(expenses_recordset, many=True) return Response(serializer.data, status=status.HTTP_200_OK) else: return Response("BAD REQUEST: Missing 'id' Parameter", status=status.HTTP_400_BAD_REQUEST) It returns: (good except that I don't want the square list brackets) [ { "xid": 111, "xdate": "2021-02-15T00:00:00Z", "xseller": "Amazon", "xamount": "30.00", } ] Problem: When I set serializer = Expenses_Serializer(expenses_recordset, many=False), it now returns this null data and drops my xid field. Why? { "xdate": null, "xseller": null, "xamount": null, } I want it to return: { "xid": 111 "xdate": "2021-02-15T00:00:00Z", "xseller": "Amazon", "xamount": "30.00", } Here's my serializer and data model: class Expenses_Serializer(serializers.ModelSerializer): class Meta: model = Expenses fields = ('xid', 'xdate', 'xseller', 'xamount') class Expenses(models.Model): xid = models.AutoField(db_column='xID', primary_key=True) # Field name made lowercase. xdate = models.DateTimeField(db_column='xDate', blank=True, null=True) # Field name made lowercase. xseller = models.CharField(db_column='xSeller', max_length=50, blank=True, null=True) # Field name made lowercase. xamount = models.DecimalField(db_column='xAmount', max_digits=19, decimal_places=2, blank=True, null=True) # Field name … -
How to implement a derived select in Django? The purpose is to narrow down before more expensive operations
We are working on a reporting table of a transaction dataset assembled with dynamic EAV attributes by the left outer join operators. The sample SQL query below contains a snippet of limit 20 OFFSET 27000 simulating a pagination scenario of displaying a page of 20 records in the middle of the overall data set sized nearly 30 thousand rows. With Django ORM, we started the QuerySet from the Model object and filtered its active_objects before appending the left outer join operators, with the below snippet: transaction = Transaction.active_objects.filter( product_id=product_id ).order_by('-id').all()[27000:27020] As a default system behaviour of Django, I guess, the ORM put the WHERE clause at the rear of the the SQL query. As a result, the MariaDB v10.5 database performs all the left outer join operators on the overall data set before it applies the filtering condition. The running time is nearly 20 seconds in our test setting. We made a hand-written improvement to the SQL query and reduced the running time to under one second. The change is moving the WHERE clause up to immediately following the FROM transaction clause, and moreover, wrapping it inside the brackets ( ) to make the database engine treat it as a … -
Assign a type to JSONField in Django
I'm using a property of type JSONField in my model: from django.db import models class MyClass(models.Model): variables = models.JSONField() I want to avoid as much as possible using strings to access variables properties, is there any way to specify the type of variables, so that I can use obj.variables.prop_name rather than obj.variables['prop_name']? -
Django and pgAdmin not aligned
I was trying to change the order of the table columns in a postgreSQL table. As I am just starting, it seemed easier to manage.py flush and create a new DB with new name and apply migrations. I can see the new DB in pgAdmin received all the Django models migrations except my app model/table. I deleted all migrations folder (except 0001_initial.py) and still, when I run python manage.py makemigrations I get: No changes detected But the model class table is not in the DB. When I try to migrate the app model it says: Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions Running migrations: No migrations to apply. Is there any way to delete all tables, makemigrations and migrate and postgres get all the tables? Any idea why postgreSQL/pgAdmin cannot get my Django app model/table? -
Django pdf template count severity per row
I am using Django but I am stuck with the PDF report. There are three severity which are "Damage to Property", "Fatal" and "Non-Fatal". Download of PDF is working but but in my PDF report, I would want for every distinct address, it will count each severity (the number of Damage to Property, Fatal or Non-fatal). How can I achieve this? This is what the table will look like: Date | Time | Address | Damage to Property | Fatal | Non-Fatal Model class IncidentGeneral(SoftDeleteModel): PENDING = 1 APPROVED = 2 REJECTED = 3 STATUS = ( (PENDING, 'Pending'), (APPROVED, 'Approved'), (REJECTED, 'Rejected') ) IF_DUPLICATE = ( ('Duplicate', 'Duplicate'), ('Possible Duplicate', 'Possible Duplicate'), ('Not Duplicate', 'Not Duplicate') ) WEATHER = ( ('Clear Night', 'Clear Night'), ('Cloudy', 'Cloudy'), ('Day', 'Day'), ('Fog', 'Fog'), ('Hail', 'Hail'), ('Partially cloudy day', 'Partially cloudy day'), ('Partially cloudy night', 'Partially cloudy night'), ('Rain', 'Rain'), ('Rain', 'Rain'), ('Wind', 'Wind'), ) LIGHT = ( ('Dawn', 'Dawn'), ('Day', 'Day'), ('Dusk', 'Dusk'), ('Night', 'Night'), ) SEVERITY = ( ('Damage to Property', 'Damage to Property'), ('Fatal', 'Fatal'), ('Non-Fatal', 'Non-Fatal'), ) user = models.ForeignKey(User, on_delete=models.CASCADE, editable=False, null=True, blank=True) generalid = models.CharField(max_length=250, unique=True, null=True, blank=True) upload_id = models.ForeignKey(UploadFile, on_delete=models.CASCADE, editable=False, null=True, blank=True) description = … -
How can I can not raise error in mutations with graphene-django-cud?
I'm using graphene-django-cud for mutations. But I can't raise any GraphQLError, ValueError or Exception in mutations. Like in before_mutate() or any validate_ method. The process just stop with out any error message. Then return null for the instance and message. @classmethod def before_mutate(cls, root, info, input, id): print("before_mutate") from graphql import GraphQLError raise GraphQLError(f"The observation with id {id} doesn't exists") @classmethod def validate_name(cls, root, info, value, input, id, obj): print("validate_name") raise ValueError(f"The observation with id {id} doesn't existssss") Anyone met this before? Thanks in advance! -
"Remember Me" option when logging in with Django + DRF + Djoser + Nuxt
I've got a site that uses Django as a backend and Nuxt for frontend. I'd like to implement the commonly-seen "Remember Me" checkbox when a user logs in. If unchecked, the user should only be logged in for that session and has to log in again the next time they open their browser. If checked, they should stay logged in indefinitely unless they manually log out. The backend is using Django, with Django Rest Framework and Djoser for authentication. Currently using DRF's TokenAuthentication, and not JWT stuff. The frontend is using Nuxt, which is using the Nuxt Auth module with the local strategy for logging in. This is saving the token in localStorage, which never expires. How would I go about adding this "Remember Me" functionality? I'm not even sure which part to modify - either the backend or the frontend. -
Frontend + NGINX can't make a request to backend endpoints (2 different docker containers)
I am having issues making requests to a backend Django container from a frontend app that is reverse proxied by NGINX. I have a backend Django server which serves database information, carries out authenticated etc. It is containerised thru a docker container. This is locally served on http://127.0.0.1:8000/. I then have NGINX project.conf as follows: server { listen 80; server_name docker_flask_gunicorn_nginx; location / { proxy_pass http://my_app:8080; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } location /static { rewrite ^/static(.*) /$1 break; root /static; }} There are a few different endpoints in the backend app, but it fails at the first hurdle which is trying to authenticate at /api/token/. When the frontend app makes a request to http://127.0.0.1:8000/api/token/ the following error is returned: HTTPConnectionPool(host='127.0.0.1', port=8000): Max retries exceeded with url: /api/token/ (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7fc3208f6910>: Failed to establish a new connection: [Errno 111] Connection refused')) For completeness the docker-compose for the frontend / NGINX setup is: version: '3' services: my_app: container_name: my_app-frontend restart: always build: ./my_app ports: - "8080:8080" command: gunicorn -w 2 -b :8080 app:server env_file: - ./my_app/.env nginx: container_name: nginx restart: always build: ./nginx ports: - "80:80" depends_on: - my_app From what I can see … -
Django: on visiting page I get an alert with dictionary values in it. What is causing this?
New to Django and python, been following a tutorial and playing around with creating a user to user messaging functionality. So far all works great except that when I visit the messages page I always get an alert like: {'user': <User: test2>, 'last': datetime.datetime(2022, 12, 15, 20, 21, 19, 109214, tzinfo=datetime.timezone.utc), 'unread': 0} alert Any ideas on what is causing this and how can I remove it? urls.py from django.urls import path from . import views as user_views app_name = 'chat' urlpatterns = [ path('messages/', user_views.inbox , name='messages'), path('messages/<username>', user_views.Directs , name='directs'), path('messages/send/', user_views.SendDirect , name='send_direct'), ] views.py from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from .models import Message from django.http import HttpResponse, HttpResponseBadRequest from django.template import loader from django.contrib.auth.models import User @login_required def inbox(request): messages = Message.get_messages(user=request.user) active_direct = None directs = None if messages: message = messages[0] active_direct = message['user'].username directs = Message.objects.filter(user=request.user, recipient=message['user']) directs.update(is_read=True) for message in messages: if message['user'].username == active_direct: message['unread'] = 0 context = { 'directs': directs, 'messages': messages, 'active_direct': active_direct, } template = loader.get_template('chat.html') return HttpResponse(template.render(context, request)) @login_required def Directs(request, username): user = request.user messages = Message.get_messages(user=user) active_direct = username directs = Message.objects.filter(user=user, recipient__username=username) directs.update(is_read=True) for message in messages: if message['user'].username … -
Nginx calling directories that don't exist
I'm trying to fix my static files not been served. I finally found out how to access the error log and it turns out that Nginx is searching a category that does not exist. It is requesting: /home/dave/mhprints/static/styles/html-body-styles.css /static/styles/html-body-styles.css My actual path /home/dave/mhprints/static/css/html-body-styles.css /static/css/html-body-styles.css My HTML templates Any ideas why nginx is doing this? I've been trying to fix this problem for my static and images for over 48 hours now. Thank you in advance. -
How to remove a useless "UPDATE" query when overriding "response_change()" in Django Admin?
In PersonAdmin():, I overrode response_change() with the code to capitalize the name which a user inputs on Change person as shown below: # "store/person" from django.contrib import admin from .models import Person @admin.register(Person) class PersonAdmin(admin.ModelAdmin): def response_change(self, request, obj): # Here obj.name = obj.name.capitalize() obj.save() return super().response_change(request, obj) Then, I input david to Name: on Change person as shown below: Then, the name was successfully changed from John to David capitalized as shown below: But according to PostgreSQL logs, there is a useless UPDATE query as shown below. *I use PostgreSQL and you can check On PostgreSQL, how to log queries with transaction queries such as "BEGIN" and "COMMIT": So, how can I remove the useless UPDATE query as shown above? -
import files to django project
sorry for the nooby question . but i got an MNIST project as a college homework and i'm trying to deploy it in a django website so far i made the HTML canvas , the jpg to base64 converter so i transfer the image in a django form, the script to read the base64 string and guess the number and tested them on another project , but my only problem is that i can't make the model folder/file (.model) visible to django . it's my first time working on django and i just want the model to be read by the script i made all the script in view.py folder cuz it ain't much + don't know how to add modules to django view.py : from django.shortcuts import render from django import forms import base64 import io import re from PIL import Image import cv2 import numpy as np import tensorflow as tf ## this isn't visible model = tf.keras.models.load_model(STATIC_URL+'handwriting.model') class Form(forms.Form): cv = forms.CharField(label='') def testable(msg): base64_data = re.sub('^data:image/.+;base64,', '', msg) byte_data = base64.b64decode(base64_data) image_data = io.BytesIO(byte_data) img = Image.open(image_data) img = img.resize((28, 28), resample=Image.Resampling.BILINEAR) a = cv2.cvtColor(np.array(img), cv2.COLOR_BGR2GRAY) a = np.array([a]) recon = model.predict(a) print(f'this is a {np.argmax(recon)} … -
Django queryset hide value of object
I have the following (simplified) Model: class Order(models.Model): is_anonymized = models.BooleanField(default=False) billing_address = models.ForeignKey('order.BillingAddress', null=True, blank=True) I want to hide the billing_address for objects where the customer chosen to do so by setting is_anonymized=True. My best approach so far was to do that in the init: def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if self.is_anonymized: self.billing_address = None self.billing_address_id = None This works fine in the Admin BUT... anywhere in the code there are select_related-QuerySets for Orders: queryset = Order._default_manager.select_related('billing_address') All places where the select_related-querysets are used, the billing_address is accidentally shown. Elsewhere (like in the admin), it isn't. How can I ensure to remove the billing_address everywhere for objects with is_anonymized = True? I thought about overwriting the queryset in the manager but i couldn't overwrite the billing_address field by condition. Using the getter-setter pattern was not a good solution because it breaks the admin at multiple places (there are many attributes to cloak like billing_address). -
Why can't I log in after upgrading Django from 2.2 to 3.2?
I just upgraded my Django 2.2 project to 3.2, and now I cannot login with any user in the database. I am so confused because I'm not getting any error messages, but continually being redirected to the login page after successfully authenticating and logging in. Here are the steps that I am taking: Enter username/password into the login form (works great in 2.2) The python file uses user = authenticate(username=username, password=password) and then login(request, user) I can confirm that the username/password are correct, and printing request.user immediately after the login call logs the correct user. When I inspect the cookies in the browser, a value for sessionid is set. After successful login, the server sends a redirect to an auth-protected route. However, when getting the protected route, printing the request.user is AnonymousUser, and then I am redirected back to the login page. This appears to be an issue with the sessions. I can see that the cookies are being set, and even when I manually set the sessionid cookie to be the value returned by request.session.session_key right after the call to login it still does not recognize the authorized user. I have followed the recommendations in the release notes to … -
getting pk of item in test unit
there is a test unit that gets request and pk of an item in Form and the problem that i cant figure how to create a new item in the data base and get the pk from it in the test unit function. class test_editTransfer_admin(TestCase): def test_editTransfer_page_open(self): url = reverse(views.editTransfer) response = self.client.get(url) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'admin_u/editTransfer.html') def test_editTransfer_view_deployed_to_page(self): factory = RequestFactory() request = factory.get('admin_u/editTransfer') response = views.editTransfer(request, #pk here ) self.assertEqual(response.status_code, 200) i tried to defined a setUp function that creates the product but without success.. -
Add search control to django-leaflet admin map. GEODJANGO
I'm totally new to this, I want to add a search bar like the one on the OpenStreetMap website, to search for coordinates, streets, or any location on the django-leaflet admin map, but I have no idea how to do it. It is somewhat difficult to find locations on this map, my idea is to look for the coordinates in google maps to be able to add a marker at the desired location. OpenStreetMap: enter image description here My Django Admin enter image description here I tried to follow some tutorials, but I don't understand. how to add leaflet-geosearch control in django admin -
(1062, "Duplicate entry '1' for key 'usuario_id'") en django
i a The problem here is that after all this happens I wanted to try creating a new superuser and it gives me the error in the title, if someone could help me I would appreciate it update this is the traceback File "c:\proyectos\first-proyect\gastos\users\views.py", line 24, in sing_up form.save() File "c:\proyectos\first-proyect\venv\lib\site-packages\django\contrib\auth\forms.py", line 143, in save user.save() File "c:\proyectos\first-proyect\venv\lib\site-packages\django\contrib\auth\base_user.py", line 68, in save super().save(*args, **kwargs) File "c:\proyectos\first-proyect\venv\lib\site-packages\django\db\models\base.py", line 812, in save self.save_base( File "c:\proyectos\first-proyect\venv\lib\site-packages\django\db\models\base.py", line 863, in save_base updated = self._save_table( File "c:\proyectos\first-proyect\venv\lib\site-packages\django\db\models\base.py", line 1006, in _save_table results = self._do_insert( File "c:\proyectos\first-proyect\venv\lib\site-packages\django\db\models\base.py", line 1047, in _do_insert return manager._insert( File "c:\proyectos\first-proyect\venv\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "c:\proyectos\first-proyect\venv\lib\site-packages\django\db\models\query.py", line 1790, in _insert return query.get_compiler(using=using).execute_sql(returning_fields) File "c:\proyectos\first-proyect\venv\lib\site-packages\django\db\models\sql\compiler.py", line 1660, in execute_sql cursor.execute(sql, params) File "c:\proyectos\first-proyect\venv\lib\site-packages\django\db\backends\utils.py", line 103, in execute return super().execute(sql, params) File "c:\proyectos\first-proyect\venv\lib\site-packages\django\db\backends\utils.py", line 67, in execute return self._execute_with_wrappers( File "c:\proyectos\first-proyect\venv\lib\site-packages\django\db\backends\utils.py", line 80, in _execute_with_wrappers return executor(sql, params, many, context) File "c:\proyectos\first-proyect\venv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute with self.db.wrap_database_errors: File "c:\proyectos\first-proyect\venv\lib\site-packages\django\db\utils.py", line 91, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "c:\proyectos\first-proyect\venv\lib\site-packages\django\db\backends\utils.py", line 89, in _execute return self.cursor.execute(sql, params) File "c:\proyectos\first-proyect\venv\lib\site-packages\django\db\backends\mysql\base.py", line 75, in execute return self.cursor.execute(query, args) File "c:\proyectos\first-proyect\venv\lib\site-packages\MySQLdb\cursors.py", line 206, in execute res = self._query(query) File "c:\proyectos\first-proyect\venv\lib\site-packages\MySQLdb\cursors.py", line 319, … -
Django is rendering an awkward result
Basically, I am working on a django project, and whenever I insert data into the database, the result is weirdly formatted. this is my model customer.py class Customer(models.Model): user = models.OneToOneField(User,null=True,blank=True,on_delete=models.CASCADE) name = models.CharField(max_length=200, null=True) email= models.CharField(max_length=200, null=True) phone_number= models.CharField(max_length=200, null=True) def __str__(self): return self.name Now, say I have saved a new customer new_customer = Customer.objects.create(name="Henry",email="henry@mail.com",phone_number="+330145786259") new_customer.save() when i try to retrieve the customer name i get this: print(new_customer.name) >('henry',) Anyone has any insight for me??? I tried to recreate the model on a new project but still having the same result