Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Pass JS variable to another JS and to django view
I have several cards with items. I added a counter to each card and a button 'Add to cart'. I want to pass the count of item into django view using ajax. But I dont know how to pass variable from counter to ajax function, for each card. The current version doesn't work correctly, cuz every time count = 1. var globalVariable; var buttonPlus = $(".qty-btn-plus"); var buttonMinus = $(".qty-btn-minus"); var incrementPlus = buttonPlus.click(function() { var $n = $(this) .parent(".col") .find(".input-qty"); $n.val(Number($n.val()) + 1); globalVariable = $(this).$n.val(); }); var incrementMinus = buttonMinus.click(function() { var $n = $(this) .parent(".col") .find(".input-qty"); var amount = Number($n.val()); 1 if (amount > 0) { $n.val(amount - 1); globalVariable = $(this).$n.val(); } }); $(document).ready(function() { $(".send-quantity").click(function() { var quantity = globalVariable; if (quantity === undefined) { quantity = 1; } var id = $(this).data("id"); $.ajax({ url: "{% url 'stripe_order:cart_add' %}", data: { 'id': id, 'quantity': quantity, }, }); }); }); My HTML: {% for item in items %} <div class="col"> <div class="card mb-4 rounded-4 shadow-sm"> <div class="card-header py-3"> <h3 class="my-0 fw-normal">{{ item.name }}</h3> </div> <div class="card-body"> <h4 class="card-title pricing-card-title ">${{ item.price }}</h4> <ul class="list-unstyled mt-3 mb-4"> <li>{{ item.description }}</li> </ul> <div class="row"> <div class="col"> <div class="col … -
Is it possible to obtain both the count and results of a query in a single MySQL query?
I'm currently working on optimizing a MySQL query, and I'm wondering if there's a way to retrieve both the count of the results and the actual result set in a single query. I'm aware that I can achieve this using separate queries, one for the count and one for fetching the results, but I'm curious if there's a more efficient way to accomplish this within a single query. -
Django DeserializationError: "string indices must be integers, not 'str'" when loading large JSON data into SQLite
I'm encountering a TypeError: string indices must be integers, not 'str' error while trying to load large JSON data into my Django application using the load data command. The data is stored in C:\Users\ambai\PyCharm Projects\Task1\app/fixtures\data.json. My models are defined in models.py. this is the models.py fields I created based on the raw json format data I used gemini.ai to generate these fields did not done it manually: from django.db import models # Create your models here. class Game(models.Model): team=models.CharField(max_length=50) team1=models.CharField(max_length=50) team_score=models.IntegerField() team1_score=models.IntegerField() box=models.URLField() box1=models.URLField() class Team(models.Model): game_set=models.ForeignKey(Game,on_delete=models.CASCADE,related_name='team_set') points=models.IntegerField() field_goals=models.IntegerField() field_goals_attempts=models.IntegerField() field_goals_percentage=models.FloatField() three_pointers_made=models.IntegerField() three_point_attempts= models.IntegerField() three_point_percentage=models.FloatField() free_throws_made= models.IntegerField() free_throw_attempts= models.IntegerField() free_throw_percentage=models.FloatField() offensive_rebounds= models.IntegerField() total_rebounds= models.IntegerField() assists= models.IntegerField() personal_fouls= models.IntegerField() steals= models.IntegerField() turnovers= models.IntegerField() blocks= models.IntegerField() class Field(models.Model): game_set = models.ForeignKey(Game, on_delete=models.CASCADE) author= models.CharField(max_length=100) body=models.TextField(max_length=100) created_at= models.DateTimeField(auto_now_add=True) the error it shows when I run the loaddata command is of Deserialization: python manage.py loaddata app/fixtures CommandError: No fixture named 'fixtures' found. (.venv) PS C:\Users\ambai\PycharmProjects\Task1> python manage.py loaddata app/fixtures/data.json Traceback (most recent call last): File "C:\Users\ambai\PycharmProjects\Task1\.venv\Lib\site-packages\django\core\serializers\json.py", line 70, in Deserializer yield from PythonDeserializer(objects, **options) File "C:\Users\ambai\PycharmProjects\Task1\.venv\Lib\site-packages\django\core\serializers\python.py", line 114, in Deserializer Model = _get_model(d["model"]) ~^^^^^^^^^ TypeError: string indices must be integers, not 'str' The above exception was the direct cause of the following exception: Traceback … -
KeyError in Django when using Huggingface API
i use Django and i want to use Huggingface API with it. The API sometimes return error to me saying: KeyError at /GenerativeImage2Text 0 34. if "generated_text" in output[0]: ^^^^^^^^ this is my view.py def GIT(request): output = None generated_text = None form = ImageForm() if request.method == 'POST': form = ImageForm(request.POST, request.FILES) if form.is_valid(): form.save() image_name = str(form.cleaned_data['Image']) imgloc = os.path.join( 'media', 'images', image_name) while True: output = query(imgloc) if "generated_text" in output[0]: generated_text = output[0].get('generated_text') break else: print(output[0]) else: print("This image is invalid") return render(request, "imagecaptioning.html", {"form": form, "output": generated_text}) i want to fix this problem and make sure that API always return no error such that. is the problem in my code or with the API ? thanks in advance -
Add more than one custom order to a bag session - Django e-commerce application
I am building a Django e-commerce application. I have implemented to ability to leave a custom order on the site and for users to be able to update the quantity, delete the custom order and checkout. I am now trying to refactor the code to allow more than one custom order to be placed in the users bag. What is currently happening is the second custom order is replacing the first custom order in the bag. context.py file if 'custom_order' in bag: custom_order_id = bag['custom_order'] custom_order = CustomOrder.objects.get(pk=custom_order_id) if 'quantity' in bag: total += bag['quantity'] * custom_order.price individual_total = bag['quantity'] * custom_order.price bag_items.append({ 'product_id': custom_order.product_id, 'custom_order_id': custom_order_id, 'category': custom_order.category, 'material': custom_order.material, 'individual_total': individual_total, 'quantity': bag['quantity'], 'product_name': custom_order.product_name, 'price': custom_order.price, }) else: total += custom_order.price bag_items.append({ 'product_id': custom_order.product_id, 'custom_order_id': custom_order_id, 'category': custom_order.category, 'material': custom_order.material, 'individual_total': custom_order.price, 'quantity': 1, 'product_name': custom_order.product_name, 'price': custom_order.price, }) my view where I am adding to the bag: def add_custom_order_to_bag(request, custom_order_id): """Add custom order to the shopping bag """ custom_order = CustomOrder.objects.get(pk=custom_order_id) bag = request.session.get('bag', {}) bag['custom_order'] = custom_order_id request.session['bag'] = bag return redirect(reverse('view_bag')) I tried adding a list into the view to handle the multiple custom orders, which seemed like the right way to go, but … -
Python requests returns 503 status code as response when sending a file through POST request
So I am using python requests to send a post request to another server (both servers are internal to the company). It worked some weeks ago, but I tried today and it has suddenly stopped working. I can use postman to send the same request and the server responds with 201. I can perform a get request from my python code using requests library. The problem ONLY occurs on post request from python code. Here's the piece: with open(filepath, "rb") as f: # f is a file-like object. data = {"name": experiment_id + ".zip", "content": f} #The CALCSCORE_URL is an env variable named CALCSCORE_BE set up in each environment. calcscore_url = f"{settings.CALCSCORE_URL}/api/hive/experiment/{experiment_id}/roi" response = request.post(calcscore_url, files=data) I tried different things, like sending the data in a separate 'files' and 'data' argument but its always the same error. The file is 5 MB in size. I don't think its that big? response.content shows response timed out. -
django view with redis cluster not working
I'm using AWS elasticache redis cluster. However, I'm unable to implement my current view to utilize the cluster. Here's my view: redis_conn = redis.Redis(host=settings.REDIS_HOST, port=settings.REDIS_PORT, db=0, decode_responses=True) def orders(request): logger.info(f"Accessing the orders view for user: {request.user.username}") # Fetch user-specific cached shipment data processed_shipments_display_str = redis_conn.get(f"processed_shipments_display_{request.user.id}") all_shipments_display = [] last_updated_at = "Not Available" if processed_shipments_display_str: cache_data = json.loads(processed_shipments_display_str) all_shipments_display = cache_data.get('shipments', []) last_updated_at = cache_data.get('timestamp', 'Not available') else: all_shipments_display = [] last_updated_at = 'Not available' return render(request, 'app/orders.html', { 'all_shipments': all_shipments_display, 'last_updated_at': last_updated_at }) Everytime I try to access the page it just loads and nothing ever happens. I'm unable to use redis-py-cluster (which worked initially) since my redis version is incompatible with channels-redis and this. I also tried using startup_nodes = [{"host": settings.REDIS_HOST, "port": settings.REDIS_PORT}] redis_conn = RedisCluster(startup_nodes=startup_nodes, decode_responses=True) but then I keep getting the error AttributeError at /app/orders/ 'dict' object has no attribute 'name' Here's my settings.py: REDIS_HOST = os.getenv('REDIS_HOST', 'clustercfg.rediscluster.m0rn9y.use1.cache.amazonaws.com') REDIS_PORT = os.getenv('REDIS_PORT', 6379) CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.pubsub.RedisPubSubChannelLayer", "CONFIG": { "hosts": [{ "address": "rediss://clustercfg.rediscluster.m0rn9y.use1.cache.amazonaws.com:6379", "ssl_cert_reqs": None, }] }, }, } CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "rediss://clustercfg.rediscluster.m0rn9y.use1.cache.amazonaws.com:6379", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", "SSL_CERT_REQS": None, } } } Any help is appreciated. Thanks. -
datefield not showing a default value
I tried using a DateField and show a default value, but it does not show on the page (but in the HTML): class foo(models.Model): date = models.DateField() class FooForm(ModelForm): class Meta: model = Foo fields = "__all__" widgets = {"date": DateInput(format=("%d-%m-%Y"), attrs={"class": "form-control", "value": timezone.now().strftime("%d-%m-%Y"), "type": "date"}),} this produces: <input type="date" name="date" value="29-02-2024" class="input" prod_date="input" required="" id="id_date"> which shows as: But not with the current date as placeholder. -
Django Admin: How to Override Add Form to Choose Existing Object Instead of Raising 'Already Exists' Error?
I am working with Django and using the Django admin panel for managing a model called Keyword. When adding a new instance of the Keyword model, I want to customize the behavior so that if the keyword already exists, the admin form should select the existing keyword instead of raising the 'Already Exists' error. When i try to add keyword that already exists it wont let me so i have to scroll thru hundreds of keywords to find the one i need like this I have attempted various approaches, including custom forms and overriding the save_model method in the admin class, but the issue persists. The current implementation still raises a "Keyword with this Name already exists" error. -
How to edit apps platform files on digital ocean?
I used nano editor on the app's console to access and edit my Django files but the thing is in the console the file is showing edited but my live site code isn’t updating. here are the images nano command console html file The actual web app file which wasn't updating I am expecting that the code I changed in the console will update on the digital ocean server. -
On click function is not working in script though models and views are ok and original template is working perfectly
In product_detail.html: {% extends 'partials/base.html'%} {%load static%} {% block content %} <style> /* Basic Styling */ html, body { height: 100%; width: 100%; margin: 0; font-family: 'Roboto', sans-serif; } .containerbox { max-width: 1200px; margin: 0 auto; padding: 15px; display: flex; } /* Columns */ .left-column { width: 65%; position: relative; } .right-column { width: 35%; margin-top: 60px; } /* Left Column */ .left-column img { width: 70%; position: absolute; left: 0; top: 0; opacity: 0; transition: all 0.3s ease; } .left-column img.active { opacity: 1; } /* Right Column */ /* Product Description */ .product-description { border-bottom: 1px solid #E1E8EE; margin-bottom: 20px; } .product-description span { font-size: 12px; color: #358ED7; letter-spacing: 1px; text-transform: uppercase; text-decoration: none; } .product-description h1 { font-weight: 300; font-size: 52px; color: #43484D; letter-spacing: -2px; } .product-description p { font-size: 16px; font-weight: 300; color: #86939E; line-height: 24px; } /* Product Configuration */ .product-color span, .cable-config span { font-size: 14px; font-weight: 400; color: #86939E; margin-bottom: 20px; display: inline-block; } /* Product Color */ .product-color { margin-bottom: 30px; } .color-choose div { display: inline-block; } .color-choose input[type="radio"] { display: none; } .color-choose input[type="radio"] + label span { display: inline-block; width: 40px; height: 40px; margin: -1px 4px 0 0; vertical-align: … -
why is this error coming after trying to deploy a django app on vercel?
After trying to deploy a django app on vercel, this error comes Running build in Washington, D.C., USA (East) – iad1 Cloning github.com/Anupam-Roy16/Web_project (Branch: main, Commit: 90df2f4) Cloning completed: 677.995ms Previous build cache not available Running "vercel build" Vercel CLI 33.5.3 WARN! Due to builds existing in your configuration file, the Build and Development Settings defined in your Project Settings will not apply. Learn More: https://vercel.link/unused-build-settings Installing required dependencies... Failed to run "pip3.9 install --disable-pip-version-check --target . --upgrade -r /vercel/path0/requirements.txt" Error: Command failed: pip3.9 install --disable-pip-version-check --target . --upgrade -r /vercel/path0/requirements.txt ERROR: Ignored the following versions that require a different python version: 5.0 Requires-Python >=3.10; 5.0.1 Requires-Python >=3.10; 5.0.2 Requires-Python >=3.10; 5.0a1 Requires-Python >=3.10; 5.0b1 Requires-Python >=3.10; 5.0rc1 Requires-Python >=3.10 ERROR: Could not find a version that satisfies the requirement Django==5.0.2 (from versions: 1.1.3, 1.1.4, 1.2, 1.2.1, 1.2.2, 1.2.3, 1.2.4, 1.2.5, 1.2.6, 1.2.7, 1.3, 1.3.1, 1.3.2, 1.3.3, 1.3.4, 1.3.5, 1.3.6, 1.3.7, 1.4, 1.4.1, 1.4.2, 1.4.3, 1.4.4, 1.4.5, 1.4.6, 1.4.7, 1.4.8, 1.4.9, 1.4.10, 1.4.11, 1.4.12, 1.4.13, 1.4.14, 1.4.15, 1.4.16, 1.4.17, 1.4.18, 1.4.19, 1.4.20, 1.4.21, 1.4.22, 1.5, 1.5.1, 1.5.2, 1.5.3, 1.5.4, 1.5.5, 1.5.6, 1.5.7, 1.5.8, 1.5.9, 1.5.10, 1.5.11, 1.5.12, 1.6, 1.6.1, 1.6.2, 1.6.3, 1.6.4, 1.6.5, 1.6.6, 1.6.7, 1.6.8, 1.6.9, 1.6.10, 1.6.11, 1.7, … -
How can I use get_or_create in TranslatableModel?
I am using dajngo-parler to make my site multi-language. But I have a problem when querying. For example, in this query, only ID is created and the rest of the fields are not stored in the database. MyModel.objects.language('en').get_or_create(title='test',description='test') But when I use this method, there is no problem. MyModel.objects.language('en').create(title='test',description='test') Is there another way to create data in multi-language models with parler?? -
"ORDER BY NOT ALLOWED IN SUBQUERIES OF COMPOUND STATEMENTS" in Django while using UNION function
I'm new to Django and want to use this snippet code in my project who use sqlite database: if "dashboard_filters_parent_checkbox" not in request.POST: all_task_id=tasks_no_assign.union(tasks_no_start).union(tasks_start).union(tasks_no_confirmed).union( tasks_confirmed).values_list('id',flat=True) all_task_parent_id=tasks_no_assign.union(tasks_no_start).union(tasks_start).union(tasks_no_confirmed).union(tasks_confirmed).values_list('task_parent__id',flat=True) #.union(sub_tasks_no_confirmed) all_task_parent_id = list(set(all_task_id) & set(all_task_parent_id)) tasks_no_assign=tasks_no_assign.exclude(Q(pk__in=all_task_parent_id)&~Q(pk__in=all_tasks_children_id)) tasks_no_start=tasks_no_start.exclude(Q(pk__in=all_task_parent_id)&~Q(pk__in=all_tasks_children_id)) tasks_start=tasks_start.exclude(Q(pk__in=all_task_parent_id)&~Q(pk__in=all_tasks_children_id)) tasks_no_confirmed=tasks_no_confirmed.exclude(Q(pk__in=all_task_parent_id)&~Q(pk__in=all_tasks_children_id)) tasks_confirmed=tasks_confirmed.exclude(Q(pk__in=all_task_parent_id)&~Q(pk__in=all_tasks_children_id)) but I get this error when I open the page that above lines are in that code: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/Dashboard/ Django Version: 5.0.2 Python Version: 3.12.2 Installed Applications: ['django.contrib.ad...] Installed Middleware: ['django.middleware....] Traceback (most recent call last): File "C:\...\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "C:\...\views\dashboard\dashboard.py", line 203, in Dashboard all_task_parent_id = list(set(all_task_id) & set(all_task_parent_id)) File "C:\...\Lib\site-packages\django\db\models\sql\compiler.py", line 1549, in execute_sql sql, params = self.as_sql() ^^^^^^^^^^^^^ File "C:\...\Lib\site-packages\django\db\models\sql\compiler.py", line 751, in as_sql result, params = self.get_combinator_sql( Exception Type: DatabaseError at /Dashboard/ Exception Value: ORDER BY not allowed in subqueries of compound statements. I search it and understand it's because "union" function and sqlite but don't now where is problem and didn't find any answer for fix it. what can I do and what's correct way? thanks in advance <3 -
Extra Square Brackets "[]" in Django Admin Login Page Rendering
please help me. I am using Django 5.0.2 and Python 3.12 with Apache 2.4 and mod_wsgi 5.0.0. When I run the development server, everything looks fine. However, when I run it on production over Apache, I encounter an issue where extra square brackets "[]" appear, as shown in the picture below: image1 : https://ibb.co/m6JXXDN This issue also appears in my forms: image2: https://ibb.co/ZV0Q3xN I have tried several solutions, but none have resolved the problem. Please help me. I checked the dependencies and the Apache configuration for static files. I also rechecked my forms and views. The app works perfectly on the local machine with the development server -
How to use cache system for large and dynamic data
I want to use a cache system for my django web application, I have been using django-cachepos for caching my data but now I have some issues like having big data for reports which includes a lot of filters and should be online when data upate . Now my response time is too long (like 12 13 s ) and I want some guides from you to implant a cache sytem or a cache strategy that can helps to improve my code cosider this that appliacation is going to be a large scale project and right now have 3 4 lead from all interner and cant stop being online Ps. I have this problem on some other endpoints with requests with lots of data I try to use redis functions to set and get data but I have no idea how to use it with filters and even cache response data -
how to open the poping window just bellow the burger logo in django
solve the JavaScript and CSS and html code with suitable reason of the code so that the Ui seems seamless and beautiful and attracting to interact to the user in the website. I am expecting the beautiful Ui of the window so that the Ui seems attracted and beautiful. -
Django JsonResponse returning 'Year and month parameters are required' despite parameters being present in request.GET
I am using 'fullcalendar' and I want to send the month and year to django view and fetch the total hours for each day in that month from this api: 'api/get_calendar_data/' to display the calendar properly. But then I am receiving an unexpected respond where it says it needs the parameters while there are present in the request. I will provide the code to and you will get what I am doing. dashboard.html: <div id="calendar"></div> <script src="{% static 'js/calendar.js' %}"></script> calendar.js: function updateCalendar(month, year) { console.log(year); console.log(month); $.ajax({ url: "/api/get_calendar_data/", // to my django view to fetch data method: "GET", data: { year: year, month: month }, // to django view to send month and year success: function (data) { // data = { '2024-02-01': 5, '2024-02-02': 7, ..} for (let date in data) { let hoursWorked = parseFloat(data[date]); let calendarDate = new Date(date); let formattedDate = calendarDate.toISOString().slice(0, 10); //to get the day number 2024-04-23 -> 23 let dayElement = calendarEl.querySelector( `[data-date="${formattedDate}"]` ); if (hoursWorked >= 7) { dayElement.style.backgroundColor = "#5cb85c"; //finished work } else { dayElement.style.backgroundColor = "#d9534f"; //not inished } } }, error: function (xhr, status, error) { console.error("Error fetching calendar data:", error); }, }); } //initialize the … -
Async Django MQTT Client cannot re-connect pg-pool after 24 hours
Let me tell you my structure and problem. I have sync and async containers on K8. These pods are running via this command in my docker-entrypoint.sh gunicorn myappname.wsgi:application --worker-class gevent --workers 3 --bind 0.0.0.0:8000. In the async ones, I run some MQTT Clients (paho.mqtt.client). This is my custom apps.py that runs clients asynchronously: import asyncio import importlib import sys from os import environ from django.apps import AppConfig, apps from django.db import connection from .server import MQTTConsumer # inherited from paho.mqtt.Client from .consumers import ResponseConsumer class CustomMqttConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'custom.mqtt' def ready(self): for _app in apps.app_configs.keys(): topic_patterns = [ ('$share/my-app/response', ResponseConsumer) ] connection.close() for _topic, _consumer in topic_patterns: asyncio.run(MQTTConsumer()(topic=_topic, consumer=_consumer)) Everything works perfectly until 24 hours passed after the first init of my consumers. After 24 hours, I get connection closed error for each MQTT request from my db (in this case pg-pool) BUT when I open a shell in my async container (docker exec -it <container_id> bash) and get in the django shell (python manage.py shell) I can use my models and filter my DB while my consumers throwing that error. I checked my pg-pool (show pool_processes) before and after restarting my async pods and saw that … -
Pydantic, Django Ninja "Day is out of range for month"
2024-02-29 14:04:15 pydantic.error_wrappers.ValidationError: 1 validation error for NinjaResponseSchema 2024-02-29 14:04:15 response 2024-02-29 14:04:15 day is out of range for month (type=value_error) I have fields "created_at" and "updated_at". Today my project crashed because of them. How can I update validators in schemas to skip those fields validation? I've tried multiple things but nothing helped me. My versions: django-ninja==0.22.0 pydantic==1.10.14 -
Based on two field input of a form need to generate choices for another field dynamically on Django
on _create_mywork_help.html ******************************* function generate_daily_time_list() { var start_time = document.getElementById("id_start_time").value; var interval = Number(document.getElementById("id_interval").value); var daily = document.getElementById("id_daily"); //document.getElementById("id_daily").value = document.getElementById("id_daily").defaultValue; document.getElementById("id_daily").innerHTML = ""; console.log(start_time); console.log(interval); console.log(daily); const stime = String(start_time).split(" "); const hm = stime[0].split(":"); console.log(hm[0]); console.log(hm[1]); var hr = Number(hm[0]); var mins = String(hm[1]); var pre = 0; while (hr > 0){ pre = hr; hr = hr - interval; } console.log(mins); console.log('Deba'); var i = pre; while (i < 24){ var option= document.createElement("option"); dtime = String(i).padStart(2, '0')+':'+mins; //dtime_v = 'x'+String(i).padStart(2, '0')+mins; console.log(dtime) i = i+interval; option.value= dtime; option.text= dtime; daily.add(option); } } class myworkAction(workflows.Action): start_time = forms.ChoiceField(label=_("Start Time"), required=False) interval = forms.CharField(label=_("Hourly"), required=False, initial=24, validators=[validate_scheduler_interval], widget=forms.TextInput( attrs={'placeholder': "Repeat interval must be in numbers only (Ex: 1 or 2)...", 'onkeyup': " $('#id_interval').val(document.getElementById('id_interval').value)", 'onchange': "generate_daily_time_list()"})) daily = forms.MultipleChoiceField(label=_("Daily"), required=False) class Meta: name = _("mywork") help_text_template = ("project/workloads/" "_create_mywork_help.html") def __init__(self, request, *args, **kwargs): super(myworkAction, self).__init__(request, *args, **kwargs) start_time_list = populate_time_list() self.fields['start_time'].choices = start_time_list I want to take input 12:15 PM start time and interval e.g. 2 It should generate choices for "daily" filed as e.g. like 14:15 , 16:15 and it is generating, but when i select and submitting it is giving error : Select a valid choice. 14:15 … -
Fly.io django and postgres deploy
I'm trying to deploy my django app in Fly.io with postgreSQL database, so I've followed de docs to attach my app with the postgres cluster with the main app. I’ve generated the DATABASE_URL like this: flyctl pg attach ac7-postgres Checking for existing attachments Registering attachment Creating database Creating user Postgres cluster ac7-postgres is now attached to ac7 The following secret was added to ac7: DATABASE_URL=postgres://ac7:@ac7-postgres.flycast:5432/ac7?sslmode=disable So I have this code in settings.py: os.environ['DATABASE_URL'] = 'postgres://ac7:<PASSWORD>@ac7-postgres.flycast:5432/ac7?sslmode=disable' DATABASES = { 'default': dj_database_url.config(default=os.getenv('DATABASE_URL')) } but when I try “py manage.py makemigrations” it shows: UnicodeDecodeError: ‘utf-8’ codec can’t decode byte 0xe3 in position 76: invalid continuation byte Can someone help me? Please -
How can display values of item selected in dropdownlist all items from db in template django
Please help to get Revision and Company of selected Project in dropdownlist in software.html template django, image with more detail in attached, Thanks! models.py ` class PROJ(models.Model): User=get_user_model() author = models.ForeignKey(User, on_delete=models.CASCADE) project_id=models.CharField(max_length=100, null=True, blank=True, db_index=True) Company=models.CharField(max_length=100, null=True, blank=True) Revision=models.CharField(max_length=100, null=True, blank=True)` urls.py urlpatterns = [ path('software/', views.software, name='software'), views.py ` def software(request): assert isinstance(request, HttpRequest) PROJS = PROJ.objects.filter(author=request.user) return render( request, 'app/software.html', { 'year':datetime.now().year, 'PROJS': PROJS, } )` software.html ` <label class="col-md-3 col-form-label">Project/Site:</label> <div class="col-md-9"> <select class="form-select" name="Select" id="Select"> {% for PROJ in PROJS %} <option value="{{ PROJ.id }}">{{ PROJ.project_id }}</option> {% endfor %} </select> </div> <label class="col-md-3 col-form-label">Revision:</label> <div class="col-md-9"> <input type="text" class="form-control" name="Revision" placeholder="Revision" id="Revision" value="{{PROJ.Revision}}"> </div> <label class="col-md-3 col-form-label">Company:</label> <div class="col-md-9"> <input type="text" class="form-control" name="Company" placeholder="Company" id="Company" value="{{PROJ.Company}}"> </div>` descriptions -
"ORDER BY NOT ALLOWED IN SUBQUERIES OF COMPOUND STATEMENTS" in Django while using UNION function [closed]
I'm new to Django and want to use this code: if "dashboard_filters_parent_checkbox" not in request.POST: all_task_id=tasks_no_assign.union(tasks_no_start).union(tasks_start).union(tasks_no_confirmed).union( tasks_confirmed).values_list('id',flat=True) all_task_parent_id=tasks_no_assign.union(tasks_no_start).union(tasks_start).union(tasks_no_confirmed).union(tasks_confirmed).values_list('task_parent__id',flat=True) #.union(sub_tasks_no_confirmed) all_task_parent_id = list(set(all_task_id) & set(all_task_parent_id)) tasks_no_assign=tasks_no_assign.exclude(Q(pk__in=all_task_parent_id)&~Q(pk__in=all_tasks_children_id)) tasks_no_start=tasks_no_start.exclude(Q(pk__in=all_task_parent_id)&~Q(pk__in=all_tasks_children_id)) tasks_start=tasks_start.exclude(Q(pk__in=all_task_parent_id)&~Q(pk__in=all_tasks_children_id)) tasks_no_confirmed=tasks_no_confirmed.exclude(Q(pk__in=all_task_parent_id)&~Q(pk__in=all_tasks_children_id)) tasks_confirmed=tasks_confirmed.exclude(Q(pk__in=all_task_parent_id)&~Q(pk__in=all_tasks_children_id)) but I get this error: ORDER BY NOT ALLOWED IN SUBQUERIES OF COMPOUND STATEMENTS I now this error shown for using Union function but where is problem? how can I do and what is correct way? thanks in advance <3 -
When I run "python .\manage.py runserver" I get this: No Python at '"C:\Users\Utilizador\AppData\Local\Programs\Python\Python312\python.exe'
virtual environment activated (env) PS C:\Users\Utilizador\Documents\FSapp> python .\manage.py runserver No Python at '"C:\Users\Utilizador\AppData\Local\Programs\Python\Python312\python.exe' virtual environment deactivated PS C:\Users\Utilizador\Documents\FSapp> python .\manage.py runserver python : The term 'python' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 python .\manage.py runserver + CategoryInfo : ObjectNotFound: (python:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException When using "python3 .\manage.py runserver" I get python3 : The term 'python3' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 python3 .\manage.py runserver + CategoryInfo : ObjectNotFound: (python3:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException IMPORTANT: I'm using django and nodejs to build a full stack application I installed all the packages while having the virtual envirnmont "env" activated Here are my system variables Here are my users variables