Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Case insensative search/filter in django
at my Search class of django project I try to get products query from db but it case sensative not matter what i tried, i still can not enhance my search query maybe not that way to solution, i will find a possible way to get it right but one and biggest broblet that i use Sqlite3 wher is method (name__icontains=search_query) not valid, i mean valid but does not work part of Search class: def get_queryset(self): search_query = self.request.GET.get('q') print(f"start q {search_query}") print(Product.objects.filter(name__icontains=search_query)) print(repr(search_query),"----------") if search_query: # Filter products where label contains the search query (case-insensitive) return Product.objects.filter(name__icontains=search_query) else: return Product.objects.none() -
Why is Django prefetch_related resulting in 100s of extra SQL queries?
My relationships are as follows: A Portfolio has a many 2 many relationship to LoanTape through PortfolioLoanTapes A Quote has many LoanTapes A Quote has many Documents I am trying to query a Portfolio and all its related starred documents in a GET portfolio API call in DRF ModelViewSet. models.py class Portfolio(models.Model): loan_tapes = models.ManyToManyField("LoanTape", through="PortfolioLoanTapes") class PortfolioLoanTapes(models.Model): portfolio = models.ForeignKey(Portfolio, on_delete=models.PROTECT) loan_tape = models.ForeignKey(LoanTape, on_delete=models.PROTECT) class LoanTape(models.Model): portfolios = models.ManyToManyField("Portfolio", through="PortfolioLoanTapes") quote = models.ForeignKey("Quote", on_delete=models.PROTECT, blank=False, null=False, related_name="loan_tapes") class Quote(models.Model): ... class Document(models.Model): quote = models.ForeignKey(Quote, on_delete=models.PROTECT, related_name="documents") is_starred = models.BooleanField(default=False) view.py def get_queryset(self): starred_documents_qs = Document.objects.filter(is_starred=True) quotes_prefetch = Prefetch('quote__documents', queryset=starred_documents_qs, to_attr='starred_documents') loan_tapes_prefetch = Prefetch('portfolioloantapes_set__loan_tape', queryset=LoanTape.objects.prefetch_related(quotes_prefetch)) qs = Portfolio.objects.prefetch_related(loan_tapes_prefetch).filter(deleted__isnull=True) return qs serializer.py class PortfolioDetailSerializer(serializers.ModelSerializer): loan_tapes = PortfolioLoanTapeSerializer(many=True, read_only=True, source="portfolioloantapes_set") class PortfolioLoanTapeSerializer(serializers.ModelSerializer): def to_representation(self, instance): ret = super().to_representation(instance) ret.update(LoanTapeSerializer(instance.loan_tape).data) return ret class LoanTapeSerializer(serializers.ModelSerializer): image_url = serializers.SerializerMethodField() def get_image_url(self, instance): if starred_docs := getattr(instance.quote, 'starred_documents', []): return starred_docs[0].url test.py (missing some setup objects) def test_retrieve_query_count(self): with self.assertNumQueries(4): response = self.client.get(f"/api/v1/portfolios/{portfolio.id}/", **self.headers) self.assertEqual(response.status_code, 200) When asserting the number of queries in the test above, Django is making 224 DB calls!! Are my prefetch objects not setup correctly? Is there a more efficient path in the prefetch? I'm quite lost and can't seem … -
Django crispy form how to format while typing
super_amount = models.DecimalField( max_digits=20, decimal_places=2, default=Decimal(0), ) {{ form.super_amount|as_crispy_field }} I have this field in my form but I want this field to be formatted with commas while typing in browser. So if I write 123456789, it will be shown like this everytime I write a number: 1 -> 12 -> 123 -> 1,234 -> 12,345 -> ... -> 123,456,789 https://stackoverflow.com/a/39279790/14253522 I tried to use this but after 6 digit, field clears itself. I tried to work around this problem but wasn't able to solve it. -
NGINX and Django not in debug serving some static files and some no
I am experiencing some weird behaviour after switching off DEBUG on Django, behind NGINX reverse proxy. I am testing it on a Armbian Linux with Python 3.7.3. Django project has the manage.py inside the folder folder configuration is - /var/webserver/backend - manage.py - backend - settings.py - static - img (contains collected plus my logo and favicon) - admin (the collected admin files) The NGINX configuration is as following (the static part, the rest is a reverse proxy with a self signed certificate): location /static { autoindex on; autoindex_exact_size off; alias /var/webserver/backend/static; } The settings.py static part is as following, staticfiles app is in the APPS: STATIC_URL = '/static/' STATIC_ROOT = BASE_DIR / 'static' I run the manage.py command while in the /var/webserver/backend directory, nginx is ran as service. I think I have tried all combinations of "slashes" both inside the NGINX configuration and settings.py (before, after, both, none) This configuration is the nearest to work, the situation is the following: The logo.png and favicon.ico inside the static/img folder are displayed correctly all the css, js or others are not loaded (page is completely without style) There are no 404 in the logs (either Django or NGINX access.log shows 200). … -
Django apps have circular dependency, causes foreign key models not to migrate
I have two django apps that have foreign keys to each other An api app and another app called blog Here is my models.py for the blog app class Post(models.Model): uuid = models.UUIDField(default=uuid.uuid4, primary_key=False, unique=True) title = models.CharField(max_length=600) authors = models.ManyToManyField('Author', related_name='authors') tags = models.ManyToManyField('Tag', related_name='tags') date_published = models.DateField(auto_now_add=True) # store table of contents as JSON table_of_contents = models.TextField(default=dict) # s3 link to thumbnail thumbnail = models.URLField(max_length=300) # each post belongs to a blog blog = models.ForeignKey('api.Blog', on_delete=models.CASCADE, default=0) slug = models.SlugField(max_length=100, default='') # store markdown as text content = models.TextField(default='') # link to post url = models.URLField(default='') # for json serialization def as_dict(self): return { "title": self.title, "slug": self.slug, "authors": [ author.as_dict() for author in self.authors.all() ], "tags": [ tag.as_dict() for tag in self.tags.all() ], "date_published": "01/01/2001", "table_of_contents": self.table_of_contents, "thumbnail": self.thumbnail, "id": str(self.uuid), } def __str___(self): return self.title class Author(models.Model): name = models.CharField(max_length=100) blog = models.ForeignKey('api.Blog', on_delete=models.CASCADE, default=0) def as_dict(self): return { "name": self.name, "profile": self.name } def __str__(self): return self.name class Tag(models.Model): name = models.CharField(max_length=50) blog = models.ForeignKey('api.Blog', on_delete=models.CASCADE, default=0) def as_dict(self): return { "name": self.name } def __str__(self): return self.name And my models.py for my "api" app class Blog(models.Model): # Foreign key to the associated tenant in … -
Django objects.get not working when using the request data
I couldn't understand why this code isn't working: I'm currently using Django as cms, and nextjs as fronted: while I was testing the get request i had a lot of trouble to make the Member.objects.get(firstname='Alessia') working and also filter doesn't work at all. from django.http import HttpResponse from django.http import JsonResponse from rest_framework.response import Response from rest_framework.views import APIView from rest_framework.decorators import api_view from simulazione.models import * from simulazione.api.serializers import * @api_view(['GET']) def get_data(request): nome = request.GET.get('name', None) try: dear = Member.objects.get(firstname=nome) serializer = MemberSerializer(dear) data = {'hello': 'hello2'} return JsonResponse(serializer.data) except: print("Server error") Everytime I run this, i get this error: AssertionError at /simulazione/api/get_data/ Expected a Response, HttpResponse or HttpStreamingResponse to be returned from the view, but received a <class 'NoneType'> -
Django view caching: how to set expire at time?
I would like to cache some view until end of month. e.g. @cache_page_expire_at_end_of_month def some_view(request): ... I found this old question Django per-view caching: set expiry time rather than cache timeout? But I can't get it to work. -
Difficulty Establishing Secure Connection Between Web Server and MQTT Server
I'm currently working on a project for monitoring robots, and I've developed a web platform using Django and Vue for data acquisition and visualization. At present, I'm utilizing an MQTT server to transmit all my data. However, I've encountered an issue while trying to configure communication between my web page, which has an SSL certificate generated by Certbot, and the MQTT server implemented on a Raspberry Pi 4. I've attempted to generate an SSL certificate for MQTT using OpenSSL, but I've been unsuccessful in establishing a connection between the web server and the MQTT server. It seems that the web page doesn't allow unencrypted connections with the MQTT server. I'm employing the WebSocket protocol for this connection. Additionally, I'm unable to use Certbot to generate an SSL certificate for the Raspberry Pi, as I don't have my own domain for the Raspberry Pi's IP address. Does anyone have any ideas about what might be happening or any alternative methods for securely establishing this connection? Thanks in advance for your assistance. When attempting to establish the connection between my web server and the MQTT server, I used an SSL certificate generated by Certbot on the web server and tried to generate … -
What's an easy and safe way to provide users access to MySQL database so they can interact with it (CRUD)?
I'm creating a database for a small community and would like to set up a web interface for them to interact with it. I'd like users to be able to use a password to access their own records for changes. Also I assume there's a way to assign users to groups to be able to access a wider set of rows. Someone mentioned Django and I see that there are other possibilities like PHP. I have database experience, but little experience with web pages. I don't have much javascript or CSS. I haven't tried anything yet. I'm still considering how to start. -
Postgres15 Grant All on schema public not workiing
My code used to work fine with postgres 12, now with postgres 15 my django project can't run migrations. I found many answers suggesting to GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO <user>, but it does not work for me as shown: Below the user named django needs to be able to create tables in the public schema, so it can run migrations: sudo -u postgres psql could not change directory to "/home/john/project/src": Permission denied psql (15.6 (Debian 15.6-0+deb12u1)) Type "help" for help. postgres=# GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO django; GRANT postgres=# \q (project) john@vps-demo:~/project/src$ psql -U django my_db Password for user django: psql (15.6 (Debian 15.6-0+deb12u1)) Type "help" for help. my_db=> CREATE TABLE test_table1 (id INT); ERROR: permission denied for schema public LINE 1: CREATE TABLE test_table1 (id INT); ^ my_db=> -
function on Django to check user in database
I want to write a function to check a user in the database, can anyone help? can someone help i am learning Django I try many ways but ... ------------view.py---------------- def user_enter(request): print("hello") if request.method == "POST": enter_user_email=request.POST.get('enter_user_email') enter_user_pass=request.POST.get('enter_user_pass') print(enter_user_pass) print(enter_user_email) data=User.objects.filter(email_name = enter_user_email,user_password = enter_user_pass).exists() return render(request, 'main.html',{'data':data}) --------------HTML--------------- <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.3.1/dist/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <link rel="stylesheet" href="static/css/style.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> </head> <body> <div class="container mx-auto mt-2" style="width: 500px;" id="input_name_pass"> <img src="static/user.png" alt="..." id='user_image' class="img-thumbnail mx-auto" style="width: 200px;"> <form action="" method = "POST"> {% csrf_token %} <div class="input-group input-group-sm mb-3 mt-4"> <div class="input-group-prepend"> <span class="input-group-text" id="inputGroup-sizing-sm">User</span> </div> <input type="text" class="form-control" aria-label="Small" aria-describedby="inputGroup-sizing-sm" name = "enter_user_email"> </div> <div class="input-group input-group-sm mb-3"> <div class="input-group-prepend"> <span class="input-group-text" id="inputGroup-sizing-sl">Pass</span> </div> <input type="password" class="form-control" aria-label="Small" aria-describedby="inputGroup-sizing-sm" name = "enter_user_pass"> </div> <button type="submit" class="btn btn-primary mt-3" onclick="location.href='{% url 'user_enter' %}'">Enter</button> </form> <button type="button" class="btn btn-primary mt-3" onclick="location.href='{% url 'user_registration' %}'">Create User</button> </div> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.14.7/dist/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.3.1/dist/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script> </body> </html> -
zero tasks are running in Celery with supervisor
I am using Celery with Django, and it works perfectly fine when I use the celery command and run the worker and beat individually, but when I use supervisor to run Celery as a daemon, no tasks start running. supervisorctl status all [sudo] password for ahmed: beat RUNNING pid 22064, uptime 1:29:20 worker RUNNING pid 22063, uptime 1:29:20 celery.conf file in /etc/supervisor/conf.d/celery.conf ; ========================================== ; celery worker config ; ========================================== [program: worker] command=/home/ahmed/.local/bin/celery -A decimal_trade worker -l info directory=/home/ahmed/PycharmProjects/decimal-trade user=ahmed numprocs=1 stdout_logfile=/home/ahmed/PycharmProjects/decimal-trade/celery/log/worker.log stderr_logfile=/home/ahmed/PycharmProjects/decimal-trade/celery/log/worker.err.log autostart=true autorestart=true startsecs=10 stopwaitsecs = 600 killasgroup=true priority=998 ; priority 998 executes first and then 999 ; ======================================== ; celery beat config ; ======================================== [program: beat] command=/home/ahmed/.local/bin/celery -A decimal_trade beat -l info directory=/home/ahmed/PycharmProjects/decimal-trade user=ahmed numprocs=1 stdout_logfile=/home/ahmed/PycharmProjects/decimal-trade/celery/log/beat.log stderr_logfile=/home/ahmed/PycharmProjects/decimal-trade/celery/log/beat.err.log autostart=true autorestart=true startsecs=10 stopwaitsecs = 600 killasgroup=true priority=999 The worker log -------------- celery@ahmed-Lenovo-V14-G1-IML v5.3.6 (emerald-rush) --- ***** ----- -- ******* ---- Linux-6.2.0-39-generic-x86_64-with-glibc2.35 2024-03-14 18:19:37 - *** --- * --- - ** ---------- [config] - ** ---------- .> app: decimal_trade:0x7fa64756c3d0 - ** ---------- .> transport: redis://localhost:6379/0 - ** ---------- .> results: redis://localhost:6379/0 - *** --- * --- .> concurrency: 4 (prefork) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- -------------- [queues] … -
@api_view method not works but post method works django rest api
I have imported django_restframework.decorators from api_view @api_view(['POST']) def post_cart(self,request): serializer = CartItemSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response({"status": "success", "data": serializer.data}, status=status.HTTP_200_OK) else: return Response({"status": "error", "data": serializer.errors}, status=status.HTTP_400_BAD_REQUEST) curl -X POST -H "Content-Type: application/json" http://127.0.0.1:8000/api/cart-items/ -d "{\"product_name\":\"name\",\"product_price\":\"41\",\"product_quantity\":\"1\"}" When I use @api_view(['GET']) I get this error { "detail": "Method \"POST\" not allowed." } But When I change like this it works def post(self,request): serializer = CartItemSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response({"status": "success", "data": serializer.data}, status=status.HTTP_200_OK) else: return Response({"status": "error", "data": serializer.errors}, status=status.HTTP_400_BAD_REQUEST) curl -X POST -H "Content-Type: application/json" http://127.0.0.1:8000/api/cart-items/ -d "{\"product_name\":\"name\",\"product_price\":\"41\",\"product_quantity\":\"1\"}" It returns success 200 { "status": "success", "data": { "id": 5, "product_name": "item", "product_price": 12.5, "product_quantity": 5 } } -
Django REST Framework login and logout views
I'm building a system using django, django rest framework, django oauth toolkit, django axes in a microservices architecture but I have some doubts. Currently I have my "login" view on the client that takes the username and password from the POST request and sends it to my "UserLoginAPI" API, in the "UserLoginApi" view I validate the user and password in the "UserLoginSerializer" serializer, I check if the user is not blocked in django axes and I create a token for this user with oauth, the serializer returns the authenticated user and the token and "UserLoginApi" updates the last_login with update_last_login, I saw in a discussion on stackoverflow that it should be used update_last_login instead of login(request, user), then I return the token back to the "login" view on the client, and on the client I take this token and store it in the session and with middleware I check in each request if the token exists and if the token exists, if it has already expired, if it exists and has not expired, I update the session user with the user associated with the token. And at logout I do the same thing but I use logout(request) to log out … -
how to install mysqlclient in windows?
I am a windows 10 user, for my django project when i try to download mysqlclient module it displays error , i tried various strategies, please help me. C:\Users\sachin>pip install mysqlclient Collecting mysqlclient Using cached mysqlclient-2.1.1.tar.gz (88 kB) Using legacy setup.py install for mysqlclient, since package 'wheel' is not installed. Installing collected packages: mysqlclient Running setup.py install for mysqlclient ... error ERROR: Command errored out with exit status 1: command: 'c:\users\sachin\appdata\local\programs\python\python37-32\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\Users\sachin\AppData\Local\Temp\pip-install-ye9s3zyg\mysqlclient\setup.py'"'"'; file='"'"'C:\Users\sachin\AppData\Local\Temp\pip-install-ye9s3zyg\mysqlclient\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' install --record 'C:\Users\sachin\AppData\Local\Temp\pip-record-yz3e0ytd\install-record.txt' --single-version-externally-managed --compile --install-headers 'c:\users\sachin\appdata\local\programs\python\python37-32\Include\mysqlclient' cwd: C:\Users\sachin\AppData\Local\Temp\pip-install-ye9s3zyg\mysqlclient Complete output (29 lines): running install running build running build_py creating build creating build\lib.win32-3.7 creating build\lib.win32-3.7\MySQLdb copying MySQLdb_init_.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb_exceptions.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\connections.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\converters.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\cursors.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\release.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\times.py -> build\lib.win32-3.7\MySQLdb creating build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants_init_.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\CLIENT.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\CR.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\ER.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\FIELD_TYPE.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\FLAG.py -> build\lib.win32-3.7\MySQLdb\constants running build_ext building 'MySQLdb.mysql' extension creating build\temp.win32-3.7 creating build\temp.win32-3.7\Release creating build\temp.win32-3.7\Release\MySQLdb C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\VC\Tools\MSVC\14.38.33130\bin\HostX86\x86\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -Dversion_info=(2,1,1,'final',0) -D__version_=2.1.1 "-IC:\Program Files (x86)\MariaDB\MariaDB Connector C\include\mariadb" "-IC:\Program Files (x86)\MariaDB\MariaDB Connector C\include" … -
Null value set to True, but still it violates not-null constraint
I am trying to set a null sidebar from the Django admin interface as shown below: However, when I press "Save" I get an IntegrityError error: IntegrityError at /admin/qa/howquestion/112/change/ null value in column "sidebar_id" violates not-null constraint DETAIL: Failing row contains (112, <p>prettyprint a JSON file<br></p>, To pretty print a JSON file in Python, you can use the json m...). It's strange because null is set to True: sidebar = models.ForeignKey(Sidebar, on_delete=models.SET_NULL, related_name='qa_sidebars',null=True, blank=True) And I have applied migrations too. Please note that the error does not happen in development where an SQLite3 database is used. This only happens in deployment where I am using a PostGreSQL database. I have ran out of options. I searched everything and still don't understand this. Anyone can help? -
How do I save the pasword as hashed password in postgressql database
I have created a custom user model Employee in Django that extends AbstractBaseUser. The Employee model has a password field of type CharField. I am using PostgreSQL as the database. When creating a new Employee instance using the EmployeeManager.create_employee method and providing a plaintext password, the password is not being saved as a hashed value in the PostgreSQL database. Instead, it is being stored as plaintext. Here's the relevant code: model.py from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager from django.db import models from django.utils import timezone from django.utils.translation import gettext_lazy as _ from django.contrib.auth.hashers import make_password, check_password class OrganizationManager(BaseUserManager): def create_organization(self, email, name, **extra_fields): if not email: raise ValueError(_('The Email field must be set')) email = self.normalize_email(email) organization = self.model(email=email, name=name, **extra_fields) return organization class Organization(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) name = models.CharField(_('name'), max_length=150) is_active = models.BooleanField(_('active'), default=True) date_joined = models.DateTimeField(_('date joined'), default=timezone.now) groups = models.ManyToManyField( 'auth.Group', related_name='org_groups', # Custom related name for Organization blank=True, help_text=_( 'The groups this organization belongs to. A user will gain all permissions granted to each group.'), ) user_permissions = models.ManyToManyField( 'auth.Permission', related_name='org_user_permissions', # Custom related name for Organization blank=True, help_text=_('Specific permissions for this organization.'), ) password = None # Override the password field … -
Django + React Development Setup for a Hybrid App
I'm using Django + React hybrid setup. Django does not simply act as a backend to API but actually renders pages. The setup works in production with some urls routed to Django's templating system and others (starting with 'app/') rendered from index.html + static files from React build. This works in production. However, I'm trying to get Django development server (localhost:8000) work with react development server (localhost:3000) as follows. Django backend Urls.py urlpatterns = [ # React urls re_path(r'^app/.*',views.application,name='application'), # Django urls path("", include("my_app.urls")), ] Views.py def application(request, upstream='http://127.0.0.1:3000'): upstream_url = upstream + request.path with urllib.request.urlopen(upstream_url) as response: content_type = response.headers.get('Content-Type') # print('CONTENT TYPE: ',content_type) if content_type == 'text/html; charset=UTF-8': response_text = response.read().decode() content = engines['django'].from_string(response_text).render() else: content = response.read() return HttpResponse( content, content_type=content_type, status=response.status, reason=response.reason, ) React frontend App.js function App() { const HomePage = () => { return (<h1>Home Page</h1>); } const TestPage= () => { return (<h1>Test Page</h1>); }; return ( <BrowserRouter> <Routes> <Route path="app/" element = {<HomePage/>}/> <Route path="app/test" element = {<TestPage/>}/> </Routes> </BrowserRouter> ); }; .env PUBLIC_URL = app Both /app and app/test urls are accessible on port 3000. However, on port 8000 where Django development server is running I can only get /app while … -
Updating Cart Total Amount Dynamically After Adding Items with AJAX in Django is not working properly
I created a cart item total section for my website <div class="col-md-4"> <div class="cart-item total-section"> <h3>Subtotal: <span class="total">$50.00</span></h3> <h3>Discount: <span class="total">$50.00</span></h3> <h3>Shipping: <span class="total">Free</span></h3> <h3>Total: <span class="total">{{cart_total_ammount}}</span></h3> <button class="btn btn-checkout">Proceed to Checkout</button> </div> </div> In the above code I am taking total ammount of the cart In " <h3>Total: <span class="total">{{cart_total_ammount}}</span></h3> " this line for this I created a javascript file So, In function.js: $("#add-to-cart-btn").on("click",function(){ let quantity=$("#product-quantity").val() let product_title=$(".product-title").val() let product_id=$(".product-id").val() let product_price = $("#current-product-price").text() let product_image = $(".product-image").val() let product_pid=$(".product-pid").val() let this_val=$(this) console.log("Quantity:", quantity); console.log("Id:", product_id); console.log("PId:", product_pid); console.log("Image:", product_image); console.log("Title:", product_title); console.log("Price:", product_price); console.log("Image URL:", product_image); console.log("Current Element:", this_val); $.ajax({ url: '/add-to-cart', data: { 'id': product_id, 'pid': product_pid, 'image':product_image, 'qty': quantity, 'title': product_title, 'price': product_price }, dataType: 'json', beforeSend: function(){ console.log("Adding products to cart"); }, success: function(res){ this_val.html("Go to Cart") console.log("Added products to cart"); $(".cart-items-count").text(res.totalcartitems) $(".total").text(res.cart_total_ammount) //#p } }) }) In the above javascript file you can see that I created the cart_total_ammount section. But it is not working I mean that instade of taking cart_total_ammount it is taking totalcartitems and In my views.py: def cart_view(request): cart_total_ammount=0 if 'cart_data_obj' in request.session: for p_id, item in request.session['cart_data_obj'].items(): cart_total_ammount+= int(item['qty']) item['image'] = request.session['cart_data_obj'][p_id]['image'] # add this line return render(request, "core/cart.html",{"data":request.session['cart_data_obj'],'totalcartitems': … -
Blacklisting Network Range on django-blacklist
I've noticed recently that my django-website is being crawled by a number of spammy bots, so while looking for a way to block this IP-range I came across django-blacklist. It works well for the most part, and I've successfully blocked single IPs, but when I tried to block a range (51.222.253.0 - 51.222.253.255), it seems to be unsuccessful. My inputs were: Address = 51.222.253.0 & Prefixlen = 24 (see image below). I've read the docs, and can't seem to get more clarity on this topic, however, this isn't a strong suit of mine so let me know if I've done something wrong. All help is appreciated! -
Django application experiencing "CSRF token missing" error specifically for POST requests when deployed with Nginx and Gunicorn
I've deployed a Django application using Nginx and Gunicorn, and I'm encountering a "CSRF token missing" error specifically for POST requests. Here's a brief overview of my setup: I've deployed my Django application on an Ubuntu server using nginx and gunicorn. My Django app worked perfectly when using it locally, but now on the server I only get this error when doing POST requests: { "detail": "CSRF Failed: CSRF token missing." } [This is the tutorial we followed to set everything up on our server] (https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu) For authentication we use django_auth_adfs (microsoft). These are my setup files: nginx/sites-available/<our_project>: server { server_name <our_domain.com>; ignore_invalid_headers off; underscores_in_headers on; location / { root <location/to/frontend>; } location /oauth2/ { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } location /login_redirect { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } location ~ \.well-known { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } location /api/ { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } location /admin/ { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/sel2-4.ugent.be/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/sel2-4.ugent.be/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host = <our_domain.com>) { return 301 https://$host$request_uri; } # managed by Certbot … -
I got a "Field 'id' expected a number but got 'h'." error while submitting a form with a video url(many to one) in Django
I am new coding in Python and using Django, and I am having troubles in my project when submiting the form including a video url I get this error : "ValueError at /edit_account_details/5/ Field 'id' expected a number but got 'h'. Request Method: POST Request URL: http://127.0.0.1:8000/edit_account_details/5/ Django Version: 4.2.10 Exception Type: ValueError Exception Value: Field 'id' expected a number but got 'h'. Exception Location: C:.\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\fields_init_.py, line 2055, in get_prep_value Raised during: core.views.edit_profile Python Executable: C:.\AppData\Local\Programs\Python\Python39\python.exe Python Version: 3.9.13 Python Path: ['C:\...\Dessoc\dessoc', 'C:\.\AppData\Local\Programs\Python\Python39\python39.zip', 'C:\.\AppData\Local\Programs\Python\Python39\DLLs', 'C:\.\AppData\Local\Programs\Python\Python39\lib', 'C:\.\AppData\Local\Programs\Python\Python39', 'C:\.\AppData\Local\Programs\Python\Python39\lib\site-packages'] Server time: Wed, 13 Mar 2024 21:28:03 +0000" if I leave the url field empty it work perfect, My code for model is: class Account(models.Model): profile = models.ForeignKey(Profile, on_delete=models.CASCADE) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) date_of_deceased = models.DateField() rest_location_coordinates = models.CharField(max_length=255) rest_location_info = models.TextField(blank=True) biography = models.TextField(blank=True) photo_gallery = models.ManyToManyField('Photo') video_gallery = models.ManyToManyField('Video') guestbook_entries = models.ManyToManyField(GuestbookEntry, blank=True, related_name='account_guestbook_entries') def __str__(self): return f"{self.first_name} {self.last_name} - {self.profile.user.username}" class Photo(models.Model): account_id = models.ForeignKey(Account, on_delete=models.CASCADE) title = models.CharField(max_length=255) image = models.ImageField(upload_to='photos/') def __str__(self): return self.title class Video(models.Model): account_id = models.ForeignKey(Account, on_delete=models.CASCADE) title = models.CharField(max_length=255) video_url = models.URLField() def __str__(self): return self.title def save_form_data(self, instance, data): if data is None: return # Check if 'video_url' is present in … -
Template is not working correctly in Django
I am trying to create a page for logistic company where a user can request a quote through this page. I am trying to implement a page where I can click on an add product button and then it will allow me to choose the product from the dropdown menu and then let me specify a quantity for it. this is my models.py from django.db import models from phonenumber_field.modelfields import PhoneNumberField from django.utils import timezone from .states import STATE_CHOICES,prod_choices class Product(models.Model): name = models.CharField(max_length=100,choices=prod_choices, unique=True) def __str__(self): return self.name class Quote(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=60) email = models.EmailField() address=models.CharField(max_length=150) ph_num= PhoneNumberField() state=models.CharField(max_length=45,choices=STATE_CHOICES,default="State") city=models.CharField(max_length=20,default="City") pincode = models.CharField(max_length=10) created_at = models.DateTimeField(auto_now_add=True) order_id=models.CharField(max_length=255, unique=True,default="#") process_status=models.BooleanField(default="False") def generate_order_id(self): state_abbreviation = self.state[:3].upper() city_abbreviation = self.city[:3].upper() current_datetime = timezone.now().strftime('%Y%m%d%H%M%S') order_id = f"{state_abbreviation}_{city_abbreviation}_{self.name}_{current_datetime}" return order_id def __str__(self): return f"Quote {self.id}" class QuoteProduct(models.Model): quote = models.ForeignKey(Quote, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.PositiveSmallIntegerField(default=0) def __str__(self): return f"{self.product.name} - {self.quantity}" This is my forms.py from django import forms from .models import Quote from .models import QuoteProduct class QuoteForm(forms.ModelForm): class Meta: model = Quote fields = ['name', 'email', 'address', 'ph_num', 'state', 'city', 'pincode'] class QuoteProductForm(forms.ModelForm): class Meta: model = QuoteProduct fields = ['product', 'quantity'] This is my … -
Django Adding Square Brackets In Admin-Related Views
I am hosting two Django applications on a webserver and I recently upgraded all my packages to more recent versions, along with bringing the project to Python 3.12, which was generally beneficial. In doing so, I noticed that square brackets ("[]") started appearing in seemingly random views associated with admin views. To be specific, when looking at individual models in the admin view AND on the sign-in page, which I believe Django admin heavily handles. It's not mission critical to solve, and there's nothing in the source code that I know of that would cause this, and no code changes were made apart from upgrading versions. I would think it's some random setting I have to turn off but I've spent a good amount of time trying to figure it out. Admin Model View Example 1 Admin Model View Example 2 Admin Login Standard Login I've tried going in a bringing the version down on a couple of packages, but there a multitude of packages in the dependencies and for the sake of where I'd like to take the project, I'd want it to use updated versions of packages as there are certain features I can't utilize properly unless both … -
how can i solve postman error in django web app?
i have a django web app. when i try to post a request in post man i get some errors. what is the solution?[enter image description here](https://i.stenter image description hereack.imgur.com/mWggv.png)[[enter image description here](https://i.stack.imgur.com/zxIS0.png)](https://i.stack.imgur.com/55VfT.png) i tried many times for solving this problem but everytime i got 500 internal errors in postman.