Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to add a XML file to postgreSQL table using python in Django
I have initially connected to postgreSQL in settings.py and added my app in the INSTALLED_APPS. Then I created my table in models.py models.py: class Activity(models.Model): date = models.DateField(default=None) time = models.TimeField(default=None) function = models.CharField(max_length=10, default = None) status = models.CharField(max_length=10,default=None, blank=True, null=True) logfilename = models.CharField(max_length=128) after that I migrated my table and the table was created in postgreSQL. currently I added the XML data to postgreSQL Table by adding a code in the command shell command shell code: from oapp.models import Activity import os import xml.etree.ElementTree as ET from xmldiff import main, formatting file_1 = 'sample.xml' def xmlparse(): data = ET.parse(file_1) root = data.findall("record") for i in root: date = i.find('date').text time = i.find('time').text function = i.find('function').text status = i.find('status').text logfilename = i.find('logfilename').text x = Activity.objects.create(date=date, time=time, function=function, status=status, logfilename=logfilename) x.save xmlparse() But I wanted to run it as a python code. When I run it as python code it shows module not found error. It only works in command shell. What I want is to run t as a python code. error when run as python: Traceback (most recent call last): File "c:\Users\ostin\Desktop\nohope\projectq\qapp\qcode.py", line 1, in <module> from qapp.models import newrecord ModuleNotFoundError: No module named 'qapp' -
Django Group By like in SQL
I have following model class Product(models.Model): name = models.CharField(max_length=20) class FAQ(models.Model): product = models.ForeignKey(Product, on_delete=models.PROTECT) title = models.CharField(max_length=500) description = models.TextField(max_length=2000) order = models.IntegerField(validators=[MinValueValidator(0)], default=0) column = models.IntegerField(validators=[MinValueValidator(0)], default=0) def __str__(self): return f'{self.product.name}->{self.title}->{self.column}' class Meta: ordering = ('column', 'order') I want to group all result where column is same i.e IF column have value 1 in my model all data is enclosed inside one list I tried looking for annotate but could not figure out how i use in my code expected response [ [## this have column value 1 { "product": 1, "title": "Test 1", "description": "Description 1", "order": 0, }, { "product": 1, "title": "Test 2", "description": "Description 2", "order": 1, } ], [ ## this have column value 2 { "product": 1, "title": "Test3", "description": "Description 3", "order": 0, }, { "product": 1, "title": "Test 4", "description": "Description 4", "order": 1, } ] ] Here is my overall code any class FAQView(APIView): def list(self, request): queryset = FAQ.objects.values('product', 'title', 'description', 'order').annotate("?") serializer = FAQSerializer(queryset, many=True) return Response(serializer.data) -
Access blocked: django-oauth’s request is invalid
Sign in with Google Access blocked: django-oauth's request is invalid a avinash.sharma@technogetic.com You can't sign in because django-oauth sent an invalid request. You can try again later, or contact the developer about this issue. Learn more about this error If you are a developer of django-oauth, see error details. Error 400: redirect_uri_mismatch i am trying to use google oauth(social-auth) in django.i followed these steps given in this link="https://www.section.io/engineering-education/django-google-oauth/" but keep getting this error in browser.please help -
`SynchronousOnlyOperation` error while trying to run Playwright automation triggered django admin action
This is the error: SynchronousOnlyOperation at /admin/app/modelA/ You cannot call this from an async context - use a thread or sync_to_async. What I'm trying to do is: I have an action in django-admin that intends to run an automated task with Playwright. The action in admin.py looks like this: @admin.action(description="Do task") def run_task(modeladmin, request, queryset): for obj in queryset: task = Task(obj) task.run() And the Task class looks like this: class Task: def __init__(self, task: Task) -> None: self.task = task def run(self): with sync_playwright() as p: browser = p.chromium.launch(headless=True) page = browser.new_page() page.go_to("www.google.com") # DO SOME STUFF browser.close() And when I run the action the error shows as soon as chromium gets ready. Thank you beforehand. I expect it to do the stuff without running at least get the title of the page. I tried using sync_to_async as these docs suggest, implemented it in two ways (which I believe are wrong) First way I tried: Is by trying to use sync async in the admin.py file when the function Task.run is called: @admin.action(description="Do task") def run_test(modeladmin, request, queryset): for obj in queryset: task = Task(obj) sync_to_async(task.run, thread_sensitive=True) It didn't work 2. Second way I tried: Is by adding the … -
what are the different ways to login and authenticate user (like using OAuth2 ,jwt ,okta ) in Django application
I want to know what are the different ways by which live applications built on Django framework Authenticate users while login. what all ways are used apart from Django inbuilt authentication for user login . I found all these tutorials using Django's inbuilt authentication from Django.contrib library. I want to know what methods are used in real world live Django applications. -
Django Q and reduce doesn`t work as expected
I'm newly in Django. Don't understand where I'm going wrong. When I use this code it will work as expected. def filter_qs(self, qs): if self.filter == {}: return qs else: q_objects = [models.Q()] if self.filter['vendor']: q_objects.append(Q(vendor__in=self.filter['vendor'])) if self.filter['start_date']: q_objects.append(Q(date__gte=self.filter['start_date'])) if self.filter['end_date']: q_objects.append(Q(date__lte=self.filter['end_date'])) if self.filter['product']: product_list = (Q(product_type__contains=product) for product in self.filter['product']) if product_list: q_objects.append(reduce(operator.or_, product_list)) if len(q_objects) > 1: qs = qs.filter(reduce(operator.and_, q_objects)) However, when I use the query filter, filter_query = Result.objects.filter( Q(vendor__in=vendor) if vendor else Q() & Q(date__gte=start_date) if start_date else Q() & Q(date__lte=end_date) if end_date else Q() & Q(reduce(operator.or_, (Q(product_type__contains=product) for product in products)))) this part of the query does not work in filter_query: Q(reduce(operator.or_, (Q(product_type__contains=product) for product in products))) I don't get a query filter per product. Don't understand where I'm going wrong. Look for the query to work properly. -
hello can I make several genlist on the same model with different forms [closed]
I create a model and i do a genlist,gencreate,genupdate .... and now i need another genlist on the same model. I do it but on the menu the first genlist is always affiched. What can i do to display the second genlist or the second forms on the edit mode. -
NoReverseMatch at /question/1 Reverse for 'upvote' with arguments '('',)' not found. 1 pattern(s) tried: ['answers/(?P<id>[0-9]+)/upvote\\Z']
Can some one help me,Iam trying to get a details view page and i got this error No reverse match.Im sharing my view page,urls, and models down here .please find a solution guys!!!! https://hastebin.com/ogogofawag.typescript i tried to change the url names and didnt get rid of that error the url link is ` <a href="{%url 'upvote' ans.id %}">upvote<span>{{ans.upvote.all.count}}</span></a> ` -
How to customise task context (process_data cards) in django-viewflow
What I want I'm building an approval workflow using django-viewflow and django-material. The individual tasks are rendered as a main form with context on a very narrow column on the right hand side. I want to change the layout so that the task context (the detail views of all involved model instances) is better readable to the user, and also customise which fields are shown (eg. exclude a user's password hash). Where I'm stuck Is there a way to override which data is available as process_data short of overriding viewflow's get_model_display_data and include_process_data? E.g. I'd like to have the related instance's __str__() as title. Does viewflow have any canonical way to provide individual detail card templates? My alternative would be to completely re-work the contents of the process_data sidebar using context['process'] as the central instance, but that would tie the templates to the data model. I'd be grateful on any pointers here. What I've tried I'm overriding/extending the viewflow templates. As per templatetag include_process_data, the template process_data.html supplies the column of model instance detail cards, fed by data from get_model_display_data. It's e.g. easy to override process_data.html to change the cards into a MaterializeCSS collapsible list: {% load i18n viewflow material_frontend … -
Date Converter app in django views.py is running same time, i would like post method to run after user click only
I have created views.py for BS to AD date converter but my views will run only the UserInputForm() get loaded first, i have to comment post method then input data from frontend then again uncomment my post method views to get converted data. Please help me to fix by running first UserInputForm() then after click need to go thought the post method views.py from django.shortcuts import render from pyBSDate import convert_BS_to_AD from . forms import UserInputForms # Create your views here. def neview(request): # todays's date fm = UserInputForms() if request.method == 'POST': data = request.POST.get('date') up = data.replace('-',',') y = up[0:4] m = up[6:7] d = up[8:10] ad_data = convert_BS_to_AD(y, m, d) return render(request, 'NEC/NepaliToEnglish.html', {'fmr': fm, 'dt': ad_data}) html page {% extends 'NEC/base.html' %} {% block title %} Mid-West University Date Conveter App {% endblock title %} {% block content %} <h1>Welcome to Mid-West University Date Converter Application</h1> <h1>BS to AD Date Converter YYYY-MM-DD</h1> <form action="" method="post"> {% csrf_token %} {{fmr}} <br /> <br /> <input type="submit" /> </form> {{dt}} {% endblock content %} -
Subquery a Parent Model returning Error in Django
class Customer(models.Model): pass class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.CASCADE, related_name='orders') total_amount = models.DecimalField() As you can see, a customer can have many orders. What I want to know, how much amount one customer has spent so far. qs = Customer.objects.get(pk=OuterRef('customer').orders.all().aggregate(total=Sum('total_amount)) Order.objects.annotate(customer_total=Subquery(qs.values('total')[:1])) But I am getting error ValueError: This queryset contains a reference to an outer query and may only be used in a subquery. My question is, can we Subquery a parent Model ? or i am doing something wrong ? -
Is it possible for Django to sum non numetric field?
I have learned we can sum all(or filtered) columns like price from this question. ItemPrice.objects.aggregate(Sum('price')) But is it possible for Django to sum non numetric field's length, such as CharField or JSONField? A pseudocode is like following. User.objects.aggregate(Sum(len('username'))) -
Please configure the inventory detail for item
I am trying to create an item fulfillment for an item , the on hand quantity on item fulfillment record is showing as X for that item at that location , but when it says configure inventory details for line X i am not able to see available under the status column I tried creating a saved search and getting the item's on hand greater than zero and location in the results but got as empty I also checked previous item fulfillments for that item they are created successfully with on hand quantity but now i am getting error as - Please configure the inventory detail for item -
Should i use different servers for backend and api provider?
I'm building an app in which I'm using react as frontend. And now I need to provide data from APIs, now my question is should I create a new server for APIs? Can anybody suggest to me how can I do this? BTW I'm using Django-restframework to interact with React. -
set optional parameter in a django url how can do this
I have write down this code in a url path('list/<str:name>', GetList.as_view(), name = "getList" ) now i want to set name as optional parameter with list it show show all and with name i will implement query -
Django manage stream response from StreamingHttpResponse
I met a problem when create stream video from Django server. generator_list = [] @gzip.gzip_page def get_stream_video(request, stream_link): if len(generator_list) == 2: generator_list[1].close() del(generator_list[1]) try: generator = detect_stream(stream_link) generator_list.append(generator) stream = StreamingHttpResponse(, content_type="multipart/x-mixed-replace;boundary=frame") return stream except: pass Everytime I call this controller from client, it will create new instance of connection. Then I found that if those streaming response not closed, CPU will load more and more. I try to save stream generator and close but it did not work. -
Could I make a Django project in ubuntu by Java?
Well... In my toy project, I want to make a Django project in ubuntu server by java ` ProcessBuilder builder = new ProcessBuilder(); builer.command("sh","-c","django-admin startproject helloWorld"); builder.directory(/home/ubuntu/toy_service); try { builder.start(); } catch(IOException e) {e.getMessage();} ` I check process builder activate command such as touch, ls, cd etc... But django-admin never activate ever. I check django is installed on my server How can I make a django project? Sorry for my fool English expected ProcessBuilder builder = new ProcessBuilder(); builer.command("sh","-c","django-admin startproject helloWorld"); builder.directory(/home/ubuntu/toy_service); try { builder.start(); } catch(IOException e) {e.getMessage();} happen nothing -
python django intercepting an sql query before it is executed
I have a library that natively crashes into django and works with django Admin and knows how to use objects.all() and so on. The QuerySet goes instead of to the database location in another api project. I need to intercept an sql query before executing which django does so that I can do even more magic with queries. maybe someone knows how to do it in theory ? well, or there is an example I will be glad to see. у меня есть библиотека которая нативно врезается в django и работает с django Admin и умеет использовать objects.all() и тд. Сам QuerySet в место базы данных ходит в другой проект по api. мне нужно перехватить sql запрос до выполнения который делает django что бы я мог делать еще больше магии с запросами. может кто то знает как это в теории сделать ? ну или есть пример буду рад увидеть. I tried to look for something similar on the Internet, but everywhere there is information only for outputting information to the logs about executed requests through Middleware я пробовал искать что то подобное в интернете но везде есть информация только на вывод в логи информацию о выполненных запросах через Middleware -
pylint with Django settings not working in vscode
I am attempting to configure pylint to use in my Django project. However, in VS Code it does not seem to be working when I configure my settings.json. For example, my settings.json is as follows: { "python.linting.enabled": true, "python.linting.pylintEnabled": true, "python.linting.pylintArgs": [ "--disable=C0111", "--load-plugins", "pylint_django", "--django-settings-module", "myproject.settings" ] } When I remove the two lines "--django-settings-module" and "myrpject.settings", pylint begins to work and throws linting errors. When I add the lines back, the linting errors go away (when they should actually be linting errors i.e. importing a package that isn't used). Below is my folder structure for the project I am working in. What could be the issue behind the django-settings-module? Why is it not registering when the argument is used? -
Django how to pass clicked on link text to a URL on another HTML page showing static images?
I have table of tickers on one HTML page, and four charts displayed on another HTML page. These charts come from my static/images folder full of hundreds of images named by ETF tickers. If I click the ETF ticker "PSCD" in the first row of the table, how can I have that linked in the other HTML page so that it shows only the images from my static/images folder whose filename contains the associated ticker...in this case "PSCD" when clicked. In the charts.html code example below, I hardcoded PSCD into the image tag but I want this dynamically linked. Below you will see my table.html page showing my table from above. Next is the charts.html where I would like the etf_ticker that was clicked in that table to be entered into the image tags such as <img src="{% static 'forecast/images/sample_regression_PSCD.jpg' %}" alt="sample_regression"/></div> where you see I have hardcoded "PSCD" into the image tag. But I need this to be dynamic, from which you click on the link in table.html, and it gets inserted into the image tag in charts.html. table.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>ETF Table</title> {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'myapp/css/table_style.css' %}"> … -
Combining two serializer into one
I have a ListApiView where i list the data on a website and on the same page i could select the records and export to xl and pdf file here right now i am using same serializer called ListingSerializer for exporting the data to file and listing it, for listing the data and exporting the fields are same except for exporting i have two additional fields to be exported but right now i need two serializers one for listing ListingSerializer and other for exporting ExportSerializer without repeating the fields. class ListingSerializer(serializers.ModelSerializer): class Meta: model = Mymodel fields = '__all__' class ExportSerializer(serializer.ModelSerializer): date_records_received = serializers.SerializerMethodField() class Meta: model = Mymodel fields = '__all__' Class Mylist(ListAPIView): def get_queryset(): return queryset def get_serializer(): serializer = ListingSerializer(self.get_queryset(), many=True, context={'request': self.request}) return serializer -
When I access the page, nothing appears
question I want to use the following code to filter the data in models.py in views.py and output the Today_list to today.html, but when I open this url, nothing is displayed. What is the problem? class Post(models.Model): created =models.DateTimeField(auto_now_add=True,editable=False,blank=False,null=False) title =models.CharField(max_length=255,blank=False,null=False) body =models.TextField(blank=True,null=False) def __str__(self): return self.title from Todolist import models from django.views.generic import ListView from django.utils import timezone class TodayView(ListView): model = models.Post template_name ='Todolist/today.html' def get_queryset(self): Today_list= models.Post.objects.filter( created=timezone.now()).order_by('-id') return Today_list {% extends "Todolist/base.html" %} {% block content %} {% for item in Today_list %} <tr> <td>{{item.title}}</td> </tr> {% endfor %} {% endblock %} urlpatterns=[ path('today/' ,views.TodayView.as_view() ,name='today')] -
Failed building wheel for psycopg2 (Windows 11)
I am building a Django project, and as I was installing the psycopg2(using virtual env), I kept getting an error. Versions: Django==4.1.2 Python==3.11.0 PIP==22.3 OS==Win11 Code: (env) PS C:\Users\keiko\Desktop\project> pip install psycopg2 Error: ERROR: Failed building wheel for psycopg2 Running setup.py clean for psycopg2 Failed to build psycopg2 Installing collected packages: psycopg2 Running setup.py install for psycopg2 ... error note: This error originates from a subprocess, and is likely not a problem with pip. error: legacy-install-failure I have already tried the solutions I found on the internet like: Install psycopg2-binary instead. Code: pip install psycopg2-binary Error: Failed building wheel for psycopg2-binary Upgrade the wheel and setup tools Code: pip install --upgrade wheel pip install --upgrade setuptools pip install psycopg2 Install it with python Code: python -m pip install psycopg2 ERROR: Failed building wheel for psycopg2 Install the Microsoft C++ Build Tools ... but still none of these solutions helped me. I'm really hoping to install the package(psycopg2) on my project, I've been stuck with this error for so long and I can't really find any solution to this. I hope someone can help me with this. -
Beginner in Django, I would like to know how to retrieve the fields of the Consultation table starting from the Students table?
This is the error I get ProgrammingError at /Action/PassagePerso/19E000183/ operator does not exist: character varying = numeric LINE 1: ...on", public."Actions_students" WHERE matricule_id = 19E00018... ^ HINT: No operator matches the given name and argument types. You might need to add explicit type casts. Request Method: GET Request URL: http://127.0.0.1:8000/Action/PassagePerso/19E000183/ Django Version: 4.1.2 Exception Type: ProgrammingError Exception Value: operator does not exist: character varying = numeric LINE 1: ...on", public."Actions_students" WHERE matricule_id = 19E00018... ^ HINT: No operator matches the given name and argument types. You might need to add explicit type casts. Exception Location: /home/jasonfofana/D/Workspace/PYTHON/Projects/Pharmacy_school/venv/lib/python3.10/site-packages/django/db/backends/utils.py, line 89, in _execute Raised during: Actions.views.ConsultationPersonnelle Python Executable: /home/jasonfofana/D/Workspace/PYTHON/Projects/Pharmacy_school/venv/bin/python Python Version: 3.10.4 Python Path: ['/home/jasonfofana/D/Workspace/PYTHON/Projects/Pharmacy_school', '/usr/lib/python310.zip', '/usr/lib/python3.10', '/usr/lib/python3.10/lib-dynload', '/home/jasonfofana/D/Workspace/PYTHON/Projects/Pharmacy_school/venv/lib/python3.10/site-packages'] Server time: Wed, 02 Nov 2022 02:42:05 +0000 I would like to use the two tables Consultation and Students in relations to display the information of a person def ConsultationPersonnelle(request, pk_student): student = Students.objects.get(pk=pk_student) consult = Students.objects.raw(f'SELECT * from public."Actions_consultation", public."Actions_students" WHERE matricule_id = {student.matricule} and matricule = {student.matricule}') context = {'consultant': consult} return render(request, 'consult_perso.html', context) -
CSS files loaded but got not rendered Django Rest Framework
I have a Django app with Gunicorn and Nginx deployed on AWS ECS. NGINX can load static files but the page still shows only text. Nginx: server { listen 80; listen [::]:80; server_name api.example.com; location /health { access_log off; return 200; } proxy_read_timeout 300; proxy_connect_timeout 300; proxy_send_timeout 300; # Main app location / { if ($request_method !~ ^(GET|POST|HEAD|OPTIONS|PUT|DELETE|PATCH)$) { return 405; } include /etc/nginx/mime.types; proxy_pass http://example-api:8000; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $http_x_forwarded_proto; proxy_set_header X-Forwarded-Port $http_x_forwarded_port; } location /static/ { autoindex on; alias /my_app/static/; } } In settings.py STATIC_URL = '/static/' STATIC_ROOT = '/my_app/static/' When I inspect the webpage, all CSS files are loaded, no 404 (It was an issue before but I fixed that). So not sure what else I am missing here. The UI works fine when running without Nginx and runserver, but on AWS ECS, I use gunicorn.