Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
the error ('QuerySetManager' object is not callable) pops up? dont understand why?
def connectFunctionToNonFunction(functionID, nfID): connect_toMongoDB() print("In side connect function and function id is: ", functionID, "nonfunction id is: ", nfID) find=model_mongo.mapFunctionToNonfunction() find=find.objects(funID=functionID).get() print("find is ==========", find.funID, find.non_function_lst) if find is not None: find.update(push__non_function_lst= str(nfID)) find.save() else: print("object does not exist.. adding is in process") ds = model_mongo.mapFunctionToNonfunction() ds.funID=functionID ds.non_function_lst.append(str(nfID)) ds.save() print("index is sucessfully added") -
How to manage JSON data in javascript pass form django model?
I need to dynamically display my audio on my website. The audio is a file path stored in the Django model. Djanog Model: class audio(models.Model): instrumentId = models.OneToOneField(instrument, on_delete=models.CASCADE, primary_key=True) location = models.FileField() I pass the data through view.py into json data so my script can read the data. view.py, PostJsonListView fetch data form the model and generate json data, testView connect to the html displaying audios class PostJsonListView(View): def get(self, *args, **kwargs): print(kwargs) #upper is to get the number from the js file to set a upper boundry upper = kwargs.get('num_aduios') #intial state be 3 lower = upper - 3 #pass in the audio in to the list [lower:upper] use to set boundry audios = list(audio.objects.values()[lower:upper]) #comfirmation of no more audi to load audio_size = len(audio.objects.values()) size = True if upper >= audio_size else False return JsonResponse({'data':audios, 'max': size}, safe=False) class testView(TemplateView): template_name = 'frontend/testView.html' JSON data in browser Javascript that hand the data, after a button click, it would display three more data console.log('HELLO') const aduiosBox = document.getElementById('audio-box') //get the div audio-box const nextBtn = document.getElementById('next-btn') let visible = 3 const handleGetData = () =>{ $.ajax({ type: 'GET', url: `/json/${visible}/`, success: function(response) { max_size = response.max //getting all … -
How to fetch page_obj before passing to template
I am using pagenation so, in template page_obj has already selected-by-page items. {% for obj in page_obj %} So, I want to get the selected-by-page items in view class before passing to template. Is it possible? class ActionListView(LoginRequiredMixin, ListSearchView): template_name = "message_logs/action_delivery_log.html" form_class = ActionLogSearchForm model = Delivery.history.model def get_queryset(self): //is it possible to get the selected page_obj here? // or can I override some other function to get the page_obj? -
problem with rendering of property (django)
I'm trying to learn about property. I'm trying to get an output but it doesn't work what is the problem? class ShiftPlace(models.Model): name = models.ManyToManyField(to=DashboardEmploye) adress = models.CharField(blank=True, null=True, max_length=200) postcode = models.CharField(max_length=60) HouseNumber = models.IntegerField(blank=False, null=False) city = models.CharField(null=False, blank=False, max_length=200) startTime = models.TimeField(auto_now=False) endTime = models.TimeField(auto_now=False) comment = models.TextField(blank=True, null=True, max_length=10000) @property def Get_time(self): return 41 html <div class="card"><li>Totale Uren gepland: {{shiftplace.Get_time}}</li></div> view def dashboard(request): employe = DashboardEmploye.objects.all() shift = ShiftPlace.objects.all() employeInfo = Employe.objects.all() context ={ 'employe': employe, 'employeInfo': employeInfo, 'shift': shift } return render(request, 'dash/dashboard.html', context) -
Grid or table in model in django admin
I have a model with different fields: char, datetime and etc. I want to use a table or a grid for one field in django admin. I want to use it not on the main page, but on the page, where I can edit this model. something like that: Info: time day 10:00 Monday 03:00 Friday Is it possible to do it? -
Use historycalRecords as default model in view class
I am using HistorycalRecords as table member from simple_history.models import HistoricalRecords class Delivery(BaseModel): history = HistoricalRecords( excluded_fields=['created_by', 'updated_by', 'updated_at']) It create another table automatically named such as myapp_historicaldelivery Now I want to use historical table itself as default model of view. Because I would like to show the list of changed points. class ActionLogListView(LoginRequiredMixin, ListSearchView): template_name = "message_logs/action_log.html" form_class = ActionLogSearchForm model = Delivery.history // want to set here. However it shows error, maybe because Delivery.history is not model. TypeError: object of type 'NoneType' has no len() HistorycalModel source code is here https://github.com/jazzband/django-simple-history/blob/master/simple_history/models.py How can I treat history as model class to show the list in view? -
Windows: vscode python3 virtualenv not working when trying to install package
I am trying to work on a Django project, but when I create a Virtualenv, then installing the package is not working. can someone help me because I tried to look on google for a day I did not find any working solution. python 3.10.4. please help PS C:\Users\schad\Desktop\importExport> & c:/Users/schad/Desktop/importExport/env/Scripts/Activate.ps1 (env) PS C:\Users\schad\Desktop\importExport> pip install django-import-export Fatal error in launcher: Unable to create process using '"C:\Users\schad\Desktop\env\Scripts\python.exe" "C:\Users\schad\Desktop\importExport\env\Scripts\pip.exe" install django-import-export': The system cannot find the file specified. (env) PS C:\Users\schad\Desktop\importExport> pip install mysqlclient Fatal error in launcher: Unable to create process using '"C:\Users\schad\Desktop\env\Scripts\python.exe" "C:\Users\schad\Desktop\importExport\env\Scripts\pip.exe" install mysqlclient': The system cannot find the file specified. (env) PS C:\Users\schad\Desktop\importExport> [project][1] -
how to install channels_redis module in django without errors
am trying to install channels_redis in Django using pip but so far am getting this error: Building wheel for hiredis (setup.py) ... error error: subprocess-exited-with-error × python setup.py bdist_wheel did not run successfully. │ exit code: 1 ╰─> [17 lines of output] C:\Users\Teacher-5F84DF\AppData\Local\Temp\pip-install-a7pi2nhv\hiredis_6b689b761b5b44cc87e6dbe9cbaa0597\setup.py:7: DeprecationWarning: the imp module is deprecated in favour of importlib and slated for removal in Python 3.12; see the module's documentation for alternative uses import sys, imp, os, glob, io c:\users\teacher-5f84df\appdata\local\programs\python\python310\lib\site-packages\setuptools\dist.py:697: UserWarning: Usage of dash-separated 'description-file' will not be supported in future versions. Please use the underscore name 'description_file' instead warnings.warn( running bdist_wheel running build running build_py creating build creating build\lib.win-amd64-3.10 creating build\lib.win-amd64-3.10\hiredis copying hiredis\version.py -> build\lib.win-amd64-3.10\hiredis copying hiredis\__init__.py -> build\lib.win-amd64-3.10\hiredis copying hiredis\hiredis.pyi -> build\lib.win-amd64-3.10\hiredis copying hiredis\py.typed -> build\lib.win-amd64-3.10\hiredis running build_ext building 'hiredis.hiredis' extension error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/ [end of output] I tried installing pip install python-dev-tools but dint work.Please help am stuck. -
Reduce Read Time of a File for Web Application
I made a Django application (runs on Apache mod-wsgi server) which reads contents of a file(with million entries in it) and displays it after performing some operations on it (operation time very less compared to read time). Actually the file stores the metadata of objects in cloud. So instead of fetching the data from cloud everytime a user opens the application, the metadata is cached on the server which is used. This cached data is synced regularly with cloud to store the latest metadata. Now the problem with this is that the data in cloud scales exponentially due to which the cached metadata in the file also increases thereby increasing the number of entries which in turn slows down the application. What should I do to reduce the read time of file so that the application reads quickly and in turn load time decreases? -
Django logging only logs "root", no other handlers
This is my Django logging config: LOGGING = { "version": 1, "disable_existing_loggers": False, "filters": {"require_debug_false": {"()": "django.utils.log.RequireDebugFalse"}}, "formatters": { "verbose": { "format": "%(levelname)s %(asctime)s %(module)s " "%(process)d %(thread)d %(message)s" } }, "handlers": { "mail_admins": { "level": "ERROR", "filters": ["require_debug_false"], "class": "django.utils.log.AdminEmailHandler", 'include_html': True, }, "console": { "level": "DEBUG", "class": "logging.StreamHandler", "formatter": "verbose", }, "file": { "class": "logging.FileHandler", "filename": os.path.join(APPS_DIR + "..", "app.log"), }, 'db_queries': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': os.path.join(APPS_DIR + "..", 'db_queries.log'), }, }, "root": { "level": "WARNING", "handlers": ["file", "mail_admins"], "propagate": True, }, "loggers": { "django.request": { "handlers": ["file", "mail_admins"], "level": "ERROR", "propagate": True, }, "django.security.DisallowedHost": { "level": "ERROR", "handlers": ["file", "mail_admins"], "propagate": True, }, "django": { "handlers": ["file"], "level": "DEBUG", "propagate": True, }, 'django.db.backends': { 'level': 'DEBUG', 'handlers': ['db_queries'], 'propagate': False, }, }, } The "root" logger works, both for file and mails_admin, but the other loggers don't seem to do anything. I would expect that at least the "django" and "django.db.backends" handlers would write something to file. Any ideas what could be the cause? -
Postgres: Convert `character varying[]` to string
After loading data from a django dumpdata using loaddata one column was somehow converted from character varying(100)[] to character varying(100)[][]. How can I collapse the inner array. Example: previous data {frank} uploaded data {{f,r,a,n,k}} -
Construct DQL by multiple Q filter
I have class AppUser and AppUserGroup and each AppUser has one type and AppUserGroup has multiple types class AppUser(BaseModel): user_type = m.ForeignKey('UserType', on_delete=m.SET_NULL, null=True, blank=True,default=1) class AppUserGroup(BaseModel): user_types = m.ManyToManyField('UserType',blank=True) Now I want to fetch the AppUser which has the type which AppUserGroup has , like this below fetch_users class AppUserGroup(BaseModel): user_types = m.ManyToManyField('UserType',blank=True) def fetch_users(self): app_users = [] for user_type in self.user_types: temp = AppUser.objects.filter(type=user_type) app_users.append(temp) However it's wrong way , because app_users are not the list of AppUser. And I call AppUser.objects.filter many times. I want to call db more simply such as AppUser.objects.filter(Q(type=user_types[0] | Q(type=user_types[1] | ... )) How can I construct this query?? -
I'm trying to check if two column's specific values in a db table exist in the same row
Essentially I'm trying to make sure that both of the values the two columns have exist in a row. If they do I'll return a True boolean value. Just unclear on the logic to do the check itself. -
Dynamically update pandas NaN based on field type in django model
I need to save data from csv file to django models. The data comes from external api so I have no control on its structure. In my schema, I allowed all fields to be nullable. This is my script text = f"{path}/report.csv" df = pd.read_csv(text) row_iter = df.iterrows() for index, row in row_iter: rows = {key.replace("-", "_"): row.pop(key) for key in row.keys()} # print(f"rows {rows}") # default_values = { # "amazon-order-id",merchant-order-id,purchase-date,last-updated-date,order-status,fulfillment-channel,sales-channel,order-channel,ship-service-level,product-name,sku,asin,item-status,quantity,currency,item-price,item-tax,shipping-price,shipping-tax,gift-wrap-price,gift-wrap-tax,item-promotion-discount,ship-promotion-discount,ship-city,ship-state,ship-postal-code,ship-country,promotion-ids,is-business-order,purchase-order-number,price-designation,is-iba,order-invoice-type # } sb, created = Order.objects.update_or_create( sellingpartner_customer=c, amazon_order_id=rows["amazon_order_id"], sku=rows["sku"], asin=rows["asin"], defaults={**rows}, ) However, since some of the csv fields has empty values, pandas will replace it with NaN value, this is where django returns an error django.db.utils.OperationalError: (1054, "Unknown column 'NaN' in 'field list'") I tried replace empty values as empty string("") df.fillna("", inplace=True) But django will return an error for fields that are not charfields django.core.exceptions.ValidationError: ['“” value must be a decimal number.'] My question is, how do you handle empty values from csv file in pandas so for example if the field type is boolean, pandas will just replace empty value with boolean False for django boolean type fields, 0 for empty decimal types, and just blank for empty charfields, etc ? -
Managing multiple Model Relationships
I've been scratching my head for a while trying to deal with this, it's really complex to me. I'm quite new to Django and currently learning how to manage model relationships. I've done the following: Build a relationship between models based on this: A User can have a Job Title (Director, Analyst, etc), and this job title is related to the user's State and Sector(Who is responsible by X events) I've done the following: Job Title Class: class JobTitle(models.Model): JOB_TITLES = [ ('0', 'Director'), ('1', 'Manager'), ('2', 'Coordinator'), ('3', 'Supervisor'), ('4', 'Analyst'), ] jobtitle = models.CharField(max_length=35, choices=JOB_TITLES) user = models.ForeignKey(User, on_delete=models.CASCADE, >null=False, blank=False) state = models.ForeignKey(States, on_delete=models.SET_NULL, >null=True) sector = models.ForeignKey(Sector, on_delete=models.SET_NULL, >null=True) class Meta: verbose_name = "Job Title" verbose_name_plural = "Job Titles" def __str__(self): return self.jobtitle This is the State Class: class States(models.Model): states = models.CharField(max_length=100) def __str__(self) -> str: return self.states class Meta: verbose_name_plural = "States" And the Sector class: class Sector(models.Model): sector = models.CharField(max_length=100) events = models.ManyToManyField(Event) class Meta: verbose_name = "Sector" def __str__(self) -> str: return self.sector Well, Sectors have many Events related to them, and these Events have many Categories to them Events Class: class Event(models.Model): events = models.CharField(max_length=100) category = models.ManyToManyField(Category) def __str__(self): return … -
How do I map query results to an HTML table in python?
I have two tables : Driver and Car from django.db import models # Create your models here. class Driver(models.Model): name = models.TextField() license = models.TextField() class Car(models.Model): make = models.TextField() model = models.TextField() year = models.IntegerField() vin = models.TextField() owner = models.ForeignKey("Driver", on_delete=models.SET_NULL, null=True) And here is the data inside the tables: INSERT INTO car_driver (name, license) VALUES ('John Smith', 'ZX1092931i'), ('Karen Doe', 'KOanksndan'); INSERT INTO car_car (make, model, year, vin, owner_id) VALUES ('Mercedes', 'Legend', 2009, '912asdasda12', 1), ('Nissan', 'Altima', 2002, 'a9a98aa7a772', 1), ('Lada', 'Kalina', 1987, 'SU91991', 2), ('BMW', 'Challenger', 2013, 'BM91818X', 2); It doesn't matter what type of query I do, I would like to display an empty html table, and depending on the query the results get populated from django.shortcuts import render from car.models import Car, Driver # Create your views here. def car_detail(request, pk): owner_obj = Driver.objects.get(pk=pk) car_objs = Car.objects.filter(owner_id=owner_obj.id) context = { "vehicles": car_objs, "drivers": owner_obj, } return render(request, "v2.html", context) And here is the html: <!doctype html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Contacts</title> <link rel="stylesheet" href="https://unpkg.com/tachyons@4.10.0/css/tachyons.min.css"/> </head> <body> <h1>V2</h1> <table> {% block page_content %} <tr> <th></th> </tr> {% endblock %} </table> </body> </html> I'm coming from Node/Express, the way I would do … -
How to use Kepler.gl in Django?
iam new here and searching for a solution to integrate Kepler.gl to a Django Project. I installed yarn, npm, node.js. Got react (17.0.2) react-dom (17.0.2) react-redux (3.3.7) kepler.gl (2.5.5) invariant (2.2.4) uuid styled-components via yarn add. But the code is all time red underlined with no solution. Is it even possible to use Kepler.gl in the django project in pycharm itself? On the view with the generated code via html (from the kepler website) it works with linked scripts, but i have to customize the ui and thats not possible trough the html with scripts. Do anybody know how to do this? There are no tutorials or material, that explain ho to do Django with Kepler.gl. Hope somebody know anything. Thank you for helping guys. Kind Regards hsul-so -
Why is django-storages s3boto3 backend file url failing with AWS Signature Version 4 error?
The django-storages s3boto3 backend claims to provide presigned url generation for files uploaded to s3 using the url property on the file field. The generated url looks about right, but is returning the S3 error 'Requests specifying Server Side Encryption with AWS KMS managed keys require AWS Signature Version 4.' How can I fix this? -
Getting CORS error in frontend with Django backend
From my frontend http://127.0.0.1:5500/index.html I am calling Django REST POST API http://127.0.0.1:8000/api. I have installed django-cors-headers and my frontend's image_upload.js, backend's settings.py, and views.py, project level urls.py and app level urls.py are as follows, API is working in postman but I am getting CORS error in chromes console, Chrome console Django console image_upload.js const image_input = document.querySelector("#image_input"); const display_image = document.querySelector("#display-image"); image_input.addEventListener("change", (event) => { console.log(event.target.files[0]); // console.log(URL.createObjectURL(event.target.files[0])); display_image.src = URL.createObjectURL(event.target.files[0]); const url = "http://127.0.0.1:8000/api"; const data = event.target.files[0]; axios .post(url, JSON.stringify(data), { method: "POST", headers: { "Content-Type": "application/json", "Access-Control-Allow-Origin": "*", }, }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }); }); settings.py """ Django settings for model project. Generated by 'django-admin startproject' using Django 2.2. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'pd^*8)+5$qr_q9(a+n)(meh22&m=0+qn7a^g8$#&)(+fv!1wgc' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['http://127.0.0.1:5500'] # Application definition INSTALLED_APPS = … -
selected option in view
I have a radio checkboxes poll that I pass selected_option to the view, when I compare it to the loop counter it's 0 and 0 but says it's false. template: <label id="poll"> <input type="radio" name="poll" value="{{ forloop.counter0}}" required> {{ poll.option }} - {{poll.votes}} </label> &nbsp; views.py: selected_option = request.POST['poll'] print(selected_option == i) if selected_option == i: for i, poll in enumerate(polls): if Vote.objects.get(poll=poll,voter=request.user).exists(): if poll.votes - 1 < 0: Vote.objects.get(poll=poll ,voter=request.user).delete() return JsonResponse(poll.votes, safe=False) -
pending state in celery django redis
I am getting pending state in celery. I have built a django app and put celery.py in same folder with settings.py is. In celery.py i put following from __future__ import absolute_import, unicode_literals import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'main_app.settings') app = Celery('main_app') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) @app.task def add(x, y): return x + y When i do python manage.py shell from main_app.celery import add,debug_task debug_task.delay() the output is <AsyncResult: 47aba4e5-c9e7-48a3-8453-8de2453ada03> and when i do task = add.delay(1, 2) print(task.state) the state is pending. When i run following command celery -A main_app.celery worker --loglevel=info the output is -------------- celery@my-pc v5.2.6 (dawn-chorus) --- ***** ----- -- ******* ---- Linux-5.13.0-39-generic-x86_64-with-glibc2.29 2022-04-13 14:36:42 - *** --- * --- - ** ---------- [config] - ** ---------- .> app: main_app:0x7fc36fc757f0 - ** ---------- .> transport: redis://localhost:6379// - ** ---------- .> results: redis://localhost:6379/ - *** --- * --- .> concurrency: 24 (prefork) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- -------------- [queues] .> celery exchange=celery(direct) key -
How to put a link in ModelChoiceField empty_label?
I'm working on an app, with a form that is a ModelForm. I have select boxes for the model foreign keys that display all the objects of the related tables. Since ther are many objects in the table, I would like to display only a few and have an exta option that when clicked on displays a kind of modal with the list of all objects of the table. My form.py: class ltaForm(ModelForm): def __init__(self, *args, **kwargs): super(ltaForm,self).__init__(*args, **kwargs) self.fields['idagent'] = ModelChoiceField(queryset = Agent.objects.all()[:7], empty_label="<a>Plus</a>") self.fields['idagent'].widget.attrs.update({'class': "form-control m-1 d-inline-block"}) class Meta: model = Lta fields = '__all__' My template: <form> ... <div class="row m-1"> <div class="col-5"> <label for="{{ ltaform.idagent.id_for_label }}">Emmetteur</label> {{ ltaform.idagent}} <button type="button" class="btn btn rounded rounded-circle float-start bg-light" data-bs-toggle="modal" data-bs-target="#agentModal" id="agentVolModalButton"> <i class="fa-solid fa-plus text-secondary"></i> </button> </div> </div> ... </form> What I would like is to have an extra option that triggers that modal or popup that I described, so I was wondering if I could set a link in the ModelChoice empty_label to do that. But the way I do it here it just displays as plain text in the html. Is there a way to achieve what I want to achieve ? Thanks in advance -
How to solve <Request 400> Error in django?
I tried to make a request from my Django project. This is my code: st_data = {"documentId": 1388, "type": 1, "useAsMain": True } headers2 = { 'Authorization': 'Bearer ' + token_key, "Content-Type": "application/json" } statement = requests.post(url_statement, headers=headers2, data=json.dumps(st_data)) The response of this request is <response 400> And the error code is: {"type":"https://tools.ietf.org/html/rfc7231#section-6.5.1","title":"One or more validation errors occurred.","status":400,"traceId":"00-0bbcfce14dfc2146b553c2d98c323b3d-80f72a6fe60f18 4c-00","errors":{"$":["The JSON value could not be converted to System.Collections.Generic.IEnumerable`1[Otc.Data.Objects.StatementDTO]. Path: $ | LineNumber: 0 | BytePositionInLi ne: 1."]}} But when I send request from Swagger UI like; It returns <response 200> Where is my mistake? -
In django admin panel permissions given to the users by group not working
In Django admin panel I create groups and give permission to them. eg: Create a Student Group and give it permission to view the student model. Create a Teacher Group and give it permission to view the student model and add the student model. create user using API and added to those groups, and also staff status checked for each user. When users log in on the admin panel that shows Site administration You don’t have permission to view or edit anything. How to solve it. -
Django Admin filter then exclude products
When i am filtering, i am getting all the products name , that i am not expecting also those products are not assigned to any country just list of name products. i made this query to exclude but not working. admin.py def formfield_for_manytomany(self, db_field, request, product_name=None, product_name__isnull= True, **kwargs): if db_field.name == "product_name" : kwargs["queryset"] = models.ProductName.objects.filter(product_name == request._user_country).exclude(product_name__isnull == True) return super().formfield_for_foreignkey(db_field, request, **kwargs) model.py class Product(models.Model): name = models.ManyToManyField( ProductName, verbose_name=_("Products Name") country = models.ForeignKey(Country, on_delete=models.CASCADE, verbose_name=_("Country"))