Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
File "<frozen importlib._bootstrap>", No module name 'material' | AWS ec2 instance, django project
~/blog/blog$ python3 manage.py makemigrations Traceback (most recent call last): File "/home/ubuntu/blog/blog/manage.py", line 22, in <module> main() File "/home/ubuntu/blog/blog/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/ubuntu/.local/lib/python3.10/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line utility.execute() File "/home/ubuntu/.local/lib/python3.10/site-packages/django/core/management/__init__.py", line 416, in execute django.setup() File "/home/ubuntu/.local/lib/python3.10/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/ubuntu/.local/lib/python3.10/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/home/ubuntu/.local/lib/python3.10/site-packages/django/apps/config.py", line 193, in create import_module(entry) 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 1004, in _find_and_load_unlocked ModuleNotFoundError: No module named 'material' when i tried to run this coomand makemigrations on aws ec2 for my django project, it appeared No module named 'material' how can I fix this problems? -
DJANGO - python manage.py inspectdb - ERROR - TypeError: translation() got an unexpected keyword argument 'codeset'
I have a database with tables and relationships between those tables in MySQL Workbench and I am trying to connect/integrate with Django. I have specified it settings.py in my Django project: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'data_storage', 'USER': 'root', 'PASSWORD': 'my_password', 'HOST': 'localhost', 'PORT': '3306', } } When I run python manage.py inspectdb or python manage.py inspectdb > DjangoWebPage/models.py in (VS Code) terminal, it shows an ERROR: TypeError: translation() got an unexpected keyword argument 'codeset' Full prompt: (.venv) PS C:\Users\Prakse\Desktop\DjangoApp> python manage.py inspectdb Traceback (most recent call last): File "C:\Users\Prakse\Desktop\DjangoApp\manage.py", line 22, in <module> main() File "C:\Users\Prakse\Desktop\DjangoApp\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\Prakse\Desktop\DjangoApp\.venv\Lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\Prakse\Desktop\DjangoApp\.venv\Lib\site-packages\django\core\management\__init__.py", line 357, in execute django.setup() File "C:\Users\Prakse\Desktop\DjangoApp\.venv\Lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Prakse\Desktop\DjangoApp\.venv\Lib\site-packages\django\apps\registry.py", line 112, in populate app_config.import_models() File "C:\Users\Prakse\Desktop\DjangoApp\.venv\Lib\site-packages\django\apps\config.py", line 198, in import_models self.models_module = import_module(models_module_name) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Prakse\AppData\Local\Programs\Python\Python311\Lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1206, in _gcd_import File "<frozen importlib._bootstrap>", line 1178, in _find_and_load File "<frozen importlib._bootstrap>", line 1149, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 690, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 940, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "C:\Users\Prakse\Desktop\DjangoApp\.venv\Lib\site-packages\django\contrib\auth\models.py", line 94, … -
Filtering objects by date
My app has an optional date selection. All objects created on that day will be filtered by the selected date. I have a model: class MyModel(models.Model): name = = models.CharField() ... pub_date = models.DateTimeField(auto_now_add=True) Objects will be added every day and there will be a lot of them in the future. I planned to implement filtering with something like this: object = MyModel.objects.filter(pub_date__year=year pub_date__month=month, pub_date__day=day) But it occurred to me that if I make a separate model for the date, link it to the main model and filter by related_name, then the query will be more optimal and faster. class PubDateModel(models.Model): pub_date = models.DateTimeField(auto_now_add=True) class MyModel(models.Model): name = = models.CharField() ... pub_date = models.ForeignKey(PubDateModel, related_name='my_models') If I understand correctly, then my request will look like this: pub_date = get_object_or_404(PubDateModel, pub_date=date) objects = pub_date.my_models.all() Which option will be faster with a very large number of objects in the database? -
Page not found (404) at /user_signup in Django
Getting 404 error on signup and some more URLs. /login, /logout, /admin is working perfectly. I'm making a web app that lets a user login, logout, search a flight, book a flight and view the bookings made. urls.py from django.urls import path from . import views urlpatterns = [ path('', views.home, name='home'), path('search_flights/', views.search_flights, name='search_flights'), path('book_flight/<int:flight_id>/', views.book_flight, name='book_flight'), path('my_bookings/', views.my_bookings, name='my_bookings'), path('login/', views.user_signup, name='login'), path('signup/', views.user_signup, name='signup'),] views.py from django.shortcuts import render, redirect from django.contrib.auth.forms import AuthenticationForm, UserCreationForm from django.contrib.auth import authenticate, login from django.contrib.auth.decorators import login_required from .models import Flight, Booking from django.contrib.auth.forms import UserCreationForm from .forms import SignUpForm, SignInForm, EditProfileForm def home(request): flights = Flight.objects.all() return render(request, 'home.html', {'flights': flights}) @login_required def search_flights(request): if request.method == 'POST': date = request.POST.get('date') time = request.POST.get('time') flights = Flight.objects.filter(date=date, time=time) return render(request, 'search_flights.html', {'flights': flights}) return render(request, 'search_flights.html') @login_required def book_flight(request, flight_id): flight = Flight.objects.get(id=flight_id) if request.method == 'POST': # Check if seats are available if flight.seats_available() > 0: # Book the ticket booking = Booking.objects.create(flight=flight, user=request.user) return redirect('my_bookings') else: # Show error message return render(request, 'book_flight.html', {'flight': flight, 'error': 'No seats available.'}) return render(request, 'book_flight.html', {'flight': flight}) @login_required def my_bookings(request): bookings = Booking.objects.filter(user=request.user) return render(request, 'my_bookings.html', {'bookings': bookings}) def user_login(request): … -
Why am I getting 403 for POST with DRF and rest_framework_api_key?
I am getting a 403 response from the server in my new Django app. It is very simple. I don't even have models, I just want to return an audio file, but I want to do it through an API. Because of that, since I am not going to have users, I need an API key, and I found that I can use the Django REST framework and the REST framework API key modules. I have followed the quickstarts and can't seem to get a response. It was working before, but it was authenticating through CSRF, and like I said, it is going to be an API, so I won't have CSRF cookies. Here is the view I am using: @api_view(["POST"]) def tts_view(request): data = request.POST voice_name = data.get("voice_name") text = data.get("text") if not voice_name or not text: return JsonResponse({"error": "Missing voice_name or text"}, status=400) return JsonResponse({"wav": text_to_wav(voice_name, text)}, status=200, safe=False) The settings: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework_api_key', 'TTS', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] REST_FRAMEWORK = { "DEFAULT_PERMISSION_CLASSES": [ "rest_framework_api_key.permissions.HasAPIKey", ] } And the fetch (the API key is just a test, so it doesn't matter): fetch('/create-speech', … -
An issue with OTP verification while using python-social-auth
I am attempting to implement a third-party login flow that redirects to an OTP verification screen before redirecting to a dashboard screen. It seems that after completing the OTP verification, when you use the command return redirect(reverse('social:complete', args=(backend_name,))), an 'AuthMissingParameter' error occurs with the message 'Missing needed parameter state'. I am not sure what's wrong with my code, any tips/suggestions are greatly appreciated. setting.py django_settings.SOCIAL_AUTH_PIPELINE = [ 'common.djangoapps.third_party_auth.pipeline.parse_query_params', 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.auth_allowed', 'common.djangoapps.third_party_auth.pipeline.show_otp_form', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.user.create_user', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', ] pipeline.py @partial.partial def show_otp_form(strategy, details, backend, request, *args, **kwargs): is_pass_otp = strategy.session_get("is_pass_otp", None) if not is_pass_otp: request.session['backend_name'] = request.backend.name return redirect('otp') views.py def otp_form(request): if request.method == 'POST': ....logic verify code OTP........ request.session['is_pass_otp'] = True backend_name =request.session['backend_name'] return redirect(reverse('social:complete', args=(backend_name,))) return TemplateResponse(request, 'otp/otp.html', {}) -
Django HTTPS on EC2 without a domain name?
I have a Django app working on HTTP with an EC2 instance running Amazon Linux 2. I was hoping to get HTTPS working without a domain name. How would I get a self signed certificate to work with the public IPv4 address assigned to my EC2 instance and then launch the django app on EC2 with HTTPS? Is it even possible? I have tried making a certificate using openssl and running the django app using django-extensions and Werkzeug using python manage.py runserver_plus but the app crashes on ec2 (works fine locally). I have tried a few other python packages with the same results. Any help is appreciated. -
Why coming this error: UnicodeDecodeError at /api/image/
My goal is to show the image's URL in response but it's not working. I getting errors. Here actually is it possible to return request.data.get('img')? Can you please give me a solution? serializer.py: class ImageSerializer(serializers.Serializer): img = serializers.ImageField(required=False) views.py: class ImageView(APIView): def post(self, request): serializer = ImageSerializer(data=request.data) return Response( { "processed_image_data": request.data.get('img') }, status=status.HTTP_200_OK ) errors: UnicodeDecodeError at /api/image/ 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte Request Method: POST Request URL: http://127.0.0.1:8000/api/image/ Django Version: 4.2 Exception Type: UnicodeDecodeError Exception Value: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte Exception Location: D:\23_Spondon-Bhai\2_Image-Process\venv\lib\site-packages\rest_framework\utils\encoders.py, line 50, in default Raised during: app.views.ImageView Python Executable: D:\23_Spondon-Bhai\2_Image-Process\venv\Scripts\python.exe Python Version: 3.9.5 Python Path: ['D:\\23_Spondon-Bhai\\2_Image-Process', 'c:\\users\\dcl\\appdata\\local\\programs\\python\\python39\\python39.zip', 'c:\\users\\dcl\\appdata\\local\\programs\\python\\python39\\DLLs', 'c:\\users\\dcl\\appdata\\local\\programs\\python\\python39\\lib', 'c:\\users\\dcl\\appdata\\local\\programs\\python\\python39', 'D:\\23_Spondon-Bhai\\2_Image-Process\\venv', 'D:\\23_Spondon-Bhai\\2_Image-Process\\venv\\lib\\site-packages'] Server time: Wed, 19 Apr 2023 17:23:42 +0000 Unicode error hint The string that could not be encoded/decoded was: ���� Traceback Switch to copy-and-paste view D:\23_Spondon-Bhai\2_Image-Process\venv\lib\site-packages\django\core\handlers\exception.py, line 55, in inner return inner else: @wraps(get_response) def inner(request): try: response = get_response(request) … except Exception as exc: response = response_for_exception(request, exc) return response return inner Local vars D:\23_Spondon-Bhai\2_Image-Process\venv\lib\site-packages\django\core\handlers\base.py, line 220, in _get_response self.check_response( response, middleware_method, name="%s.process_template_response" % (middleware_method.__self__.__class__.__name__,), ) try: response = response.render() … except Exception as e: response = … -
Cannot Configure (Error While) Django setting in nginx
My server cannot find the files, it says no files found . I have following configuration user www-data; worker_processes auto; pid /run/nginx.pid; include /etc/nginx/modules-enabled/*.conf; events { worker_connections 768; } http { sendfile on; tcp_nopush off; tcp_nodelay off; keepalive_timeout 265; types_hash_max_size 2000; and Server is server { listen 8000; server_name joshna.co www.joshna.co joshna.net www.joshna.net; location = /favicon.ico { access_log off; log_not_found off; } location /static/{ autoindex on; alias /home/bsyal/mysite/mypro/static; } location /media/{ autoindex on; alias /home/bsyal/mysite/mypro-project/static; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } Server cannot find file, I have gone thhrough others solution but could not figured out -
Rest API create class based view using a mixin
I have a view inheriting from APIView and another custom mixin. None of the APIView methods is defined in the view but it is used only for declaring it as view. I need the url from only the mixin. But the mixin's url is never found django.urls.exceptions.NoReverseMatch. I am not sure how exactly to explain the problem therefore, I will provide the code: class TypeAPI(TwoFieldListMixin, APIView): queryset = Type.objects.all() permission_classes = [IsAuthenticated] class TwoFieldListMixin: query_field: str = "id" name_field: str = "name" @action(detail=False, methods=["GET"], url_name="id_code_list") def id_code_list(self, request: Request, *args: None, **kwargs: Any) -> Response: self.query_field = ( request.query_params.get("query_field", None) or self.query_field ) self.name_field = ( request.query_params.get("name_field", None) or self.name_field ) queryset: QuerySet[Any] = self.filter_queryset(self.get_queryset()).values( self.query_field, self.name_field ) serializer: ICListSerializer = ICListSerializer(queryset, many=True) return Response(serializer.data) url.py urlpatterns = [ path("types/", TypeAPI.as_view(), name="types"), ] + router.urls Test that I am writing: def test_pt_detail_api(self)->None: res = self.client.get(f"/api/v1/na/types/id_code_list/") res = self.client.get(url) assert res.status_code == 200 Here is the error: /usr/local/lib/python3.10/site-packages/django/urls/resolvers.py:802: NoReverseMatch django.urls.exceptions.NoReverseMatch: Reverse for 'types-id_code_lis... Or applying some variations give an error: 'request_path': '/api/v1/na/types/id_code_list/', 'exception': 'Resolver404'} Question is how can I achieve creating a simple view which inherits from a mixin and does nothing else. -
Can anyone help me figure out what's happening with this html
So i am making this ecommerce for fun and got this weird bug That is html for new-skincare.html page. But then i have this perfumes page which is exactly the same as skincare page i just changed filter options in html so instead {% for skincare_item in skincare %} i used {% for perfume in perfumes %} . This is skincare.html {% extends 'base.html' %} {% block new_products%} {% load static %} {% load item_sizes %} <section class="page-header"> <div class="container"> <div class="row"> <div class="col-md-12"> <div class="content"> <h1 class="page-name">New Arrivals</h1> <ol class="breadcrumb"> <li><a href="{% url 'product-list'%}">Home</a></li> <li class="active">new skincare</li> </ol> </div> </div> </div> </div> </section> <section class="products section"> <div class="container"> <div class="row"> <div class="col-md-3"> {% block widget %}{% include 'widget.html'%}{% endblock widget%} </div> <div class="col-md-9"> <div class="row"> {% for item in skincare %} {% if item.is_new %} <div class="col-md-4"> <div class="product-item"> <div class="product-thumb"> <!-- TODO: CHANGE PRICE IF SALE --> {% if item.sale %} <span class="bage">Sale</span> {% endif %} {% if item.is_new %} <span class="new">New</span> {% endif %} {% load display_image %} {% static 'base/static/catalog/sku/'|add_str:item.front_image|add_str:'.webp' as front_image %} <img class="img-responsive" src="{{front_image}}" alt="product-img" /> {% comment %} {% endfor %} {% endcomment %} <div class="preview-meta"> <ul> <li> <span data-toggle="modal" data-target="#itemModal{{forloop.counter}}"> <i class="tf-ion-ios-search-strong"></i> … -
Dict in Django TemplateView throws Server Error 500, ListView helps for DetailView
I'm attempting to utilise the dictionary prices to retrieve the stock prices from yahoo finance. And the Django database is where I get my stock tickers. In HTML, I am unable to utilise dict. Please review the code samples I've included below. If the datatype for the variable "prices" is likewise a dict, Django produces a 500 server error. I need to pull stock prices from yahoo finance and show stock tickers from the Django database in HTML. How can I fix it? Please give me some advice on how to show my coins using ListView. In order to assist me with DetailView, which is crucial to my online application. I want to say thank you. Model: class Coin(models.Model): ticker = models.CharField(max_length=10) def __str__(self): return self.ticker View: class BucketView(LoginRequiredMixin, TemplateView): template_name = 'coinbucket/bucket.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) symbols = [symbol.ticker for symbol in Coin.objects.all()] prices = {} for symbol in symbols: ticker = yf.Ticker(symbol) price = ticker.history(period='1d')['Close'][0] prices[symbol] = f'$ {price:.6f}' context["prices"] = prices return context Template: {% for coin in coins %} <div class="col-12 col-md-8 my-2"> <div class="card"> <div class="card-body"> <div class="row"> <div class="col">{{ coin }}</div> <div class="col">{{ prices[coin] }}</div> </div> </div> </div> </div> {% endfor %} … -
Reference Serializer fields from Model in Django Rest Framework
The usual way of creating ModelSerializer in Django Rest Framework is specifying the fields attribute: class MyModelSerializer(serializer.ModelSerializer): class Meta: model = ModelConfig fields = ( 'id', 'uid', 'hashid', 'created_at', 'updated_at', 'added_by', 'updated_by', 'qr_code',) However in bigger projects, refactoring can be easier if the fields can be referenced through their Model, instead of specifying them as a string literal. However I don't know how this could be done in the most OOP way. I have tried using Model._meta.get_field(field) but this also only accepts the field_name, not a reference to the attribute. Something like Model.field.name would be great. Is this somehow possible? -
JavaScript returns value on the first review only, l don't know why
Am having a problem but l nor know what brings it. When I try to loop the Django to for JavaScript to display the Stars, it returns only on the first review and the rest it returns nothing. Now what can't do so that each user who adds a rating it displays it's stars not displaying only the first one? Below it's my HTML and JavaScript below Even l added also an image for results if try to reflesh the page. Html {% for review in reviews %} <p>display of numbers </p> <option value="{{ review.rating }}" id="hours"></option> <div class="staz"> <p id="demo"></p> {% endfor %} JavaScript <script> let hour = document.getElementById('hours').value; let greetings; if (hour == 1){ greetings = "★"; } else if (hour == 2){ greetings = "★★" } else if(hour == 3){ greetings = "★★★" } else if(hour == 4){ greetings = "★★★★" } else if(hour == 5){ greetings = "★★★★★"; } document.getElementById('demo').innerHTML = greetings </script> Results I expected that each review, it returns it's stars. -
Django deploy never completes on render.com
I have created app on Django. It works locally. Now I am trying to deploy it on render.com. Although, build is successful deploy never completes: Apr 19 05:33:01 PM 128 static files copied to '/opt/render/project/src/myproject/staticfiles'. Apr 19 05:33:03 PM Operations to perform: Apr 19 05:33:03 PM Apply all migrations: admin, auth, avito, contenttypes, sessions Apr 19 05:33:03 PM Running migrations: Apr 19 05:33:03 PM No migrations to apply. Apr 19 05:33:04 PM ==> Uploading build... Apr 19 05:33:13 PM ==> Build uploaded in 8s Apr 19 05:33:13 PM ==> Build successful 🎉 Apr 19 05:33:13 PM ==> Deploying... Apr 19 05:33:44 PM ==> Starting service with 'cd ./myproject && gunicorn --bind 0.0.0.0:8000 --workers=2 --preload --log-level debug myproject.wsgi' Apr 19 05:33:55 PM [2023-04-19 17:33:55 +0300] [51] [INFO] Starting gunicorn 20.1.0 Apr 19 05:33:55 PM [2023-04-19 17:33:55 +0300] [51] [DEBUG] Arbiter booted Apr 19 05:33:55 PM [2023-04-19 17:33:55 +0300] [51] [INFO] Listening at: http://0.0.0.0:8000 (51) Apr 19 05:33:55 PM [2023-04-19 17:33:55 +0300] [51] [INFO] Using worker: sync Apr 19 05:33:55 PM [2023-04-19 17:33:55 +0300] [61] [INFO] Booting worker with pid: 61 Apr 19 05:33:55 PM [2023-04-19 17:33:55 +0300] [62] [INFO] Booting worker with pid: 62 Apr 19 05:33:55 PM [2023-04-19 17:33:55 +0300] … -
I cant runserver from manage.py in Django
i want to runserver from my manage.py file for my Django project but i gives me error i should say that my graphic is old(Nvidia Geforce 9500gt) and the OpenGL version its : 1.1 , i think the error is for the open gl and i need a better graphic card but see my error. My python version is : 3.8 and my django is : 4.2 and my vs code is : 1.70 July 2020 I used this code for runserver: .\manage.py runserver i should say that i cant use the python before the manage.py .manage.py runserver because my vs code is old and it gives me error! but when i use the first code this error happend in my terminal: [2612:0419/191928.798:ERROR:gl_surface_egl.cc(808)] EGL Driver message (Error) eglCreateContext: Requested GLES version (3.0) is greater than max supported (2, 0). [2612:0419/191928.798:ERROR:gl_context_egl.cc(352)] eglCreateContext failed with error EGL_SUCCESS as i say my graphic card is old. -
Getting error while install django-autofixture
[getting error while installing django-fixture, tried pip install django-fixture, tried pip3, tried specific version of autofixture still getting error "AttributeError: 'UltraMagicString' object has no attribute 'endswith' [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: metadata-generation-failed × Encountered error while generating package metadata. ╰─> See above for output." ](https://i.stack.imgur.com/RHxRR.png) -
Error while deploying Django with mod_wsgi
I'm trying to deploy my django project with mod_wsgi. My site config: <VirtualHost *:80> ServerName djangoproject.com ServerAlias www.djangoproject.com DocumentRoot /home/djangoproject ErrorLog /home/djangoproject/logs/back-error.log CustomLog /home/djangoproject/logs/back-access.log combined <Directory /home/djangoproject/djangoproject> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess djangoproject.com python-path=/home/djangoproject/ python-home=/home/djangoproject/venv WSGIProcessGroup djangoproject.com WSGIScriptAlias / /home/djangoproject/djangoproject/wsgi.py </VirtualHost> But im getting error ModuleNotFoundError: No module named 'django' My project structure: /home/djangoproject /djangoproject ... wsgi.py /venv /logs manage.py What am i doing wrong? -
Django: How can I use subquery and annotate with 2 tables in 2 different databases in Django?
I have Table 1 in database1 and Table2 in database2. I try to use annotate and subquery like bellow but it's not work. from django.db.models import Subquery, OuterRef, Count from app1.models import Table1 from app2.models import Table2 subquery = Table2.objects.filter(table1_id=OuterRef('id')).values('table1_id').annotate(count=Count('id')).values('count') queryset = Table1.objects.annotate(table2_count=Subquery(subquery, output_field=models.IntegerField()), using='database1') The error is: QuerySet.annotate() received non-expression(s): database1. -
Generate a PDF with FPDF with content from django-website
I'm trying to run a Python code that are using the FPDF- library to produce a pdf with some simple text. def example(request): .... generatePDF(parameter1, parameter2, parameter3) ... return HttpResponse("PDF generated") def generatePDF(x,y,z): import fpdf from FPDF pdf = FPDF pdf = FPDF('L", "mm", "A4") pdf.addpage() ... ... ... pdf.output("test.pdf", "F") The Django-code without do run perfectly smoothly itself, and the function for PDF- production runs without problem when I call it in the terminal. But when I try to use the PDF function inside a Django view, I only get an Error 500 in return. Why is this happening? -
How to show __str__ representations for existing Inline objects in the admin UI, but still use the form for adding new objects
I have a Django Admin view with a number of inlines. The 'Add another ' works as expected and brings up an empty form to fill in the values. Once added though, it shows that related object in form view, and all fields on all inlines remain editable. What I'd like to achieve is that all existing objects are listed in their __str__ representation, but the 'Add another' button still brings up the form. Can this be done in Django Admin, or am I looking for too much? -
Keep on getting this error message when trying to run my django server: [Errno 2] No such file or directory
I'm trying to run my django server but keep on getting this error, [Errno 2] No such file or directory. I tried using the cd manage.py command but also got this error cd : Cannot find path 'C:\Users\nyaknoiton\Desktop\Django 2\manage.py' because it does not exist. -
Django model for ordered list with polymorphic relations
I am trying to figure out the way to implement a Django model for optical/mechanical simulations for photovoltaic modules and glazing units. The simplest real-life representation of the problem looks like this: Position Material 1 Glass 2 EVA foil 3 Solar cells 4 EVA foil 5 PVF Here is my idea of the data representation: The class PVmodule class handles has the ForeignKey field referencing its composition like so: class PVmodule(models.Model): #---components---# composition = models.ForeignKey(ModuleComposition,related_name="composition",on_delete=models.CASCADE) The class ModuleComposition is an abstraction of an optical stack (as in the table above) - set of ordered materials like glass, gas, coatings and polymers... each represented by separate django model. Upon save() it handles optical calculations based on the ManyToMany relation with the StackItem class and fills in its' remaining fields with data automatically: class ModuleComposition(models.Model): self.stack = models.ManyToManyField(StackItem) The StackItem class is a representation of a single material on a specific position. It relates via ForeignKey to a table handling the specific material parameters. class StackItem(models.Model): self.position = models.PositiveIntegerField() self.material = models.ForeignKey( ... ) I would like this allows the user to define the module composition step by step or to an already existing module composition for quick evaluation. However, I cannot … -
Automatically update and render item quantity on cart update
I have been working on my cart functionality but I cannot seem to get the cart item.quantity to automatically update without a page refresh. I'm wondering how I could modify the code below to not only update my CartIcon but update specific item quantity too or whether I need a new function/util entirely. Here is the HTML snippet with the variable {{item.quantity}} I would like to automatically update when the quantity is changed. <svg class="icon--cart change-quantity update-cart" data-product="{{item.product.id}}" data-action="add" > <use href="/media/sprite.svg#plus-solid"/> </svg> {{item.quantity}} <svg class="icon--cart change-quantity update-cart" data-product="{{item.product.id}}" data-action="remove"> <use href="/media/sprite.svg#minus-solid"/> </svg> Here is a util I made for updating the Cart Icon number in my header: @login_required def get_cart_quantity(request): cart = get_object_or_404(Cart, user=request.user) quantity = sum(item.quantity for item in cart.items.all()) return JsonResponse({'quantity': quantity}) Here is my current script that successfully updates my CartIcon: function updateCartQuantity() { fetch("/get_cart_quantity/") .then((response) => response.json()) .then((data) => { document.getElementById("cart-quantity").textContent = data.quantity; }) .catch((error) => { console.error("Error fetching cart quantity:", error); }); } // Call updateCartQuantity when the page loads and after adding an item to the cart window.addEventListener("load", updateCartQuantity); Below is the quantity field I want to automatically update, so it is specific to the item, not the whole cart quantity. -
Limit the number of objects in django TabularInline
I use Django, and I want create a TabularInline showing a maximum of 10 results You can configure it with max_num and extra, but that does not limit the results. They have a special section on "Limiting the number of editable objects". Where they say "max_num does not prevent existing objects from being displayed". But also not how its actually done. I can also not overwrite the get_queryset method because Django does a filter later and then I get TypeError: Cannot filter a query once a slice has been taken. Does anyone know how I can do this?