Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Share and save a contact with click on link in browser
I have a query? I want to save contact. when i click on the link which is mention in website. how to do? Its work on mobile application( QR. Code Scanner). When i scan a Qr code of contact.after that the scanner open a contact app and ask to save a contact. it work both android and IOS(Apple device). The same process,i want to without scan a code. when i click a link in browser contact app open and ask me to save a contact in mobile device. I am doing this functionality in Python with Django Framework. what is do to do that? How Work on mobile device. Step 1. First a QR code of contact with this website. Qr code generator Step 2. then i select a VCARD , fill the form and submitted. Step 3. after that it will generate a QR image code. Step 4. then i open a mobile scanner app to scan this code. Step 5. it will redirect and open a contact app to save this contact. I am doing this functionality in Python with Django Framework. what is do to do that? #django #python #QRcode #VCARD #Conact #Javascipt #Share -
Why am I getting 'pg_config executable not found' when deploying my web app using Vercel?
I'm trying to use Psycopg2 with Railway to connect django to postgres using this tutorial: https://dev.to/dennisivy11/easiest-django-postgres-connection-ever-with-railway-11h6. However, I got "pg_config executable not found" when trying to deploy my django web app to Vercel. This is what I get from Vercel: Error: Command failed: pip3.9 install --disable-pip-version-check --target . --upgrade -r /vercel/path0/workout_log/requirements.txt error: subprocess-exited-with-error × Getting requirements to build wheel did not run successfully. │ exit code: 1 ╰─> [35 lines of output] /tmp/pip-build-env-wf1ju6t6/overlay/lib/python3.9/site-packages/setuptools/config/setupcfg.py:293: _DeprecatedConfig: Deprecated config in `setup.cfg` !! ******************************************************************************** The license_file parameter is deprecated, use license_files instead. By 2023-Oct-30, you need to update your project and remove deprecated calls or your builds will no longer be supported. See https://setuptools.pypa.io/en/latest/userguide/declarative_config.html for details. ******************************************************************************** !! parsed = self.parsers.get(option_name, lambda x: x)(value) running egg_info writing psycopg2.egg-info/PKG-INFO writing dependency_links to psycopg2.egg-info/dependency_links.txt writing top-level names to psycopg2.egg-info/top_level.txt Error: pg_config executable not found. pg_config is required to build psycopg2 from source. Please add the directory containing pg_config to the $PATH or specify the full executable path with the option: python setup.py build_ext --pg-config /path/to/pg_config build ... or with the pg_config option in 'setup.cfg'. If you prefer to avoid building psycopg2 from source, please install the PyPI 'psycopg2-binary' package instead. For further information please check the … -
Is there a convention for returning an empty template in Django when making HTMX calls?
There are cases where I would like to not return any HTML in my view. Is there a good way to do it apart from returning a blank html file? Here is what I have currently: views.py def get_suites(request): address = request.GET.get('address') rental_units = Rental_Unit.objects.filter(address__address=address).order_by('suite') # return empty html requests if len(rental_units) > 1: return render(request, 'suite_list.html', {'rental_units': rental_units}) else: return render(request, 'empty.html') suite_list.html <label for="suite">Suite</label> <select name="suite" id="suite"> <option value="all">All</option> {% for rental_unit in rental_units %} <option value="{{rental_unit.suite}}">{{rental_unit.suite}}</option> {% endfor %} </select> main.html <label for="address">Address</label> <select name="address" id="address" hx-get="/get_suites" hx-target="#suite-wrapper"> <option value="all">All</option> {% for address in addresses %} <option value="{{address}}">{{address}}</option> {% endfor %} </select> <div id="suite-wrapper" style="display:inline"></div> -
How can I fix an 'invalid response' when using Django session and AJAX for ecommerce platform?
I am currently building an ecommerce platform and using Django session and AJAX. All I am trying to get is the response from the endpoint but it seems to be giving me an 'invalid response'. Below is my code. I will be glad if I am able to get help. var addToCart = document.getElementsByClassName("add-to-cart"); Array.from(addToCart).forEach(function (btn) { btn.addEventListener("click", function () { var product_id = btn.dataset.product; var action = btn.dataset.action; console.log(product_id, action); if (user === "AnonymousUser") { // Apply a flas message here in future console.log( "You need to be a registered user before you can buy a product" ); } else { updateUserOrder(product_id, action); } }); }); function updateUserOrder(product_id, action) { var url = "add/add_product/"; data = { 'product_id': product_id, 'action': action, } console.log(data); fetch(url, { method: "POST", headers: { "Content-Type": "application/json", "X-CSRFToken": csrftoken, }, body: JSON.stringify(data), }) .then((response) => { return response.json(); }) .then((data) => { console.log("data:", data); }); }``` view def add_to_cart(request): cart = Cart(request) if request.POST.get('action') == 'add': product_id = request.POST.get('productId') product = get_object_or_404(Product, product_id=product_id) cart.add(product=product) response = JsonResponse({'test': "this is a test data"}) return response return JsonResponse({'message': 'invalid data'}) Add To Cart I tried ensuring that the namings are okay but that didnt work. Please, what … -
Streaming Chat completion using langchain and websockets
I am not sure what I am doing wrong, I am using long-chain completions and want to publish those to my WebSocket room. Using BaseCallbackHandler, I am able to print the tokens to the console, however, using AsyncCallbackHandler is a challenge, basically, nothing seems to be happening, I tried printing stuff, but after the print message on init, nothing seems to be happening. async def send_message_to_room(room_group_name, message): print("sending message to room", room_group_name, message) channel_layer = get_channel_layer() await channel_layer.group_send( room_group_name, { "type": "chat_message", "message": message, } ) class MyCustomHandler(AsyncCallbackHandler): def __init__(self, room_group_name): self.channel_layer = get_channel_layer() self.room_group_name = room_group_name print("MyCustomHandler init") async def on_llm_new_token(self, token: str, **kwargs): print(token) await send_message_to_room(self.room_group_name, token) def generate_cited_answer_stream(roomname, question=question, texts=texts, responsetype="Simple and Pedagogical" , system_message_with_response_type=system_message_with_response_type , human_message_with_response_type=human_message_with_response_type): handler = MyCustomHandler(room_group_name=roomname) chat = ChatOpenAI(temperature=0, streaming=True, callbacks=[handler]) system_message_with_response_type = SystemMessagePromptTemplate.from_template(system_message_with_response_type) human_message_prompt = HumanMessagePromptTemplate.from_template(human_message_with_response_type) chat_prompt = ChatPromptTemplate.from_messages([system_message_prompt, human_message_prompt]) prompt_value = chat_prompt.format_prompt(question=question, texts=texts, responsetype=responsetype) chat(prompt_value.to_messages()) -
User defined user permissions
I'm not even sure how to fully ask this question so my googles haven't turned up much. So I have users, (obv) and they have an entity they're gonna be able to populate called a wallet. A user should have read write and delete permissions on a waller they create Naturally superadmins should have access to everything. But I want the users to be able to give other users read and / or write access. But regular staff should also have access. Do I just create a foreign key on the wallet populated with the user id's and boolean for read, write and delete access? Assuming I do that how do I handle Staff and super admin access? Do I like set up a view for a list of wallets that checks to see if you're an admin or staff and if not then checks if you have access and only displays those? And then only allow you to edit or delete if you have those boolean set? Does that make sense? -
openai module not found but can be clicked while importing in ide to go to its library
I am trying to create a chat bot with openai on django. But it shows that it doesnt exist in the IDE. I click on 'openai' and it takes me to its library. When i type "pip show openai" , it gives : Name: openai Version: 0.27.7 Summary: Python client library for the OpenAI API Home-page: https://github.com/openai/openai-python Author: OpenAI Author-email: support@openai.com License: Location: /Users/user/PROJECTS/chatbot_project/env_chat/lib/python3.9/site-packages Requires: aiohttp, tqdm, requests Required-by: the python and pip have version 3.9 i dont understand that if i am able to click on the 'openai' while importing it and it dont even red underline it so why it tells the module dont exist. import openai my python interpreter is linked with the env i created in the project i.e. env_chat i am a bit new, so help me out on this. -
some html files load in just fine and others don't work at all even tho they have the same code and are in the same folder
my problem is i have multiple files in my project that use basically the same code but with some files it does work and with others not. and all the files are in the same folder. i have tried troubleshooting and looking at the Debugging Tool on browsers and even asked chatgpt i don't get it this code works. {% extends "base.html"%} {% block subheader%} <div class="sub-header"> <div class="sub-middel"> <button class="sub-bu" onclick="window.location.href='{% url 'projects_unity' %}'">unity</button> <button class="sub-bu" onclick="window.location.href='{% url 'projects_websites' %}'">websites</button> <button class="sub-bu" onclick="window.location.href='{% url 'projects_construct' %}'">construct</button> <button class="sub-bu" onclick="window.location.href='{% url 'projects_godot' %}'">godot</button> <!-- {% for program in post.programs.all%}--> <!-- <button class="sub-bu">{{program}}</button>--> <!-- {% endfor %}--> </div> </div> {% endblock subheader %} {% block content %} {% for post in posts_websites %} <div class="posts"> <h1> {{post.title}} </h1> <!-- Slideshow container --> <div class="slideshow-container"> <!-- Full-width images with number and caption text --> {% for image in post.image.all %} <div class="mySlides"> <div class="numbertext" ><p id="currentnummer"></p><p id="imagesnummer"></p> </div> <img src="{{ image.image.url }}" alt="{{ image.image.name }}" style="width:100%" height = "348" > <div class="text">{{image.CaptionText}}</div> </div> {% endfor %} <!-- Next and previous buttons --> <a class="prev" onmouseenter="changemouseicon(true)" onmouseleave="changemouseicon(false)" onclick="changeSlide(-1)">&#10094;</a> <a class="next" onmouseenter="changemouseicon(true)" onmouseleave="changemouseicon(false)" onclick="changeSlide(1)">&#10095;</a> </div> <p> by {{ post.author }} on {{post.date_posted}} </p> <p … -
Why does the built-in "with" template tag in django result in duplicate queries
In the django docs for the "with" template tag, it says that this tag.. is useful when accessing an “expensive” method (e.g., one that hits the database) multiple times. However, when I use it in my own template, I've observed (using django debug toolbar) that each time I call the variable that I create using the "with" template tag, it results in duplicate queries to the database if I perform an operation on that variable within another template tag. Why is this the case? Shouldn't I be able to do things to that variable without it querying the database? Below is my abridged and simplified code. Background I have three models: ## models.py class Contributor(models.Model): name = models.CharField(max_length=100) class Contribution(models.Model): contributor = models.ForeignKey( Contributor, on_delete=models.RESTRICT, related_name='contributions' ) class ROLE_CHOICES(models.TextChoices): A = 'AUTHOR', _('Author') C = 'COAUTHOR', _('Co-Author') E = 'EDITOR', _('Editor') V = 'VOICE', _('Voice Actor') S = 'AUDIO', _('Audio Engineer') role = models.CharField(max_length=10, choices=ROLE_CHOICES.choices) class Scenario(models.Model): title = models.CharField(max_length=200) contributions = models.ManyToManyField( Contribution, related_name='contributions' ) The template is associated with a class-based detail view: ## views.py class ScenarioDetailView(generic.DetailView): model = Scenario Here is my custom template tag code: ## custom_tags.py @register.filter def only_role(scenario, test_role): return scenario.contributions.filter(role=test_role) Here is my … -
How do I combine multiple sorting/filtering logic in Django in efficient way?
I am trying to make a site that supports searching/sorting/filtering at the same time. I did it in the 'if/elif' logic and it works! But it doesn't seem to be so efficient (from perspective of copying the code many times and inability to change something fast). As you can see in code examlpe below, I just specify these conditions for each possible case, such as: "with filter1, but without filter2 and filter3"; "with filter1 and filter2, but without filter3" and so on. As you can imagine, adding filters 4 and 5 sounds like a nightmare now, to be able to redo all this logic. Can you please share your thougths on how to do in a better way? I'm new to Django, so looks like I'm doing something wrong here Here is how my main view inside views.py looks like: class ResultsView(LoginRequiredMixin, ListView): model = Ads paginate_by = 9 template_name = 'library.html' #GET SEARCH def get_queryset(self): query_search = self.request.GET.get('search') query_sort = self.request.GET.get('sort_by') query_filter = self.request.GET.get('filter_by_language') query_search_username = self.request.GET.get('search_username') #search=YES, sort=NO, filter=NO if query_search and not query_sort and not query_filter: object_list = self.model.objects.filter(Q(headline__icontains=query_search) or Q(promoted_url__icontains=query_search)) elif query_search_username: #and not query_sort and not query_filter: object_list = self.model.objects.filter(Q(username__iexact=query_search_username)) #search=YES, sort=NO, filter=YES elif query_search … -
Accessing OneToOneRel object in Django to perform search
currently I am working on a Django project, where we have created many relations between objects. In general - everything is working fine, expect - Frazesearch. Below I paste my model classes: Students.py from django.db import models from degreeCourse.models import DegreeCourse from studentFinances.models import StudentFinances from studentLoggingData.models import StudentLoggingData from studentPersonalData.models import StudentPersonalData # Create your models here. # Part already after refactor class Student(models.Model): personalStudentData = models.OneToOneField( StudentPersonalData, on_delete=models.CASCADE, default=None ) loggingStudentData = models.OneToOneField( StudentLoggingData, on_delete=models.CASCADE, default=None ) financesStudentData = models.ManyToManyField( StudentFinances ) STUDENTS_UPLOAD_TO = "students/" image = models.ImageField( null=True, blank=True, upload_to=STUDENTS_UPLOAD_TO ) def __str__(self): return f"{self.personalStudentData.name} {self.personalStudentData.surname}" StudentPersonalData.py from django.db import models # Create your models here. class StudentPersonalData(models.Model): name = models.CharField( max_length=40, null=False, unique=False ) surname = models.CharField( max_length=50, null=False, unique=False ) personalIdNumber = models.CharField( max_length=11, null=False, unique=True ) phoneNumber = models.CharField( max_length=20, null=False, unique=True ) email = models.CharField( max_length=50, null=False, unique=True ) streetAddress = models.CharField( max_length=40, null=True, unique=False ) houseNumber = models.CharField( max_length=4, null=False, unique=False ) flatNumber = models.CharField( max_length=4, null=True, unique=False ) zipNumber = models.CharField( max_length=6, null=False, unique=False ) country = models.CharField( max_length=40, null=False, unique=False ) isActive = models.BooleanField( default=True, null=False ) def __str__(self): return f"{self.name} {self.surname}" The problem is in views.py file for Student, … -
Elasticsearch Highlight result missing string
I am trying to use Elasticsearch's highlighting feature to highlight certain words from a text field. The text can be short or long (over 300 chars sometimes). Here is the highlight field passed to search function: def search(self): highlight = { "fields": { "content": { "type": "plain", "number_of_fragments": 0, } } } s = super(FacetedCustomSearch, self).search() return s.extra(highlight=highlight) As you can see below, the highlighted text is missing the - 1 POUND BAG string at the end. This usually happens when the text is over ~100 chars and sometimes with special characters like ! or / or - content: YOUR OFFICEKITCHEN - TASTING KITCHEN - SWEET CHILI HABANERO - GOURMET HANDMADE CRAFT MEAT SNACK - 1 POUND BAG highlighted content: YOUR OFFICEKITCHEN - TASTING KITCHEN - SWEET CHILI HABANERO - <em>GOURMET HAND</em><em>MA</em>DE CRAFT MEAT SNACK So far, I have tried to tweak the number_of_fragments (setting it to 0) and fragment_size and set the type to plain. Nothing seems to fix this issue. Any suggestions? Using elasticsearch-dsl 7.4.0 -
Python unit test got error on INSTALLED_APPS settings not configured
With PyCharm IDE, we have a unit test importing the models module of the Django project for testing. While expecting a happy pass, the test always hit en error saying: django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings. Configure() before accessing settings.. We are new to this part of the Python unit test, so we highly appreciate any hints or suggestions. The unit test: from applicationapp import models ... class TestElastic(TestCase): def test_parse_request(self): # expecting happy pass # # self. Fail() return The full error trace: /data/app-py3/venv3.7/bin/python /var/lib/snapd/snap/pycharm-professional/327/plugins/python/helpers/pycharm/_jb_unittest_runner.py --target test_elastic.TestElastic Testing started at 2:07 PM ... Launching unittests with arguments python -m unittest test_elastic.TestElastic in /data/app-py3/APPLICATION/tests Traceback (most recent call last): File "/var/lib/snapd/snap/pycharm-professional/327/plugins/python/helpers/pycharm/_jb_unittest_runner.py", line 35, in <module> sys.exit(main(argv=args, module=None, testRunner=unittestpy.TeamcityTestRunner, buffer=not JB_DISABLE_BUFFERING)) File "/usr/local/lib/python3.7/unittest/main.py", line 100, in __init__ self.parseArgs(argv) File "/usr/local/lib/python3.7/unittest/main.py", line 147, in parseArgs self.createTests() File "/usr/local/lib/python3.7/unittest/main.py", line 159, in createTests self.module) File "/usr/local/lib/python3.7/unittest/loader.py", line 220, in loadTestsFromNames suites = [self.loadTestsFromName(name, module) for name in names] File "/usr/local/lib/python3.7/unittest/loader.py", line 220, in <listcomp> suites = [self.loadTestsFromName(name, module) for name in names] File "/usr/local/lib/python3.7/unittest/loader.py", line 154, in loadTestsFromName module = __import__(module_name) File "/data/app-py3/APPLICATION/tests/test_elastic.py", line 6, in <module> from applicationapp.soap.elastic … -
How to Run a Pyomo Optimization Problem in a Django-Heroku App?
I have been trying to deploy a Django app that use the python optimization package 'pyomo' https://pyomo.readthedocs.io/en/stable/index.html It works locally, but not when deployed to heroku. In production, it is not able to find the uploaded executable for the solver. From the logs: 2023-05-30T19:49:36.256914+00:00 app[web.1]: RuntimeError: Attempting to use an unavailable solver. 2023-05-30T19:49:36.256915+00:00 app[web.1]: 2023-05-30T19:49:36.256915+00:00 app[web.1]: The SolverFactory was unable to create the solver "HIGHS" 2023-05-30T19:49:36.256915+00:00 app[web.1]: and returned an UnknownSolver object. This error is raised at the point 2023-05-30T19:49:36.256915+00:00 app[web.1]: where the UnknownSolver object was used as if it were valid (by calling 2023-05-30T19:49:36.256915+00:00 app[web.1]: method "solve"). 2023-05-30T19:49:36.256915+00:00 app[web.1]: 2023-05-30T19:49:36.256916+00:00 app[web.1]: The original solver was created with the following parameters: 2023-05-30T19:49:36.256916+00:00 app[web.1]: executable: /app/number_generator/executables/highs 2023-05-30T19:49:36.256916+00:00 app[web.1]: type: HIGHS 2023-05-30T19:49:36.256916+00:00 app[web.1]: _args: () 2023-05-30T19:49:36.256916+00:00 app[web.1]: options: {} 2023-05-30T19:49:36.257340+00:00 app[web.1]: 10.1.20.80 - - [30/May/2023:19:49:36 +0000] "POST /opttool/ HTTP/1.1" 500 145 "https://simple-esa.herokuapp.com/opttool/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36" 2023-05-30T19:49:36.257469+00:00 heroku[router]: at=info method=POST path="/opttool/" host=simple-esa.herokuapp.com request_id=73e964ec-dfca-487b-8b8c-319d01ce55f0 fwd="2.106.20.24" dyno=web.1 connect=0ms service=11075ms status=500 bytes=445 protocol=https I have three suspicions: I messed up my path to the executable You can't upload .exe files to heroku. Would there be another way to create a small optimization problem on a django-heroku app … -
Nginx refuses to connect to Django container in Lightsail
I have 2 images that I am uploading to aws lightsail. If I upload the django one it works without any issue, but trying to add to it Nginx has not been possible as Nginx cannot connect to django. I get this error: [30/may/2023:16:13:38] 2023/05/30 16:13:38 [error] 30#30: *71 connect() failed (111: Connection refused) while connecting to upstream, client: 172.26.45.36, server: localhost, request: "GET / HTTP/1.1", upstream: "http://172.26.18.131:8000/", host: "172.26.2.175" [30/may/2023:16:13:38] 172.26.45.36 - - [30/May/2023:16:13:38 +0000] "GET / HTTP/1.1" 502 157 "-" "ELB-HealthChecker/2.0" "-" this is my nginx.conf file: server { listen 80; server_name localhost; location /static/ { root /jp/static; } location / { proxy_pass http://myservice.service.local:8000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } } when I check django, it seems just fine: [30/may/2023:16:12:24] 129 static files copied to '/jp/static'. [30/may/2023:16:12:26] Operations to perform: [30/may/2023:16:12:26] Apply all migrations: admin, auth, contenttypes, myprofile, sessions [30/may/2023:16:12:26] Running migrations: [30/may/2023:16:12:26] No migrations to apply. [30/may/2023:16:12:27] [2023-05-30 16:12:27 +0000] [9] [INFO] Starting gunicorn 20.1.0 [30/may/2023:16:12:27] [2023-05-30 16:12:27 +0000] [9] [INFO] Listening at: http://0.0.0.0:8000 (9) [30/may/2023:16:12:27] [2023-05-30 16:12:27 +0000] [9] [INFO] Using worker: sync [30/may/2023:16:12:27] [2023-05-30 16:12:27 +0000] [10] [INFO] Booting worker with pid: 10 This is my docker-compose file version: '3' services: … -
django-report-builder throws unauthorized error when I try it add a report as admin user
I am trying to implement report-builder for my django application. I have followed https://django-report-builder.readthedocs.io/en/latest/quickstart/ for the setup. From the admin console I can see reports section but when I try to add one I get Unauthorized error. Attaching screenshot for your reference Thanks in advance!!! I tried checking user permissions though I am admin user. I expect it to redirect once after I click on save and build report button on reports page. -
The django modal window don't stay with content inside
I'm really lost here. I build the django model window and when i start to write the content inside, everything it's out from the modal window. I have no idea what's going on. Click here to see the image The modal code <div id="modal_window_new_register" class="modal_window_new_register" > <div class="new_register_modal"> <button class="close" id="close">X</button> </div> Test Test Test Test Test </div> The model css code /* Modal window */ .modal_window_new_register{ width: 100vw; height: 100vh; position: absolute; top: 0; left: 0; background-color: #00000080; display: none; align-items: center; justify-content: center; z-index: 9999; overflow: auto; } .new_register_modal{ width: 40%; min-width: 450px; height: 95vh; background-color: #ffff; padding: 20px; border-radius: 10px; } .close{ position: absolute; top: -5px; right: -5px; width: 30px; height: 30px; border-radius: 50%; border: 0; background-color: #ffffff96; font-size: 20; cursor: pointer; } .modal_window_new_register.open_new_register_modal{ display: flex; } -
Understanding Nginx Logging: Does $request_time include Django backend response time?
I am checking the performance and response times of a web-app and the parties involved in it. I have a question regarding the logging that nginx makes of api rest requests to the backend of the web-app (React-Django). Nginx has the ability to log the $request_time to /var/log/nginx/access.log when serving a request from the backend. The question is: does it contain within that time in seconds the time that the Django backend takes to respond to the request? This is not clear to me from reading the documentation Nginx log_format. In what I tested, django responds to a request in 30 ms and Nginx logs that request as served in 33 ms. Do those 33 ms contain the 30 ms that django takes or are they separate? or are they only referring to the handling that Nginx can do (i.e. manage the request in a queue if there is a lot of service demand)? Thanks in advance! -
How can I retrieve a Django model element by name, regardless of text case?
How can i get element by name despite of text register. for example in my models i have element with user_name equal to "hello world" and i want get this element. So i write: User.objects.get(user_name=name) It's working if name equal to "hello world", but if name equal to "Hello World" or "hElLO wOrLD" then it's not working. I can use name.lower() but if user_name from models equal to "HELLO WORLD" then it's not working again. -
Issue with "delete" functionality in Django admin inline formset
I'm experiencing an issue with the "delete" functionality in my Django admin inline formset. I have a custom template for rendering the formset, and I've added a element with the class "delete" to allow users to delete rows. However, the delete functionality doesn't seem to be working as expected. tabular.html {% load i18n admin_urls static admin_modify %} <div class="js-inline-admin-formset inline-group" id="{{ inline_admin_formset.formset.prefix }}-group" data-inline-type="tabular" data-inline-formset="{{ inline_admin_formset.inline_formset_data }}"> <!-- ... --> <table class="table table-centered table-nowrap mb-0 rounded inline"> <thead class="thead-light"> <tr> <th class="original"></th> <!-- ... --> {% if inline_admin_formset.formset.can_delete and inline_admin_formset.has_delete_permission %} <th>{% translate "Delete?" %}</th> {% endif %} </tr> </thead> <tbody> {% for inline_admin_form in inline_admin_formset %} <!-- ... --> <tr class="form-row {% if inline_admin_form.original or inline_admin_form.show_url %}has_original{% endif %}{% if forloop.last and inline_admin_formset.has_add_permission %}empty-form{% endif %}" id="{{ inline_admin_formset.formset.prefix }}-{% if not forloop.last %}{{ forloop.counter0 }}{% else %}empty{% endif %}"> <td class="original"> <!-- ... --> </td> <!-- ... --> {% if inline_admin_formset.formset.can_delete and inline_admin_formset.has_delete_permission %} <td class="delete"> {% if inline_admin_form.original %} {{ inline_admin_form.deletion_field.field }} {% endif %} </td> {% endif %} </tr> {% endfor %} </tbody> </table> <!-- ... --> </div> Image Preview of the issue I suspect that there might be missing JavaScript or CSS code that handles the … -
Field 'id' expected a number but got <QueryDict
This is a common error on stack overflow but I cannot draw similarities with their errors and mine. A number is expected in the id column of the database(automatically made by django) but a query dict was put in instead Model: class Price(models.Model): HourlyPrice = MoneyField(default_currency="GBP",max_digits=19,decimal_places=3,null=True,blank=False) # price per hour DailyPrice = MoneyField(default_currency="GBP",max_digits=19,decimal_places=2,null=True,blank=True)# price per day WeeklyPrice = MoneyField(default_currency="GBP",max_digits=19,decimal_places=2,null=True,blank=True)# price per week MonthlyPrice = MoneyField(default_currency="GBP",max_digits=19,decimal_places=2,null=True,blank=True)# price per month View: def test(request): if request.method == 'POST': form = Price(request.POST) form.save() return render(request,'app/index.html', { 'title':'Home Page', 'year':datetime.now().year, } ) else: form = TestPrice(request.GET) context = { 'form': form, } return render(request,'app/test.html',context) Template: {% extends "app/layout.html" %} {% block content %} <form method="post" action=""> {% csrf_token %} <table> {{form}} </table> <button type="submit">Submit</button> </form> {% endblock %} Thank you for your time -
How to replace filter and .distinct() with another filter and .first() when subquery returns no result in Django Python?
I've got a subquery who returning some data depending of a specific filter. This specific filter sometime return null result but what I want is to catch the first() result without specific filter if no result return with. date_filter = Q(start_date__lte=OuterRef('object_start_date'), end_date__gte=OuterRef('object_start_date')) | \ Q(start_date__lte=OuterRef('object_start_date'), end_date=None) The query where i use this filter data_subquery = Object.objects.filter(date_filter).filter(user=OuterRef('user')).distinct() This subquery is used here next : main_subquery = Main.annotate(role=Subquery(data_subquery.values('role__name')[:1])) I've to anonymized data but the goal is to understand the need .... The filter subquery *datefilter *should be used if data_subquery return something ... else I don't need this filter and want to replace .disctinct() by .first() THanks for your help :) I've got a function to return specific data depending on user and date given in parameters ... or first one ... but I don't know how to use function into subquery ;) I tried to add : if len(data_subquery) == 0: data_subquery = Object.objects.filter(user=OuterRef('user')).filter() But it can't work with subquery :( -
poetry's 'run' stopped working claiming manage.py is missing
I have been using the run command for a year to perform all kinds of admin work, in this precise manner (i.e. with a dot): poetry run ./manage.py runserver and suddenly it no longer works, saying: $ poetry run ./manage.py runserver Command not found: ./manage.py But the file is there, and is executable: $ file manage.py manage.py: Python script, ASCII text executable witha proper #! /usr/bin/env python I know there's another way, namely: $ poetry shell followed by $ ./manage.py runserver but I feel a little stupid having to work around it =) I have recreated the virtual environment, but to no avail. The problem must be somewhere else, is my shell is missing something or poetry's setup? I did reinstall the system after all, but that wasn't a first time of so doing.. Thank you for your time! -
how to filter dropdown values based on the value of other dropdown in django
I have 2 models main_category and sub_category, in the sub_category model, it has a name and Foreign key of the main_category it belongs to. and I have 3rd model which is 'record' and it has main_category and sub_category as a Foreign key. what I need is when selecting the main category from the drop-down in the 'record' form it should filter the values in the sub_category dropdown so that it shows only the values that have the selected main category here are the models class MainCategory(models.Model): name = models.CharField(max_length=100, unique=True) activity_status = models.BooleanField() def __str__(self): return self.name class SubCategory(models.Model): name = models.CharField(max_length=100) main_category = models.ForeignKey(MainCategory, on_delete=models.CASCADE) activity_status = models.BooleanField() def __str__(self): return self.name class Record(models.Model): RECORD_TYPES = [ ('income', 'Income'), ('expense', 'Expense'), ('transfer', 'Transfer'), ] DELETED_CATEGORY = 'Deleted category' date = models.DateField(default=timezone.now) category = models.ForeignKey(MainCategory, on_delete=models.SET(DELETED_CATEGORY), default=1) subcategory = models.ForeignKey(SubCategory, on_delete=models.SET(DELETED_CATEGORY)) type = models.CharField(max_length=10, choices=RECORD_TYPES) amount = models.DecimalField(max_digits=10, decimal_places=2, validators=[MinValueValidator(0)]) account = models.ForeignKey(Account, on_delete=models.CASCADE) notes = models.TextField(blank=True) transfer_ops = models.ForeignKey(TransferOperation, on_delete=models.CASCADE, null=True, blank=True) activity_status = models.BooleanField() def __str__(self): return f"{self.date} - {self.type}: {self.amount}" and here is the view class CreateRecordView(CreateView): model = Record form_class = RecordForm template_name = 'create_record.html' success_url = reverse_lazy('home') def get_form(self, form_class=None): form = super().get_form(form_class) form.fields['subcategory'].queryset = … -
Why are my media files not being served in Django application with nginx?
I have a problem with my Django application which is deployed using gunicorn and nginx. I have a model for storing images in my sqlite database. class Image(models.Model): image_file = models.ImageField(upload_to="fucking_scraper/files/item_photos") item = models.ForeignKey(Item, on_delete=models.CASCADE) Here is my urls.py file urlpatterns = [ path("admin/", admin.site.urls), path("", include("fucking_scraper.urls")), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) and here are parts of settings.py file, related to serving files BASE_DIR = Path(__file__).resolve().parent.parent MEDIA_URL = "/media/" MEDIA_ROOT = "" STATIC_URL = "static/" STATICFILES_DIRS = [os.path.join(BASE_DIR, "fucking_scraper", "static", "fucking_scraper"), os.path.join(BASE_DIR, "fucking_scraper", "files", "item_photos")] STATIC_ROOT = os.path.join(BASE_DIR, 'static/') On a deployed website images are not displayed. I assume there is a problem with nginx configuration because before deployment it was working correctly in a debug mode. Here is how it looks like: server { listen [::]:80; server_name fwebsite.org; location /static/ { root /home/django/fwebsite.org; } location /media/ { root /home/django/fwebsite.org/fucking_scraper/files/item_photos/; } location / { include proxy_params; proxy_pass http://unix:/home/django/fwebsite.org/fucking_website.sock; } } I tried setting up location /media/ following instructions found on the internet but it didn't work for me and I am currently stuck.