Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - fresh database and no such table
I'm using my complex jobs app in production and it works fine, with sqlite database. I'm trying to create new database from scratch and I cannot do that nor using migrations nor trying to make them once again: When I'm trying to reuse my migrations: rm db.sqlite3 python manage.py migrate Traceback (most recent call last): File "/backend/server/manage.py", line 22, in <module> main() File "/backend/server/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/backend/env/lib/python3.10/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/backend/env/lib/python3.10/site-packages/django/core/management/__init__.py", line 377, in execute django.setup() File "/backend/env/lib/python3.10/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/backend/env/lib/python3.10/site-packages/django/apps/registry.py", line 122, in populate app_config.ready() File "/backend/env/lib/python3.10/site-packages/django/contrib/admin/apps.py", line 24, in ready self.module.autodiscover() File "/backend/env/lib/python3.10/site-packages/django/contrib/admin/__init__.py", line 24, in autodiscover autodiscover_modules('admin', register_to=site) File "/backend/env/lib/python3.10/site-packages/django/utils/module_loading.py", line 47, in autodiscover_modules import_module('%s.%s' % (app_config.name, module_to_search)) File "/usr/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "/backend/server/jobs/admin.py", line 57, in <module> class TagCategoryDefaultImportanceAdmin(admin.TabularInline): File "/backend/server/jobs/admin.py", line 59, in TagCategoryDefaultImportanceAdmin extra = len(Role.objects.all()) File "/backend/env/lib/python3.10/site-packages/django/db/models/query.py", line 269, in __len__ self._fetch_all() File "/backend/env/lib/python3.10/site-packages/django/db/models/query.py", … -
How should the data of a collection API be?
I'm coding a BlogApi application with Django and Django Rest Framework. So I have a post model that contains the data that a post of the blog should have and When I was making some serializers and views for the endpoints, I faced a question: Because the data of a single post is long, so should I make the posts data shorter in the list (or collection) endpoints or keep them how they are? In general I want to know that should the data of an element in collection APIs be brief? -
Establish MySQL connection on Elastic Beanstalk for django application
I have django app running on Elastic Beanstalk but facing difficulty in database connectivity. For some reasons the database is hosted on EC2 instance and currently can not move it to the RDS, So my concern is can we connect the database hosted on some EC2 instance to the Elastic Beanstalk application. And is it possible to connect database hosted on EC2 which is not in the same region as of Elastic Beanstalk. -
raise FieldError("Cannot resolve keyword '%s' into field. " django.core.exceptions.FieldError: Cannot resolve keyword
Hey guys I can't populate my database with dummy data.The scale of the error I got is: (raise FieldError("Cannot resolve keyword '%s' into field. " django.core.exceptions.FieldError: Cannot resolve keyword 'Topic' into field. Choi ces are: accessrecord, date, id, name, topic_name, topic_name_id, url Below is the codes for generating dummy data using Faker import os os.environ.setdefault('DJANGO_SETTINGS_MODULE','first_project.settings') import django django.setup() # faker pop script import random from first_app.models import AccessRecord,Webpage,Topic from faker import Faker fakegen = Faker() topics = ['Search', 'Social', 'Marketplace', 'News', 'Games', 'Music'] def add_topic(): t = Topic.objects.get_or_create(top_name=random.choice(topics))[0] t.save() return t def populate(N=5): for entry in range(N): # iget the topic for the entry top = add_topic() # create fake data for that entry fake_url = fakegen.url() fake_date = fakegen.date() fake_name = fakegen.company() # create the new Webpage entry webpg = Webpage.objects.get_or_create(Topic=top,url=fake_url,name=fake_name)[0] # create fake access record for Webpage acc_rec = AccessRecord.objects.get_or_create(name=webpg,date=fake_date)[0] if __name__=='__main__': print("populating script") populate(20) print("populating complete!") -
Passing Stripe Checkout ID to Django URL
The success page, which contains the download link to download a file after completing the purchase should be accessible only after having done the payment. The idea is to pass the {CHECKOUT_SESSION_ID} to the success url. Only if the correct url .../success/?session_id={CHECKOUT_SESSION_ID} is inserted the page is accessible. How can I pass the {CHECKOUT_SESSION_ID} to my url? Here is my views.py file: def success(request): return render(request, 'checkout/success.html') def index(request): # sendMail() try: checkout_session = stripe.checkout.Session.create( line_items = [ { 'price': 'price_1LUvcWKKYbcIekP0ZtUlCmAI', 'quantity': 1, }, ], mode = 'payment', success_url = 'http://127.0.0.1:8000/checkout/success' + '/?session_id={CHECKOUT_SESSION_ID}', cancel_url = 'http://127.0.0.1:8000/create/', ) except Exception as e: return str(e) return redirect(checkout_session.url, code=303) And this is my urls.py file: from django.urls import path from checkout.views import * app_name = 'checkout' urlpatterns = [ path('', index, name='index'), path('success/', success, name='success'), ] This is the html file which I copied from stripe. It is called by a "Pay Now" button. <!DOCTYPE html> <html> <head> <title>Buy cool new product</title> <script src="https://polyfill.io/v3/polyfill.min.js?version=3.52.1&features=fetch"></script> <script src="https://js.stripe.com/v3/"></script> </head> <body> <section> <div class="product"> <img src="https://i.imgur.com/EHyR2nP.png" alt="The cover of Stubborn Attachments" /> <div class="description"> <h3>Stubborn Attachments</h3> <h5>$20.00</h5> </div> </div> <form action="/create-checkout-session" method="POST"> <button type="submit" id="checkout-button">Checkout</button> </form> </section> </body> </html> -
Django form Data
Please I gotta a model I created with three fields input1,input2,total. So I generated a model form so that if I input the values of input 1 and input2 it will automatically multiply the the inputted values. Then on calling the save method it will save the inputted values and computed value to the database -
Response 403 Error When Trying to Login To Website Using Python Requests WRONG
I am trying to pull data from this website, but I am getting a Response 403 error when running session.post. Please see code below for reference. Any help would be appreciated. URL = 'https://www.pin-up.casino/' LOGIN_ROUTE = 'ajax/players/authorization' HEADERS = { 'HOST' : 'www.pin-up.casino', 'Accept-Encoding' : 'gzip, deflate, br', 'Content-Length':'1417', 'Origin':URL, 'Connection':'keep-alive', 'Referer':URL + 'slots', 'Cookie':'pinup-authToken=cboahm274uuuq6tebgv0; pinup-language=EN; _ga_73G7FP5X9S=GS1.1.1660101630.6.1.1660104282.50; _ga=GA1.2.230685168.1659939034; pinup-login1=; _gid=GA1.2.1822135906.1659939039; pinup-quizRewrite=1; __cf_bm=sJgdmyIQSs7.tAinAP8KeX53z7anDxilmvGRT23F1ow-1660104275-0-AWW0o9EH6zmL0aeyroPLM/4TMClgoUjMFabEaeDtao2IpLiOga8gUM46KHSXbPsuSMlfdF1kBARcPJm2B4eD4ZbM5YnenKfmfF7PQz/Sp+R395M2hgt47OL4A+BWBIapFw==; pinup-prevPage=/slots; pinup-hash1=', 'Sec-Fetch-Dest': 'empty', 'Sec-Fetch-Mode' :'no-cors', 'Sec-Fetch-Site': 'e-origin', 'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:103.0) Gecko/20100101 Firefox/103.0', 'TE': 'trailers', } login_payload = { 'email':'gamail', 'registDis' : "false", 'rulesEnable' : "true", 'password' :"password", 'timezone' :"5.5", 'screenSize' : "1706x899+(1708x960)", 'doNotTrack': "unspecified", 'page': "/slots", 'token' : "03ANYolquUWuPrFGd3q02tVCfla2iI9aTVMWEXNmUvqefYbRmB9rJYWZJzzHJIbFoiyjhgHmqmTGfM3ueqMmutoUIGdpKm26-ue1wSTowSVdFWkwmKQy59DhQ0po_7iiEC7VVBl48zG_M8q77dSXZ3FBkM6PryNozemsiH69Cga7OCj0vRqA3iDeZcSPU1g89Eqom7w2jiUgK0nUeJ9XO5ID1isfA4i1Z2LCM3Laf9dCSjc3V_s9OeJq28F-c__2kPZBJ0UzH37LEziVqjK2mhT32WD9q8rnYYYruFyoNDO4G0VoFMI54GFz-Yg-QlMzyU9j9jM-JYHaUcNAP580wBfV6m6OQSn1lmboxJGVTp-wSUMYVoO-taQ4sVSW-nqVUrYzw5x4WGLX6QGxA2ZQH8gElGcPObJFWAguGwMnFQjeEF0jFKLMAys8Ww4ZGvPtGiSNpvpVGRNbLhaec9JWGUy0wWwhlkNpTSOz__cByMgXvB5FS24e7E3B_WIc2ZD…e5hk0dw6cM8k828VBQxXd113qRNDEIQQcm_uvivdZREDNyNG2goDG8ZzvmhZxuS9aZ11ngRfJis74CbZXuH3uyRe5mr6ZRE8INvE2PKcT1XY5kPp9N7wqK13_ufkf8DsYQYbQouwQ4SbgWE3kEgLQmnzbutwAkdawIbTtI_GBzYhlURBkRpYtpLSPEkM2QN9tQxQ-W_PFl9i0woYMp4kg_mcxXSqKCzOIpHAtX9poTN2eezwxrDaOe3HyqFt_3aHQL8d1gHcKLcsi0axvJC4WN_xD8-Y4MyyaDiv1KZrSSSvQoqJD6WGKdiyeR7Alzhsm91WfW_m7sQ_WKfKNAgQxCrO9988mDQOZsWfK795r_tigq3msl88lmuiPZrDn5012QKrCsXQ3ZwHpfNWzOknO_G_HAZdW6VxdcMnj_xgP1lM-wStDqqJC4cozjErGL7vgvY_5kaYUwPF98Jzto_OHPDd89X9zu9qibqU2cgXNZcvy3NuCoRsGupvTkdC9Q", } s = requests.session() p = s.get(URL, headers=HEADERS) print(URL + LOGIN_ROUTE) login_req = s.post(URL + LOGIN_ROUTE, headers = HEADERS, data = login_payload) print(login_req.status_code)``` 403 returns what is wrong -
Why can't I change primary key in postgresql?
When I migrate the Django project model, I get the error: `there is no unique constraint matching given keys for referenced table "accounts_account"` my models is: class Account(AbstractBaseUser): email = models.EmailField(verbose_name='ایمیل', max_length=60, unique=True) username = models.CharField(verbose_name='نام کاربری', max_length=30, unique=True) phone_number = models.CharField(max_length=11, blank=True, null=True, default="") profile_image = models.ImageField(default="profile.jpg", upload_to='profile/images') # media/blog/images/img1.jpg ... USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] objects = MyAccountManager() def __str__(self): return self.email def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, app_label): return True in pgAdmin the Primary Key is not changeable primary Key in pgadmin4 -
Aggregated query django manytomany field
I'm trying to make chat application where for the screen where list of messages of users are visible like the Home Screen of WhatsApp or Telegram. For which I might need Chatroom ID, Name of sender. (mainly)' I have my models set like this models.py class ChatRoom(models.Model): name = models.CharField(max_length=50) last_message = models.CharField(max_length=1024, null=True) last_sent_user = models.ForeignKey(User, on_delete=models.PROTECT, null=True) def __str__(self): return self.name class Messages(models.Model): room = models.ForeignKey(ChatRoom, on_delete=models.PROTECT) user = models.ForeignKey(User, on_delete=models.PROTECT) content = models.CharField(max_length=1024) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.content class ChatRoomParticipants(models.Model): user = models.ManyToManyField(User, related_name='chatroom_users') room = models.ForeignKey(ChatRoom, on_delete=models.PROTECT) From where I'm querying in ChatRoomParticipants to see how many ChatRoom(s) is the user connected to. In ChatRoomParticipants user has relation with users who are connected to the that particular room. To show name and last message and the fetch ID of the ChatRoom on the mobile application I've written the following query. chatrooms = list(ChatRoomParticipants.objects.filter(user=user).values('id','room__id', 'room__name', 'room__last_message', 'room__last_sent_user', 'user__chatroom_users__user__username')) But this gives me repeated an unexpected output which I'm not able to make any sense of Below I'm showing which 2 users are related to which room Database values room - f4253fbd-90d1-471f-b541-80813b51d610-99ea24b1-2b8c-4006-8970-2b4f25ea0f40 relations to - udaykhalsa9 and udaykhalsa7 room - f4253fbd-90d1-471f-b541-80813b51d610-872952bb-6c34-4e50-b6fd-7053dfa583de relations to - udaykhalsa9 and … -
Set values in summernote text editor using javascript
I want to set values in summer note text editor using JavaScript/jQuery. I have tried this both but nothing works. document.getElementById('summernote').innerHTML = data.message; $('#summernote').summernote('code', data.message); Can anyone help me how I can add values in summer note using JavaScript/jQuery. -
How to query and update Django model JsonField?
Im working on a project where using Django JSONField to store json data for the instance. When i try to query the object as per official documentation, its not working as expected. Im uanble to query the object to update the key value inside the jsonfield. Please find the below details for your reference and help to to achelve the desired result. Model class PosOrder(models.Model): store = models.ForeignKey('store.Store', on_delete=models.CASCADE, null=True) order_number = models.CharField(max_length=30, null=True) customer_phone = models.CharField(max_length=100, null=True, blank=True) order_date = models.DateTimeField(auto_now_add=True) order_total = models.DecimalField(max_digits=10, decimal_places=2, default=0.00) order_discount = models.DecimalField(max_digits=10, decimal_places=2, default=0.00) order_tax = models.DecimalField(max_digits=10, decimal_places=2, default=0.00) coupon = models.ForeignKey('shoppingcoupon.ShoppingCoupon', on_delete=models.PROTECT, null=True, blank=True) order_grand_total = models.DecimalField(max_digits=10, decimal_places=2, default=0.00) payment_method = models.CharField(max_length=100, null=True, blank=True, choices=( ('cash', 'Cash'), ('card', 'Card'), ('online', 'Online'))) order_status = models.CharField(max_length=100, null=True, blank=True, choices=order_status) payment_status = models.CharField(max_length=100, null=True, blank=True, choices=payment_status) payment_id = models.CharField(max_length=100, null=True, blank=True) complete = models.BooleanField(default=False) order_data = models.JSONField(null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) created_by = models.ForeignKey('hrms.Employee', on_delete=models.CASCADE, null=True, blank=True) Jsonfield is like {"id": 408, "store": {"id": 1, "name": "Salt Lake"}, "order_number": "POS408", "customer_phone": "9877454577", "order_status": "processed", "payment_status": null , "payment_method": "cash", "created_at": "2022-08-09T11:38:37.207775+05:30", "created_by": {"id": 5, "code": "RMS003"}, "get_order_total": 39206, "get_order_tota l_discount_amount": 2232, "get_order_total_without_tax": 32730, "get_order_total_tax": 6476, "ordered_items": [{"id": 41, "item": {"id": 3, "product": {"id": 3, … -
How can translate the the whole screen language of application by only clicking single click on lang selection using python for flutter application
I have a Flutter app with 100 language choice on login page. I want when user choose one language suppose "Hindi" language the language of whole application screen should change. How can I change the language of whole application. -
How to add value in blank query set
I am running last 6 months of report which contains month, visits, fees and other fees as fields. When a month not having any visits its shows empty query set. how to pass a value to empty query set. I am getting result as below: <QuerySet [{'month': 7, 'visits': 19, 'fees1': Decimal('6380'), 'other_fees': Decimal('1730')}]> <QuerySet [{'month': 6, 'visits': 6, 'fees1': Decimal('3201'), 'other_fees': Decimal('851')}]> <QuerySet [{'month': 5, 'visits': 6, 'fees1': Decimal('900'), 'other_fees': Decimal('1685')}]> <QuerySet []> <QuerySet [{'month': 3, 'visits': 2, 'fees1': Decimal('455'), 'other_fees': Decimal('605')}]> <QuerySet [{'month': 2, 'visits': 2, 'fees1': Decimal('430'), 'other_fees': Decimal('504')}]> month 4 is not having any visit and fees since, the query set being empty. instead of empty. I want to set value of 0 for the fields. -
Error Deployment of Web Application using Django and Heroku
-----> Building on the Heroku-20 stack -----> Using buildpack: heroku/python -----> App not compatible with buildpack: https://buildpack-registry.s3.amazonaws.com/buildpacks/heroku/python.tgz More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure ! Push failed -
How to add 'django.contrib.auth' app in django
I deployed Django project using cloud code from pycharm. but in this sample template, there were not the code in installed_app basic apps like these 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', there was only 'django.contrib.staticfiles' apps. Also the default middleweres were not completely installed INSTALLED_APPS = [ 'django.contrib.staticfiles', 'helloapp', ] MIDDLEWARE = [ 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] So, is there any way to use default apps to make login page.? -
How to Configure Celery and Celery Beat with Django deployed on Elastic Beanstalk Amazon Linux 2
Hi I'm new to celery, I was wondering if some can help me with my question. In our Django web app, there are some background tasks that we want to run every midnight. With this, I tried celery with celery beat. I was able to successfully implement background task scheduler with celery beat and worker with Redis as Celery broker following the tutorial on: https://docs.celeryq.dev/en/stable/django/first-steps-with-django.html#using-celery-with-django https://docs.celeryq.dev/en/latest/userguide/periodic-tasks.html The feature is working locally by running the servers, scheduler and workers accordingly on separate terminals. Django Server `python manage.py runserver` Redis Server `redis-server` Celery Worker `celery -A django_project.celery beat -l info` Celery Beat Scheduler `celery -A django_project worker -l info` My question is how do I configure this for deployment in Elastic Beanstalk? What is the correct way to set this up properly with Elasticache as the Redis server? Current Stack: Django 3.1 deployed on AWS Elastic Beanstalk Python 3.8 running on 64bit Amazon Linux 2/3.3.9 with ElastiCache endpoint redis==4.3.4 # https://pypi.org/project/redis/ celery==5.2.7 # https://pypi.org/project/celery/ Any help is much appreciated! -
Django query: FOR EACH month AND name SUM values
What I need: for each month, I need to get the total sales (SUM) from John and Mary. There are other people in the database, but I only need info from both of them. [ ["19-Nov", "John", 511.97], ["19-Nov", "Mary", 0], ["19-Dec", "John", 568.21], ["19-Dec", "Mary", 1542.08], ["20-Jan", "John", 621.20], ["20-Jan", "Mary", 401.06], ["20-Feb", "John", 621.39], ["20-Feb", "Mary", 0], ["20-Mar", "John", 0], ["20-Mar", "Mary", 871.14], ["20-Apr", "John", 604.25], ["20-Apr", "Mary", 653.34], ["20-May", "John", 584.94], ["20-May", "Mary", 1218.43], ] The date must be formatted in this "Year-Month" type in order (oldest to newest ones). The total sales, even if it's zero, must be printed. My Django model: class Sellers(models.Model): date = models.DateField() name = models.CharField(max_length=300) value = models.DecimalField(max_digits=19, decimal_places=2) Is it possible to create just one Django query to retrieve data in this format? Tks! -
How to implement dropdown search bar in Django?
I am thinking of a way how to implement dropdown search bar on my application, this is just the simplest form of it, given: models.py CATEGORY = ( ('Hard Disk Drive', 'Hard Disk Drive'), ('Solid State Drive', 'Solid State Drive'), ('Graphics Card', 'Graphics Card'), ('Laptop', 'Laptop'), ('RAM', 'RAM'), ('Charger', 'Charger'), ('UPS', 'UPS'), ('Mouse', 'Mouse'), ('Keyboard', 'Keyboard'), ('Motherboard', 'Motherboard'), ('Monitor', 'Monitor'), ('Power Supply', 'Power Supply'), ('Router', 'Router'), ('AVR', 'AVR'), ('Tablet', 'Tablet'), ('System Unit', 'System Unit'), ('Audio Devices', 'Audio Devices'), ('CPU', 'CPU'), ('Others', 'Others'), ) class Product(models.Model): model_name = models.CharField(max_length=100, null=True, blank=True) asset_type = models.CharField(max_length=20, choices=CATEGORY, blank=True) forms.py class ProductForm(forms.ModelForm): class Meta: model = Product fields = ['model_name', 'asset_type'] views.py def product(request): items = Product.objects.all() if request.method == 'POST': form = ProductForm(request.POST, request.FILES) if form.is_valid(): form.save() else: form = ProductForm() context = { 'items': items, } return render(request, 'products.html', context) products.html <div class="container"> <div class="row my-1"> <h4>Enroll a product:</h4> <hr> </div> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ form|crispy }} <input class="btn btn-success btn-block" type="submit" value="Add Product"> <button type="button" class="btn btn-danger btn-block">Close</button> </form> </div> We all know that the result of the form (in HTML) when showing the categories of the model Product(asset_type) is a dropdown field with no search bar on … -
With Django, connecting a User to a completed Form?
right now, users can view all forms that are completed by any user, even when they are logged in and all forms get posted onto the same html page. I want users to only be able to view their own forms they completed when logged into their account. Any directions would be helpful. I understand functions more than classes in views, an Ideal solution would use functions. Thank you sooo much for any advice as this is my first Django I am trying on my own without strictly following a video or class. models.py from django.db import models from django.contrib.auth.models import User from django.forms import ModelForm from django import forms class Step1_Model(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True) title = "STEP 1: Safety during a violent incident" box1 = models.CharField(max_length=100, null=True) box2 = models.CharField(max_length=100, null=True) box3 = models.CharField(max_length=100, null=True) box4 = models.CharField(max_length=100, null=True) box5 = models.CharField(max_length=100, null=True) box6 = models.CharField(max_length=100, null=True) def __str__(self): return self.title forms.py from django import forms from .models import Step1_Model class Step1_Form(forms.ModelForm): box1 = forms.CharField() class Meta: model = Step1_Model #which model we want to use as a model for our model form fields= ("box1","box2","box3", "box4", "box5", "box6") views.py from django.shortcuts import render, redirect from django.contrib import … -
Prevent admin url from being overridden Django
I have a urls file that looks like this, however I cannot access the admin page. Is there any way to specify that the admin URL should never be overridden? from django.contrib import admin from django.urls import path from latency import views urlpatterns = [ path("admin/", admin.site.urls), path("<str:chain>", views.regions), path("<str:chain>/<str:region>", views.chain), path("", views.index), ]``` -
Django ProgrammingError must appear in the GROUP BY clause or be used in an aggregate function using annotate func
Here is my model. class EnvAi(models.Model): dateandtime = models.CharField(db_column='DateAndTime', max_length=50, blank=True, null=True) # Field name made lowercase. tagname = models.CharField(db_column='TagName', max_length=50, blank=True, null=True) # Field name made lowercase. datavalue = models.CharField(db_column='DataValue', max_length=50, blank=True, null=True) # Field name made lowercase. dateandtime sample is "2022-08-10 10:10:20" dateandtime field is charField and i have to slice date and time. # views.py queryset = EnvAi.objects.values('datavalue', 'tagname').annotate(slicedate=Substr('dateandtime', 1, 10)) # slicedate => "2022-08-10" # Error Code queryset = queryset.values('tagname', 'slicedate').annotate(max_value=Max('datavalue')) after create 'slicedate' variable, I want to get Max value each tagname and slicedate. but i get error ProgrammingError: column "Env_AI.DateAndTime" must appear in the GROUP BY clause or be used in an aggregate function I tried using raw sql in the database using query, but there was no problem. How can i solve this problem? -
Why aren't my images showing up after following Django's documentation on static files?
I'm having some trouble displaying images in a website I'm building. I am following the instructions in the Django static files documentation. To wit, I have: Verified that my settings.py file contains STATIC_URL = 'static/' Added the equivalent of the following code to my template: {% load static %} <img src="{% static 'my_app/example.jpg' %}" alt="My image"> Stored my images in `my_app/static/my_app/ I get no error when I navigate to the relevant page. Just an empty div where the image should be. It seems like in the past, this problem has been solved by using render() (example). However, I'm using Django 4.x, as well the render() function. Why aren't my images showing up? -
How to convert this XML to a table in Django?
I am brand new to coding, but have been given a task to convert some XML files to a table and present them in an existing Django environment. I honestly don't know where to begin, especially since the XML I'm trying to convert is a bit strange. Below is an example snippet. You'll see the information is stored as element attributes rather than content: <?xml version="1.0" encoding="UTF-8"?> <object_list> <object no_step="0" id="First Object" cd_type="SYSTEM" cd_outcome="" dt_create="2022-03-04 15:31:39.965" tx_flow="FLOW_1" tx_creditproduct="Consumer Product"> </object> <object no_step="1" id="Second Object" cd_type="Ruleset" cd_outcome="Commence" dt_create="2022-03-04 15:31:39.981" tx_flow="FLOW_1" tx_creditproduct="Consumer Product"> </object> <object no_step="2" id="Third Object" cd_type="AppWriter" cd_outcome="Commence" dt_create="2022-03-04 15:31:39.981" tx_flow="FLOW_1" tx_creditproduct="Consumer Product"> </object> <object no_step="3" id="Forth Object" cd_type="Ruleset" cd_outcome="Commence" dt_create="2022-03-04 15:31:39.997" tx_flow="FLOW_1" tx_creditproduct="Consumer Product"> </object> <object no_step="4" id="Fifth Object" cd_type="WebService" cd_outcome="Commence" dt_create="2022-03-04 15:31:39.997" tx_flow="FLOW_1" tx_creditproduct="Consumer Product"> </object> </object_list> What I need to convert this to is a table, like this: table example Can anyone point a beginner in the right direction for how to achieve this using Python / Django? Thank you in advance! -
Concatenate two parameters [duplicate]
I have a python function that is receiving two parameters. I want to combine these two parameters to create the reference to a field in the model/db. The first parameter is an object of the model. The second is a string that contains the field name. I want to combine them in order to reference the field name. This code, of course, does not work, but it should show what I'm trying to accomplish. x = image_reference(parent, 'name') def image_reference(parent, field_string): db_image = parent.+field_string The value of db_image I'm looking to achieve would be parent.name, which allows me to reference the field called name in the model. Thank you in advance. -
How do I name Django ManyToMany object relations in Django admin?
Is there a way to give the relations their name instead of calling them "object-n" like shown below? Here is the code for the two models in question: class jobTag(models.Model): Tag = models.CharField(max_length=15) def __str__(self): return self.Tag class job(models.Model): Company_name = models.CharField(max_length=200, null=True, blank= True) Position = models.CharField(max_length=200, null=False, blank=False) Type = models.ForeignKey(jobType, default=" ",verbose_name="Type", on_delete=models.SET_DEFAULT) Industry = models.ForeignKey(jobIndustry, default=" ", verbose_name="Industry", on_delete=models.SET_DEFAULT) Location = models.ForeignKey(jobLocation, default=" ", verbose_name="Location", on_delete=models.SET_DEFAULT) Role_description = tinymce_models.HTMLField(default="") Role_requirements = tinymce_models.HTMLField(default="") Role_duties = tinymce_models.HTMLField(default="") Special_benefits = tinymce_models.HTMLField(default="") Date_posted = models.DateTimeField(auto_now_add=True) tags = models.ManyToManyField('jobTag', related_name="job-tags+", blank=True) def time_posted(self): return humanize.naturaltime(self.Date_posted) def __str__(self): return self.Position class Meta: verbose_name_plural = "Jobs" Thanks in advance.