Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django-admin startproject coredj File "<stdin>", line 1 django-admin startproject core SyntaxError: invalid syntax what's problem here?
whenever i am firing django-admin startproject core this command it throws me syntax error. iam using python version3.11 and django version in 5.0.6. iam trying to create this in my E:drive and i have succesfullly installed the django and import it look for the version created virtaul env but still,not working throwing syntax error at startproject django-admin startproject coredj File "", line 1 django-admin startproject coredj ^^^^^^^^^^^^ SyntaxError: invalid syntax i checked for compatible version of django with python.when i run the command i expect it to create the foldername core in my pythonproject directory which is residing in my** E :**but it's not happening -
In django by turn off the button edit the value in database to ‘NO’ on turn on the button change it to ‘YES’. Using Django
models.py class AssetOwnerPrivileges(models.Model): asset_add = models.CharField(max_length=20,default='YES') html button <td> <label class="switch"> <input type="checkbox"> <span class="slider round"></span> </label> </td> When button switch "ON" ,value in database change to YES ,while button switch "OFF" value change to "NO". -
How to send user ID through forms
I want to display the information in the profile section after receiving the information from the user But I can't submit the user ID through the forms My Models: class PersonalInformation(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='information') full_name = models.CharField(max_length=40) email = models.EmailField(blank=True, null=True) creation_date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.full_name My Forms: class PersonalInformationForm(forms.ModelForm): user = forms.IntegerField(required=False) class Meta: model = PersonalInformation fields = "__all__" MY Views: class PersonalInformationView(View): def post(self, request): form = PersonalInformationForm(request.POST) if form.is_valid(): personal = form.save(commit=False) personal.user = request.user personal.save() return redirect('profile:profile') return render(request, 'profil/profile-personal-info.html', {'information': form}) def get(self, request): form = PersonalInformationForm(request.POST) return render(request, 'profil/profile-personal-info.html', {'information': form}) -
Is serializer.save() atomic?
@api_view(["POST"]) def register_view(request: "Request"): serializer = RegisterSerializer(data=request.data) serializer.is_valid(raise_exception=True) try: serializer.save() except IntegrityError: raise ConflictException return Response(serializer.data, status=status.HTTP_201_CREATED) class ConflictException(APIException): status_code = 409 default_detail = "username is already taken" default_code = "conflict" def test_username_taken(self): with transaction.atomic(): User.objects.create_user(username="customer4", password="Passw0rd!") response = self.client.post( "/register", { "username": "customer4", "password": "Passw0rd!", "confirm_password": "Passw0rd!", "phone_number": "13324252666" }, ) self.assertEqual(response.status_code, status.HTTP_409_CONFLICT) The test result shows : raise TransactionManagementError( django.db.transaction.TransactionManagementError: An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block. I'm a Django and DRF noob and don't know what to do... I tested on postman and there is no problem, with 409 status_code response -
Is it possible to use transfer my django app on fme
So I created a randomiser app with django, I used import random and just called the function in my views. I could also use an implementation of fisher-yates algo to implement the randomisation I want. The person I built the app for has no python knowledge. They can't code with python. So I am trying to maybe integrate the python code on FME because they are efficient in using that. I was just wondering if it will be possible for me to do that. Has anyone tried something like that before and successfully done it. I am taking a short course in FME right now just to learnt the basics of using it. I am just wondering if there are any courses you guys will recommend or any steps for be to integrate the app on FME so they don't have to use django to use the app. -
What is causing this BadDeviceToken response in APNS?
This is my code sending the apns: @classmethod def PingDevice(cls, devicetoken, pushmagic): # Create the payload for the push notification payload = Payload(custom={'mdm': pushmagic}) print("Payload:", payload) print(f"device token: {devicetoken}") # Path to your certificate cert_path = os.path.join(settings.BASE_DIR, 'sign', "PushCert.pem") print("Certificate Path:", cert_path) # Load your certificate and private key credentials = CertificateCredentials(cert_path) print("Credentials:", credentials) # Create an APNs client apns_client = APNsClient(credentials=credentials, use_sandbox=False) print("APNs Client:", apns_client) # Send the push notification try: response = apns_client.send_notification(token_hex=devicetoken, notification=payload, topic='apns-topic') if response == 'Success': print("Push notification sent successfully") else: print(f"Failed to send notification: {response.description}") except Exception as e: print('Bad device token:', e) But i face the problem this is response i get with print in code on AWS: Bad device token: I really appreciate any help. -
OIDC Linkedin authentication canceled in django applicaation
I have integrated OIDC Linkedin third party auth in my django application and it automatically cancled authenticaton. I'm attaching logs for refrence, if anyone faced this issue before or does anyone know the solution please feel free to give me soluction, logs Django version is 4.1.2 library i used social-auth-core: 4.5.4 -
Dynamically generate django .filter() query with various attrs and matching types
I use django 1.6 (yep, sorry) and python2.7 and I need to generate queryset filter dynamically. So, the basic thing I need is to use different fields (field1, field2, field3) in filter and use different type of matching (equals, startsfrom, endswith, contains). Here as an example of possible combinations: Mymodel.objects.filter(field1__strartswith=somevalue). # Or like this: Mymodel.objects.filter(field2__endswith=somevalue). # Or like this: Mymodel.objects.filter(field3=somevalue) # Or like this: Mymodel.objects.filter(atrr3__contains=somevalue) I've found this answer and it looks good but I believe there are some more "django-like" ways to do it. I've also found this one with Q object. But maybe I can somehow import and pass to the queryset some objects of this types of matching? -
How can I get an image displayed in HTML with the URL from a context-object?
I'm new to Django and I'm now stuck at a problem of getting an image from a database displayed in an HTMl via it's URL. I had a code that was already working and I now tried to add advanced features and that's were all started to fall apart. So first of all what's already working: I have a Database where I store the URLs of Images and other data. I then display the images and the other data in a "Report"-Template. This is my view.py for this: from django.shortcuts import render, get_object_or_404 from django.http import JsonResponse from .utils import get_report_image from .models import Report1 from django.views.generic import ListView, DetailView from django.conf import settings from django.http import HttpResponse from django.template.loader import get_template from xhtml2pdf import pisa import pandas as pd class ReportListView(ListView): model = Report1 template_name = 'reports/main.html' class ReportDetailView(DetailView): model = Report1 template_name = 'reports/detail.html' # Create your views here. def is_ajax(request): return request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest' def create_report_view(request): if is_ajax(request): report_id = request.POST.get('report_id') name = request.POST.get('name') remarks = request.POST.get('remarks') img_Energie = request.POST.get('img_Energie') img_Emissionen = request.POST.get('img_Emissionen') img_Energie = get_report_image(img_Energie) img_Emissionen = get_report_image(img_Emissionen) #print("report_id: ", report_id) Report1.objects.create(report_id = report_id, name=name, remarks=remarks, image_Energie=img_Energie, image_Emissionen=img_Emissionen) return JsonResponse({'msg': 'send'}) return JsonResponse({}) and this is … -
static url settings in jinja2
I'm using jinja2 template in Djagon and I want to assign a static url for all my project so that I won't use long relative path in my css and js file. Below is how I set jinja2 template in Django and configured jinja2 environment. TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, { 'BACKEND': 'django.template.backends.jinja2.Jinja2', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], 'environment': 'project.utils.jinja2_env.jinja2_environment', }, }, ] def jinja2_environment(**options): """ This is the :param options: :return: """ env = Environment(**options) env.globals.update({ 'static': StaticFilesStorage.url, 'url': reverse, }) return env However, when I use the static url in my css or js like: <link rel="stylesheet" type="text/css" href="{{ static('css/reset.css') }}"> It raised an error like: File "***\login.html", line 6, in top-level template code <link rel="stylesheet" type="text/css" href="{{ static('css/reset.css') }}"> TypeError: FileSystemStorage.url() missing 1 required positional argument: 'name' I guess maybe there is some conflict between jinja2 and Django because I can't use Django template suggested like below neither {% load static %} {% static 'css/reset.css' %} I could not figure this out. Someone could help me here? Thanks. -
Django creating duplicate records
There are only 5 subjects in the Subject table with unique names, but when run the following query to fill the table, some students have 5 some 10 and some are populated with 15 or 20 records. It should create records for every student for every subject only once. Any clue? def create_student_marks()-> None: try: students_obj = Student.objects.all() for student in students_obj: subjects_obj = Subject.objects.all() for subject in subjects_obj: SubjectMarks.objects.create( student = student, subject = subject, marks = random.randint(30, 100) ) except Exception as ex: print(ex) -
gunicorn issues with ModuleNotFoundError when deploying DRF project to Render due to
DRF project is running in development environment, expects to deploy to Render through yaml. The error message is as follows: ==> Running 'gunicorn core.wsgi:application' Traceback (most recent call last): File "/opt/render/project/src/.venv/bin/gunicorn", line 8, in <module> sys.exit(run()) ^^^^^ File "/opt/render/project/src/.venv/lib/python3.11/site-packages/gunicorn/app/wsgiapp.py", line 67, in run WSGIApplication("%(prog)s [OPTIONS] [APP_MODULE]", prog=prog).run() File "/opt/render/project/src/.venv/lib/python3.11/site-packages/gunicorn/app/base.py", line 236, in run super().run() File "/opt/render/project/src/.venv/lib/python3.11/site-packages/gunicorn/app/base.py", line 72, in run Arbiter(self).run() ^^^^^^^^^^^^^ File "/opt/render/project/src/.venv/lib/python3.11/site-packages/gunicorn/arbiter.py", line 58, in __init__ self.setup(app) File "/opt/render/project/src/.venv/lib/python3.11/site-packages/gunicorn/arbiter.py", line 118, in setup self.app.wsgi() File "/opt/render/project/src/.venv/lib/python3.11/site-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() ^^^^^^^^^^^ File "/opt/render/project/src/.venv/lib/python3.11/site-packages/gunicorn/app/wsgiapp.py", line 58, in load return self.load_wsgiapp() ^^^^^^^^^^^^^^^^^^^ File "/opt/render/project/src/.venv/lib/python3.11/site-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp return util.import_app(self.app_uri) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/opt/render/project/src/.venv/lib/python3.11/site-packages/gunicorn/util.py", line 371, in import_app mod = importlib.import_module(module) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1204, in _gcd_import File "<frozen importlib._bootstrap>", line 1176, in _find_and_load File "<frozen importlib._bootstrap>", line 1126, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1204, in _gcd_import File "<frozen importlib._bootstrap>", line 1176, in _find_and_load File "<frozen importlib._bootstrap>", line 1140, in _find_and_load_unlocked ModuleNotFoundError: No module named 'core' gunicorn is called in Procfile as follows: web: gunicorn core.wsgi:application have tried to change the module name to django_project.core.wsgi:application but the … -
Django __main__.Profile doesn't declare an explicit app label
So I am working on Django and have not much experience with it yet. So far I've set up alright but now I've run into this error: RuntimeError: Model class main.Profile doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. The INSTALLED_APPS looks like INSTALLED_APPS = [ 'tweets.apps.tweetsConfig', 'django.contrib.contenttypes', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'de Sitter vacua', ] I'm completely flabbergasted at this because I have no idea what the issue here is. I tried going through stackexchange Q&As and am clueless as to what the issue here is. Tried some solutions but it doesn't seem to be working. -
Coolify Django Deployment
I'm using Coolify and I want to deploy a Django application. I created an entrypoint.sh #!/bin/sh set -e echo "Running migrations..." python manage.py migrate echo "Collecting static files..." python manage.py collectstatic --noinput echo "Starting Gunicorn HTTP server..." exec gunicorn coolify.wsgi:application --bind 0.0.0.0:8000 I have a Dockerfile and it's all connected in a docker-compose.yml file with the db. The containers are running but I keep getting a Bad Request 400 response for any endpoint. -
Using jquery-editable-select in a Django App
This is my very first Django app so please don't be too harsh :-) I'm trying to use jquery-editable-select in my Django web App but I'm lost. https://github.com/indrimuska/jquery-editable-select According to this link, it seems like I need to install NPM first or Bower. I don't know what these are, can someone give me the basics from scratch ? Is it something to install via PIP like a python package ? -
What percentage of production backends use Raw SQL directly? [closed]
I was looking at Tech Empower’s web frameworks benchmarks.. I noticed that the highest performing versions of the frameworks used raw sql and the setups of the same frameworks that used an ORM or Query builder were significantly less performant (up to 5 times!). Look at actix-web, axum for example. So i’d like to know in a real, large big tech, production environment is raw SQL used and never ORMs or Query builders? -
How do I use JWT token authentication for API requests with rest_framework_simplejwt without needing user identification?
I have an API endpoint for my django application where I am allowing anyone with the JWT access token (valid for 15 mins) to use the API. But it doesn't work when I do a GET request with the access token. Authentication responds with "Token contained no recognizable user identification". Since anyone should be allowed to access the API with the token, I don't need to check if it's valid for any particular user. JWT is a requirement in the project to have stateless user authentication for other APIs. What is the correct/standard way to avoid this? Do I need a custom class or is there any better method to implement token authentication for APIs? -
I am trying to access a model using a foreign key in another model in the same models.py file. But I am getting a name "model_name" not defined error
class chaiVariety(models.Model): CHAI_TYPE_CHOICE = [ ('ML', 'MASALA'), ('GR', 'GINGER'), ('KL', 'KIWI'), ('PL', 'PLAIN'), ('EL', 'ELAICHI'), ] name = models.CharField(max_length=100) image = models.ImageField(upload_to='chais/') date_added = models.DateTimeField(default=timezone.now) type = models.CharField(max_length=2, choices=CHAI_TYPE_CHOICE) description = models.TextField(default=' ') def __str__(self): return self.name #One to many class chaiReview(models.Model): chai = models.ForeignKey(chaiVariety, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) rating = models.IntegerField() comment = models.TextField() date_added = models.DateTimeField(default=timezone.now) def __str__(self): return f'{self.user.username} review for {self.chai.name}' As I am trying to access the chaiVariety model inside the chaiReview using a foreign key, I am getting the following error : name 'chaiVariety' is not defined -
Trouble Filtering CartOrderItems by Vendor Using Django ORM
I'm facing an issue with filtering CartOrderItems by Vendor using Django's ORM. Here's the scenario and the problem I'm encountering: 1.Scenario: I have a Django application where vendors can upload products (Product model) and manage their orders (CartOrderItems and CartOrder models). 2.Objective: I want to fetch orders (CartOrder instances) associated with products uploaded by the current vendor (request.user). 3Current Approach: In my view function vendor_pannel1, I'm trying to achieve this as follows: @login_required def vendor_pannel1(request): # Get products uploaded by the current vendor (user) vendor_products = Product.objects.filter(user=request.user) # Get the vendor IDs associated with these products vendor_ids = vendor_products.values_list("vendor_id", flat=True) # Get CartOrderItems related to those vendors order_items = CartOrderItems.objects.filter(vendor_id__in=vendor_ids) # Get orders related to those CartOrderItems orders = CartOrder.objects.filter(cartorderitems__in=order_items).distinct() context = { "orders": orders, } return render(request, "vendorpannel/dashboard.html", context) Issue: It is filtering nothing. 5.Expected Outcome: I expect to retrieve orders (CartOrder instances) related to products uploaded by the current vendor (request.user). 6.My Models: class CartOrder(models.Model): user=models.ForeignKey(CustomUser,on_delete=models.CASCADE) item=models.CharField(max_length=100) price= models.DecimalField(max_digits=10, decimal_places=2,default="1.99") paid_status=models.BooleanField(default=False) order_date=models.DateTimeField(auto_now_add=True) product_status=models.CharField(choices=STATUS_CHOICE, max_length=30,default="processing") class Meta: verbose_name_plural="Cart Order" class CartOrderItems(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) vendor = models.ForeignKey(Vendor,on_delete=models.CASCADE,default=1)default order=models.ForeignKey(CartOrder,on_delete=models.CASCADE) # product = models.ForeignKey(Product, on_delete=models.CASCADE, default=1) #please dont't ignore it invoice_num = models.BigIntegerField(blank=True,null=True) product_status=models.CharField(max_length=200) item=models.CharField(max_length=100) image=models.CharField(max_length=100) qty=models.BigIntegerField(default=0) price= models.DecimalField(max_digits=12, decimal_places=2,default="15") … -
django orm - how to join multiple tables
I have a bunch of tables in postgresql: create TABLE run ( id integer NOT NULL, build_id integer NOT NULL, ); CREATE TABLE test_info ( suite_id integer NOT NULL, run_id integer NOT NULL, test_id integer NOT NULL, id integer NOT NULL, error_text text ); CREATE TABLE tool_info ( id integer NOT NULL, tool_id integer, revision_id integer, test_info_id integer, ); CREATE TABLE suite_info ( id integer, suite_id integer NOT NULL, run_id integer NOT NULL, ); CREATE TABLE test ( id integer NOT NULL, path text NOT NULL ); I'd like to write the following query using the django ORM. I'm using 2.2. select test.path, tool_info.id, run.id, test_info.id, suite_info.id from run join test_info on run.id = test_info.run_id join suite_info on run.id = suite_info.run_id join tool_info on tool_info.test_info_id=test_info.id join test on test_info.test_id=test.id where run.id=34; I've tried this: x= Run.objects.filter(suiteinfo__run_id=34) (Pdb) str(x.query) 'SELECT "run"."id", "run"."build_id", "run"."date", "run"."type_id", "run"."date_finished", "run"."ko_type", "run"."branch_id", "run"."arch_id" FROM "run" INNER JOIN "suite_info" ON ("run"."id" = "suite_info"."run_id") WHERE "suite_info"."run_id" = 34' I can see it is doing a join, but the data doesn't appear in the select. I've tried selected_related, and the like. the RUN table is the central table that ties the data together. How can I create that query … -
redirect in view not finding url path or html template
I am trying to redirect from one view to another view or url name but getting errors regardless of what type of redirect I use. My preference is to use the view name to avoid hard coding the url. Relevant views snippets involved: main view snippet if form.is_valid(): """ check if passwords match """ print('form is valid') password1 = form.cleaned_data.get('password1') password2 = form.cleaned_data.get('password2') if password1 and password2 and password1 != password2: raise messages.add_message(request, messages.error, "Passwords don't match") return redirect('/members:new_profile') """ create user, set hashed password, redirect to login page """ print('creating user') user = form.save(commit=False) user.set_password(password1) user.save() return redirect('members:user_login') user_login view def UserLogin(request): """ Member authenticate, set session variables and login """ if request.method == 'POST': username = request.POST.get('email') password = request.POST.get('password') user = authenticate(username=username, password=password) if user is not None: if user.is_active: """ set session expiry and variables with login""" login(request, user) request.session.set_expiry(86400) watchlist_items = Watchlist.objects.filter(created_by_id=user.id, status=True).values_list('listing_id', flat=True) print(f"watchlist_items: {watchlist_items}") if watchlist_items: request.session['watchlist'] = list(watchlist_items) print(f"watchlist session variable: {request.session['watchlist']}") messages.add_message(request, messages.success, 'You have successfully logged in') else: request.session['watchlist'] = [] messages.add_message(request, messages.success, 'You have successfully logged in') return redirect('general/dashboard.html') else: """ user has old account, prompt to reactivate and pay new subscription """ messages.add_message(request, messages.error, 'This account is no … -
How I Can Fix Django Deployment Error With Media Files
Set up my django project with nginx, gunicorn and whitenoise; this using a ubuntu environment When I upload an image to my server, everything turns out excellent, but when making the request it gives this error: "GET /media/new/image/Imagen_de_WhatsApp_2024-07-05_a_las_14.24.21_e5e0f412.jpg HTTP/1.1" 404 179" This is the configuration of my different files: nginx: server { listen 80; server_name 127.0.0.1; location /static/ { alias /home/albert-ubuntu/django-club-page/staticfiles/; } location /media/ { alias /home/albert-ubuntu/django-club-page/media/; access_log off; } location / { proxy_pass http://127.0.0.1:8000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } } gunicorn: #!/bin/bash NAME="django-club-page" # Nombre de la aplicación Gunicorn DJANGODIR=/home/albert-ubuntu/django-club-page # Directorio raíz de tu proyecto Django USER=albert-ubuntu # Usuario bajo el cual se ejecutará Gunicorn GROUP=albert-ubuntu # Grupo bajo el cual se ejecutará Gunicorn WORKERS=3 # Número de workers que Gunicorn utilizará BIND=127.0.0.1:8000 # Dirección y puerto donde Gunicorn escuchará DJANGO_SETTINGS_MODULE=api.settings # Módulo de configuración de Django que Gunicorn usará DJANGO_WSGI_MODULE=api.wsgi # Módulo WSGI de Django que Gunicorn cargará echo "Starting $NAME as `whoami`" cd $DJANGODIR # Cambiar al directorio de tu proyecto Django source venv/bin/activate # Activar el entorno virtual de Python (si lo usas) export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE export PYTHONPATH=$DJANGODIR:$PYTHONPATH # Añadir el directorio de tu proyecto al PYTHONPATH # … -
React + Django webapp doesnt show user messages, despite showing server messages which are managed by the same logic both frontend and backend
What the title says, I'm trying to make battleships with websockets, yesterday everything was going more or less smooth, aside from having multiple ws opening so after changing stuff around for a while and deleting <StrictMode> i solved that problem but realized that users couldnt send messages anymore. On Frontend those are the 2 tsx files, im new to both React and websockets so perhaps im misusing the component type or something idk. Lobby.tsx : import './Lobby.css'; import React, { useEffect, useState, useRef } from 'react'; import ChatLog from '../components/ChatLog'; import BattleShipGame from '../components/BattleShipGame'; const Lobby: React.FC = () => { const [messages, setMessages] = useState<{ message: string, username: string }[]>([]); const [message, setMessage] = useState(''); const [ws, setWs] = useState<WebSocket | null>(null); const isWsOpen = useRef(false); useEffect(() => { const roomName = new URLSearchParams(window.location.search).get('room'); const token = localStorage.getItem('accessToken'); if (roomName && token && !isWsOpen.current) { console.log('Attempting to open WebSocket connection'); const socket = new WebSocket(`ws://192.168.1.125:8000/ws/lobby/${roomName}/${token}/`); socket.onmessage = (event) => { const data = JSON.parse(event.data); console.log('Received WebSocket message:', data); if (data.type === 'chat_message') { console.log('Received chat message:', data); setMessages((prev) => { const newMessages = [...prev, { message: data.message, username: data.username }]; console.log('Updating messages state with:', newMessages); return newMessages; }); } … -
I'm trying to import csv data into a Django model. The import is failing due to data types
I'm using the Django import,export module in the admin panel. The import field in question is a CHAR field. The csv field in question can contain numbers or numbers and letters. If an entry contains just a number, it imports nothing for this field. If I load this csv file in a spreadsheet, it shows that the fields that contain only numbers are considered numbers, but the fields with a mix are obviously not numbers. I expected the fields with only numbers to be accepted as CHAR, since they are allowed normally. I don't understand why it is not accepting these values as characters, or what I can do about it. Is the problem with the import procedure, how the field is defined in Django, or is it some type of formatting that is needed in the csv? Thanks. -
Why Django API serializer.data return the data empty?
I have a strange issue with my Django API I created a Model called States My serializer has printed the data well but the serializer.data printing the data like the attached screen class States(models.Model): en_name = models.CharField(max_length=100) ar_name = models.CharField(max_length=100) class Meta: verbose_name_plural = "States" def __str__(self): return self.en_name and I created a Serializer file class StatesSerializer(serializers.Serializer): class Meta: model = States fields = ['en_name', 'ar_name'] then I made my views.py @api_view(['GET']) @permission_classes([IsAuthenticated]) def getStates(request): states = States.objects.all() # Fetch all states from the database serializer = StatesSerializer(states, many=True) # Serialize the data print(serializer) # Add this line to check the serialized data return Response(serializer.data, status=status.HTTP_200_OK) my printed serializer StatesSerializer(<QuerySet [<States: Alexandria>, <States: Aswan>, <States: Asyut>, <States: Beheira>, <States: Beni Suef>, <States: Cairo>, <States: Dakahlia>, <States: Damietta>, <States: Faiyum>, <States: Gharbia>, <States: Giza>, <States: Ismailia>, <States: Kafr El Sheikh>, <States: Luxor>, <States: Matruh>, <States: Minya>, <States: Monufia>, <States: New Valley>, <States: North Sinai>, <States: Port Said>, '...(remaining elements truncated)...']>, many=True): the attached screen shows how the data is returned