Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Many To Many Field Django throwing errors
I am trying to store form-data to a model, when the user submits the form all of the data is saved correctly but a many to many field (catagory) which is throwing errors. Can someone please help me edit my view so that I can save this information? Thank you in advance. I tried to save the field 'Catagory' but at first couldn't. Then I came across answers that said to add self.save_m2m() before self.save(commit=False). But this leads to another error: Environment: Request Method: POST Request URL: http://127.0.0.1:8000/create/ Django Version: 3.2.5 Python Version: 3.9.6 Installed Applications: ['fontawesome_free', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'jquery', 'portfolio', 'blog', 'import_export', 'tinymce', 'hitcount', 'taggit', 'accounts'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "C:\Users\Babli\AppData\Roaming\Python\Python39\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Babli\AppData\Roaming\Python\Python39\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Babli\AppData\Roaming\Python\Python39\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "C:\Users\Babli\Desktop\My-Projects\MySite\mysite\blog\views.py", line 35, in make_post form.save_m2m() File "C:\Users\Babli\AppData\Roaming\Python\Python39\site-packages\django\forms\models.py", line 451, in _save_m2m f.save_form_data(self.instance, cleaned_data[f.name]) File "C:\Users\Babli\AppData\Roaming\Python\Python39\site-packages\django\db\models\fields\related.py", line 1668, in save_form_data getattr(instance, self.attname).set(data) File "C:\Users\Babli\AppData\Roaming\Python\Python39\site-packages\django\db\models\fields\related_descriptors.py", line 536, in __get__ return self.related_manager_cls(instance) File "C:\Users\Babli\AppData\Roaming\Python\Python39\site-packages\django\db\models\fields\related_descriptors.py", line 851, in __init__ raise ValueError('"%r" needs to have a value for … -
I want to use Django-ratelimit api when my api request fails . So it there any way out to use if condition or this type of condition .?
I want to use Django-ratelimit api when my api request fails . So it there any way out to use if condition or this type of condition ?? -
how to kill uwsgi process without worker respawn
I have had trouble to kill uwsgi processes. Whenever I use below commands to shutdown uwsgi, another uwsgi workers respawned after a few seconds. So after shutdown uwsgi process and start up uwsgi server again, uwsgi processes continues to accumulate in memory. sudo pkill -f uwsgi -9 kill -9 cat /tmp/MyProject.pid uwsgi --stop /tmp/MyProject.pid I want to know how to kill uwsgi processes not making uwsgi workers respawned. I attach ini file as below. [uwsgi] chdir = /home/data/MyProject/ module = MyProject.wsgi home = /home/data/anaconda3/envs/env1 master = true pidfile = /tmp/MyProject.pid single-interpreter = true die-on-term = true processes = 4 socket = /home/data/MyProject/MyProject.sock chmod-socket = 666 vacuum = true Thank you in advance!! -
How to compare html input value in django?
I am allowing users to input certain data. I got the user input data in the Django view.py but when I try to compare the user with other data. It doesn't work properly def compare(request) if request.method == 'POST': data = request.POST.get('data') if data == 'yes': print("no") elif data == 'menu': print(True) html <form method="post" enctype="multipart/form-data"> {% csrf_token %} <label for="your_name"> Specific Data </label> <input type="text" name="data" placeholder="Enter yes or menu "> <br> <button type="submit" name="submit">submit</button> </form> I entered the "menu" on the input section but it is working with a ( " if data == 'yes' ) statement -
Selenium webdriver for Django/React for Github Actions
So, to use webdriver for a django react project, I start the backend and frontend and then I use the url with webdriver, and it works fine locally. But I can't do that with Github Actions as python manage.py runserver and npm start get into infinite loops... How to get around this to make selenium work on Github Actions? -
HTML "capture" attribute for desktop computer/pc
I'm making a web app using Django that requests images from users and processes them. When I use the following code: <label for="imageFile">Upload a photo:</label> <input type="file" id="imageFile" capture="user" accept="image/*"> I don't get an option to take a photo from the laptop's camera. Several websites said that the capture attribute might not work for desktop computers and I don't know what I should use instead. -
Django request.POST.get doesn't work with Vanilla JavaScript requests
I already found a solution to this problem, but I only know that it works. I don't know how or why and that's the purpose of this question. I have a Vanilla JavaScript file that controls a dependent drop-down list of countries-regions-cities triplets. Here is the code: {% load i18n %} {% load static %} <script> /* This function retrieve the csrf token from the cookies */ function getCookie(name) { const value = `; ${document.cookie}`; const parts = value.split(`; ${name}=`); if (parts.length === 2) return parts.pop().split(';').shift(); } /* This function just sorts the list of regions or cities */ function sortList(dataList){ return dataList.sort(function(a, b){ if (a[1] < b[1]) return -1; if (a[1] > b[1]) return 1; return 0; }); } /** Creates a XmlReq request and send it. @param function func_name - it's the function in the server that will be called asynchronously. @param string token - it's the csrf token necessary to validate django forms. @param data json object - it's the data to send to the server @param callback callback - it's the callback function to be called on success. **/ function createXmlReq(func_name, token, data, callback){ var xhr = new XMLHttpRequest(); xhr.addEventListener("load", callback); xhr.open("POST", func_name); xhr.setRequestHeader("X-CSRFToken", token); /* … -
Allauth doesn't work with twitch in django
I am trying to authenticate via twitch on my site. I use allauth for github and everything works, but not for twitch. This is all I have: #settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'main', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.twitch', #'django.extensions', 'django.contrib.sites', 'allauth.socialaccount.providers.github', ] LOGIN_REDIRECT_URL = "home" ACCOUNT_EMAIL_VERIFICATION = 'none' SITE_ID = 1 I also want to show what I get as a result: here it is And twitch settings: here it is Maybe someone knows how to fix this? Would really appreciate any help -
Custom permissions for different user types django rest framework
For Django-reactjs project, I have a user model in django which has 3 boolean fields (is_admin, is_moderator, is_normal_user), and I also have 3 other models, I want to set permissions for each user type. The user can only create objects for 1 model only, the moderator is the only one that can edit a certain model field, and admins can do everything. It might be a trivial question but I am a newbie in Django and React so If you could please tell me how can I handle it with custom permissions(some steps to follow) and also how these permissions are handled from React. Thanks in advance! -
Is there a way to compare the stored values and the inputs by user to remove duplicates in django views?
I have a variable in Django View which is interfacelist and it contains [TenGigabitEthernet1/0/1, TenGigabitEthernet1/0/2, TenGigabitEthernet1/0/20, TenGigabitEthernet1/0/21]. This is what the user input from the HTML and I request.POST.get it to the view. And in my database (SQL), I have the following: Here comes the question, how do i compare the data in the database and interfacelist and remove any duplicates? Like in this case, TenGigabitEthernet1/0/1, TenGigabitEthernet1/0/2 so I would remove it and keep the TenGigabitEthernet1/0/20, TenGigabitEthernet1/0/21 to be updated in the database. I tried the following codes: (This is happening is Django View) cursor.execute(f"SELECT interface FROM {tablename} WHERE id >=2") righttable = cursor.fetchall() print(righttable) #Notworking #for i in righttable: # if interfacelist[i] == righttable[i]: # interfacelist.remove(a) #Notworking for i in interfacelist: updatequery2 = f"INSERT INTO {tablename}(interface) VALUES('{i}')" cursor.execute(updatequery2) cursor.close() The variable righttable in this case will be the image shown earlier. It contains [TenGigabitEthernet1/0/1,TenGigabitEthernet1/0/2,TenGigabitEthernet1/0/3,TenGigabitEthernet1/0/4,TenGigabitEthernet1/0/5]. Also, the commented out codes are not working as it gives me a error of list indices must be integers or slices, not tuple. How do I fix this to achieve what I wanted? Would greatly appreciate if anyone can advise or help me. Thank you! -
django model object filter from 2 different model
So I am trying to filter comments made by a specific user within a specific station. First I have a model named comment and it has a relationship with the post. class Comment(Votable): post = models.ForeignKey(Post, related_name='comments', on_delete=models.CASCADE) author = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='comments_authored', on_delete=models.CASCADE, blank=True) text = RichTextUploadingField(blank=True, null=True) parent = models.ForeignKey('self', related_name='children', null=True, blank=True, on_delete=models.PROTECT) It's pretty easy to filter just based on author. And then I have the model for post: class Post(Votable): title = models.CharField(max_length=200, unique=False) submitter = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='posts_submitted', on_delete=models.CASCADE) url = models.URLField('URL', max_length=200, null=True, blank=True) text = RichTextUploadingField(blank=True, null=True) def children(self): return self.comments.filter(parent=None) def __str__(self): return self.title def save(self, *args, **kwargs): # new if not self.post_slug: self.post_slug = slugify(str(self.title)+str(self.pk)) return super().save(*args, **kwargs) The post model has a relationship with the station, which I use StationPost to establish the relationship. So a station can have many posts: class StationPost(BaseModel): station = models.ForeignKey('Station', related_name='posts_set', on_delete=models.CASCADE) post = models.ForeignKey('Post', related_name='station', on_delete=models.CASCADE) class Meta: unique_together = ['station', 'post'] And in case of any confusion, here is the model for station class Station(BaseModel): #this is to add the station for each posts: alphanumeric = RegexValidator(r'^[0-9a-zA-Z]*$', 'Only alphanumeric characters are allowed.') station_name=models.CharField(max_length=19,validators=[alphanumeric], unique=True) creator = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='station_creator', on_delete=models.CASCADE) text = models.TextField(max_length=200, default='brief … -
how to use csrf token with django, react and axios and nginx
It been a few hours that i am getting the following errors while doing a post request to the backend from react frontend Access to XMLHttpRequest at 'https ://api.foo.com/api/create/' from origin 'https ://www.foo.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. My full stack app was working correctly, react front end, django backend, infrastructure made of s3 for react, both hosted on aws cloudfront using terraform until i tried to implement the csrf token below i created the following config react axios.defaults.xsrfHeaderName = "X-CSRFToken"; axios.defaults.xsrfCookieName = 'csrftoken'; axios.defaults.withCredentials = true const Create = () => { const [fields, handleFieldChange] = FormFields({ name: "", }); const options = { headers: { 'Content-Type': 'application/json', } }; const handleSubmit = (e) => { e.preventDefault(); axios.post("https ://api.foo.com/create/", fields, options) .then(response => { ... django settings.py CORS_ORIGIN_ALLOW_ALL = False CORS_ALLOW_CREDENTIALS = True CSRF_COOKIE_NAME = "csrftoken" CORS_ALLOW_METHODS = [ 'DELETE', 'GET', 'OPTIONS', 'PATCH', 'POST', 'PUT', ] CORS_ALLOW_HEADERS = [ 'accept', 'accept-encoding', 'authorization', 'content-type', 'dnt', 'origin', 'user-agent', 'x-csrftoken', 'x-requested-with', 'Access-Control-Allow-Origin', ] nginx ... location / { add_header 'Access-Control-Allow-Origin' 'https ://www.foo.com'; add_header 'Access-Control-Allow-Credentials' 'true'; add_header 'Access-Control-Allow-Methods' 'GET,POST,OPTIONS,PUT,DELETE,PATCH'; add_header 'Access-Control-Allow-Headers' 'Authorization,Content-Type,Accept,Origin,User-Agent,DNT,Cache-Control,X-Mx-ReqToken,Keep-Alive,X-Requested-With,If-Modified-Since,X-CSRFToken'; ... } Any help would be much appreciated, thanks -
Unable to ssh into aws EC2 instance
I have a django application running on EC2. I was able to ssh into the server instance. However, just before running certbot to obtain ssl certificate, I ran the command sudo ufw enable. That command prompted an alert that running it might alter ssh command (or something of that nature), but I ignored the warning and proceeded to enable ufw. After obtaining the ssl certificate I logged out of the server. When I tried to connect to the server subsequently, I keep getting the error ssh: connect to host ec2-xxx-xxx-xxx.us-east-2.compute.amazonaws.com port 22: Connection timed out I have spent several hours trying to fix the error but it persists. Why am I unable to connect to my ec2 instance after running sudo ufw enable.Though I'm not very sure, does using let's encrypt certbot to obtaining ssl certificate alter certain configurations in the server? I'm somewhat confused about the whole process. (the major commands I ran to obtain the ssl certificate are: sudo apt install python3-certbot-nginx and sudo certbot --nginx -d your_domain) -
i18next doesn't translate when I run "npm run build", React in frontend, Django backend
I am making a project using React on front-end and Django on back-end.. Front-end and back-end are separated. My issue occurs only when I "npm run build" and when I run python local server to view my website I can see my front-end and I managed to connect it to backend... there is no error.. but my translation doesn't work.. ONLY in this occasion When I "npm start" on front-end it works perfectly.. Here is my i18n.js file.. import { initReactI18next } from 'react-i18next'; import LanguageDetector from 'i18next-browser-languagedetector'; import HttpApi from 'i18next-http-backend'; import i18next from "i18next"; i18next .use(HttpApi) .use(LanguageDetector) .use(initReactI18next) .init({ supportedLngs: ['en', 'rs'], fallbackLng: 'en', debug: false, // Options for language detector detection: { order: ['cookie', 'htmlTag'], caches: ['cookie'], }, react: {useSuspense: false}, backend: { loadPath: '/assets/locals/{{lng}}/translation.json', }, }) export default i18n;``` Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). September 30, 2021 - 02:08:28 Django version 3.2.7, using settings 'backend.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. [30/Sep/2021 02:08:31] "GET / HTTP/1.1" 200 2513 [30/Sep/2021 02:08:31] "GET /static/js/main.4a38a3d9.chunk.js HTTP/1.1" 200 83939 [30/Sep/2021 02:08:31] "GET /static/css/2.3c7a9eae.chunk.css HTTP/1.1" 200 39104 [30/Sep/2021 02:08:31] "GET /static/js/2.c8bb41dc.chunk.js HTTP/1.1" 200 457027 [30/Sep/2021 02:08:31] … -
django python project is not using the specified template files
I know this is something dumb, but I'm a new programmer and I've been smacking my head against it for 2 hours and you will likely see it in 2 seconds so... View AllEncountersListView which has declared template_name = 'encounter_list_all.html' is using instead 'encounter_list.html'. I know the view is being called since it prints to terminal as expected. Thanks for your time. views.py: class AllEncountersListView(generic.ListView): model = Encounter paginate_by = 20 template_name = 'encounters_list_all.html' def get_queryset(self): print('in allEncounterListView') #to prove the correct view is being called return Encounter.objects.filter(user=self.request.user).order_by('-encounter_date') urls.py: urlpatterns = [ path('',views.index, name='index'), path('openencounter/', views.open_encounter, name='openencounter'), path('myencounters/', views.EncountersByUserListView.as_view(), name='my-encounters'), path('allencounters/', views.AllEncountersListView.as_view(), name='all-encounters'), path('encounter/<int:pk>', views.EncounterDetailView.as_view(), name = 'encounter-detail'), path('todaysencounters/', views.TodaysEncountersListView.as_view(), name='todays-encounters'), path('logout/', views.logout_view, name='logout'), path('export/', views.export_data_view, name = 'export'), ] file tree: ── Aents4 │ ├── __init__.py │ ├── __pycache__ │ ├── asgi.py │ ├── settings.py │ ├── templates │ │ ├── registration │ │ │ └── login.html │ │ └── temp │ ├── urls.py │ └── wsgi.py ├── db.sqlite3 ├── encounters │ ├── __init__.py │ ├── __pycache__ │ ├── admin.py │ ├── apps.py │ ├── forms.py │ ├── migrations │ │ ├── 0001_initial.py │ │ ├── 0002_auto_20210926_1548.py │ │ ├── 0003_alter_encounter_encounter_date.py │ │ ├── 0004_auto_20210927_1704.py │ │ ├── 0005_animal_max_daily.py … -
Error on PostgreSQL: Line number: 1 - value too long for type character varying(10)
I'm able to do a bulk upload via django's ImportExportModelAdmin without a problem on my localhost and on the staging application. But when I try it on prod, it displays an error. One thing to note the key difference is that I am using SQLite for my local and staging sites. But prod uses Amazon RDS PostgreSQL database. I haven't encountered this problem since, and I don't know where to start looking. Here is the traceback: Traceback (most recent call last): File "/home/ubuntu/env/lib/python3.6/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.StringDataRightTruncation: value too long for type character varying(10) The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/ubuntu/env/lib/python3.6/site-packages/import_export/resources.py", line 668, in import_row self.save_instance(instance, using_transactions, dry_run) File "/home/ubuntu/env/lib/python3.6/site-packages/import_export/resources.py", line 446, in save_instance instance.save() File "/home/ubuntu/env/lib/python3.6/site-packages/django/db/models/base.py", line 727, in save force_update=force_update, update_fields=update_fields) File "/home/ubuntu/env/lib/python3.6/site-packages/django/db/models/base.py", line 765, in save_base force_update, using, update_fields, File "/home/ubuntu/env/lib/python3.6/site-packages/django/db/models/base.py", line 868, in _save_table results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw) File "/home/ubuntu/env/lib/python3.6/site-packages/django/db/models/base.py", line 908, in _do_insert using=using, raw=raw, File "/home/ubuntu/env/lib/python3.6/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/ubuntu/env/lib/python3.6/site-packages/django/db/models/query.py", line 1270, in _insert return query.get_compiler(using=using).execute_sql(returning_fields) File "/home/ubuntu/env/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1416, in execute_sql cursor.execute(sql, params) File "/home/ubuntu/env/lib/python3.6/site-packages/django/db/backends/utils.py", line 66, in execute … -
"GET /static/css/bootstrap.min.css.map HTTP/1.1" 404 1834
I'm creating django site, I have some template and for some reason I'm getting this in django terminal. [29/Sep/2021 23:36:46] "GET /static/css/bootstrap.min.css.map HTTP/1.1" 404 1834 This is my html code <!-- Core Stylesheet --> <link href="{% static 'style.css' %}" rel="stylesheet"> <!-- Responsive CSS --> <link href="{% static 'css/responsive.css' %}" rel="stylesheet"> Tried to add here, <link href="{% static 'css/bootstrap.min.css.map' %}" rel="stylesheet"> but not working. Still same. This style.css, is doing this. @import url('https://fonts.googleapis.com/css?family=Roboto:400,500,700,900'); @import 'css/bootstrap.min.css'; @import 'css/owl.carousel.min.css'; @import 'css/animate.css'; @import 'css/magnific-popup.css'; @import 'css/font-awesome.min.css'; I only get error for first one, and I'm having a problem with my site style, some functions are not working. But I'm getting, with .map extention. What I need to do? -
Django admin select dropdown
I have a field in my model called day. I want in the admin area to have a pre populate dropdown for this field instead of the text input. I have search and cant find a solution. <select name="day" id="day"> <option value="Monday">Monday</option> <option value="Tuesday">Tuesday</option> <option value="Wednesday">Wednesday</option> <option value="Thursday">Thursday</option> </select> Modle: class Timetable(models.Model): gym_class = models.ForeignKey('GymClass', on_delete=models.CASCADE) start_date = models.DateField() end_date = models.DateField() day = models.CharField(max_length=12) time_slot = models.CharField(max_length=12) trainer = models.ForeignKey('Trainer', on_delete=models.CASCADE) def __str__(self): return self.gym_class.name admin.py: from django.contrib import admin from .models import GymClass, Category, Trainer, Timetable admin.site.register(GymClass) admin.site.register(Category) admin.site.register(Trainer) admin.site.register(Timetable) -
Trying to COPY adjacent folder into Docker image but copies the entire folder over
I have a directory structure like the following: project-root/ api/ docker/ Dockerfile ... src/ auth/ contact/ settings/ asgi.py settings.py urls.py wsgi.py manage.py client/ docker/ Dockerfile nginx.conf src/ App.js index.js In my API Dockerfile I'm trying to just copy src in to /app. However, I keep getting the entire api directory. What I expect to see is: app/ auth/ contact/ settings/ asgi.py settings.py urls.py wsgi.py manage.py This stage is the only one where src is copied over. The python-base and builder-base are either env vars or application dependencies. FROM python-base as production COPY --from=builder-base $VENV_PATH $VENV_PATH RUN chmod +x . /opt/pysetup/.venv/bin/activate COPY ../src /app WORKDIR /app CMD ["gunicorn", "-b", ":5000", "--log-level", "info", "config.wsgi:application", "-t", "150"] I've tried COPY ../src /app, COPY ./src /app, COPY src /app. How should I copy over just the src to app in this project structure? -
Need help iterating through each row in SQLite DB to render to html template
I'm using the Django framework with SQLite DB. I'm using SQL queries in my views.py and connecting that data to render on the frontend in my dashboard.html template. I'm having trouble iterating through each row in my database table 'scrapeddata'. When I view the dashboard, the data being rendered is all bunched up together in one div. I'm hoping to get each row in the database to render in one div each. I tried placing a for loop in my views.py but when I do that, I only get one row from the database rendered on dashboard.html. Any help is appreciated, thank you. views.py: def dashboard(request): connection = sqlite3.connect('db.sqlite3') cursor = connection.cursor() col1 = '''SELECT companyname FROM scrapeddata ORDER BY companyname ASC''' cursor.execute(col1) companyname = cursor.fetchall() col2 = '''SELECT name FROM scrapeddata''' cursor.execute(col2) name = cursor.fetchall() col3 = '''SELECT portfolio FROM scrapeddata''' cursor.execute(col3) portfolio = cursor.fetchall() people_data = [] data = { 'companyname': companyname, 'name': name, 'portfolio': portfolio } people_data.append(data) connection.close() if request.user.is_authenticated: return render(request, 'dashboard.html', {'people_data':people_data}) else : return redirect('/login') dashboard.html: Here's the for loop in the template. {% for data in people_data %} <div> <p>{{ data.companyname }}</p> <p>{{ data.name }}</p> <p>{{ data.portfolio }}</p> </div> {% endfor %} -
Django passing a variable through the path, causing path repetitions. how to get out of that loop?
I know this is an armature question but here goes. I have a url path as follows: path('projects/<s>', PL.projects), and i pass a string from the html template by putting it into an herf tag like so projects/some_string. this works once but then the base url changes to <ip>/projects/some_string. so when i try to excite the path to pass a string in that domain then I get an error as the url is now <ip>/projects/projects/some_string. how do i set it up so that i can pass as many strings as possible as many times as possible without having to clean my url in the browser everytime. Thanks for the help. -
Get cumulative running sum with group by in django orm
I have a table of two (relevant) columns. table: Transaction columns: transaction_date, amount I would like to get the cumulative amount for each month. So, for each month, get the sum of transactions from the beginning to that point in time. In PostgreSQL I would do something like this: SELECT date_trunc('month', transaction_date::date) AS formatted_transaction_date, SUM(SUM(amount)) OVER (ORDER BY date_trunc('month', transaction_date::date) ROWS UNBOUNDED PRECEDING) AS cumulative_transaction_amount FROM transaction GROUP BY date_trunc('month', transaction_date::date); I am trying to do the same in Django Orm. The closest I have gotten is this: Transaction.objects.values( formatted_transaction_date=TruncMonth('transaction_date') ).annotate( cumulative_transaction_amount=Window( expression=Sum('amount'), order_by=TruncMonth('transaction_date').asc(), frame=RowRange(start=None, end=0), ), ) This however throws an error: django.db.utils.ProgrammingError: column "transaction.amount" must appear in the GROUP BY clause or be used in an aggregate function I understand that the Django query I am executing is not identical to the PostgreSQL query. The PostgreSQL query runs SUM(SUM(amount)), while the Django query translates simply to SUM(amount). However, I was unable to find the syntax of Django to achieve same result. What am I doing wrong? -
One database with multiple django projects
I have two django projects connecting to same database. One of them is using authentication with custom user model and is working fine. Now i have to secure second project and use user authentication. It will be more or less similar to what we are using in first project. I tried creating models in second project but i think it is conflicting with already existing django tables. My question is how can we have two separate projects, each having their own django tables (auth and other). Till now i have tried and i am getting following error ValueError: The field admin.LogEntry.user was declared with a lazy reference to 'app.customuser', but app 'app' doesn't provide model 'customuser'. -
Django Annotate - get list of numbers in annotate
This models djago implements annotate with ArrayAgg, just in excecuted queryset view error Unable to get repr for <class 'project.model.auditoria.AuditoriaQuerySet'>. Help me please. this is query: modelA.objects.filter(field_a_id__in=list_elements,field_b_id=n).annotate(arrar_list_with_annotate=ArrayAgg(list(ModelB.objects.filter(ModelB.field_a = Cast('modelA.field_a', IntegerField()), modelA.field_c = int(nn)).values_list('ModelB.field_a', flat=True)))).values('create','view','modified','delete','arrar_list_with_annotate') -
Add delete raw button to table from database Django
I have a form on the page that adds data to the database and displays it in a table I need to add a button that will delete a specific row by id from the database index.html <tbody> {% for expense_item in expense_items %} <tr> <td>{{ expense_item.username}}</td> <td>{{ expense_item.expense_name }}</td> <td>{{ expense_item.category }}</td> <td>{{ expense_item.cost }}zł</td> <td>{{ expense_item.date_added}}</td> <td>BUTTON HERE</td> </tr> {% endfor %} </tbody> Models.py class ExpenseInfo(models.Model): username = models.CharField(max_length=255, default='NoName') expense_name = models.CharField(max_length=20) category = models.CharField(max_length=20) cost = models.FloatField() budget_id = models.CharField(default='0123456789', max_length=10) date_added = models.DateField() user_expense = models.CharField(max_length=20) Views.py def add_item(request): budget_id = request.user.last_name name = request.POST['expense_name'] category = request.POST['category'] expense_cost = request.POST['cost'] expense_date = request.POST['expense_date'] try: ExpenseInfo.objects.create(username=request.user, expense_name=name, category=category, cost=expense_cost, date_added=expense_date, user_expense=budget_id) except ValueError or TypeError: print('No data.') return HttpResponseRedirect('app')