Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
is ther any alternative way for doing chain filtering in django?
I have a django model named news and another django model named tag that there is a many to many relationship between them. But when I want to filter my news models by several tags, i need to do chain filtering and it is not useful when i am trying to filter news by a list of tags. is there any other way to do that? this is my models.py file: from django.db import models # Create your models here. class tag(models.Model): tag_name = models.CharField(max_length=200) def __str__(self): return self.tag_name class news(models.Model): title = models.CharField(max_length=200) text = models.TextField() tags = models.ManyToManyField(tag) source = models.URLField() def __str__(self): return self.title and this is the way that i use to filter news: >>> news.objects.filter(tags__tag_name='tech').filter(tags__tag_name='politic') instead of this i want to do something like this: >>> news.objects.filter(tags__tag_name__contains=['tech', 'plitics']) and i have to mention that i am using sqlite database and i cannot change my database. -
mpl3.fig_to_html() not displaying figure on the web page
So I am working on a project that involves the use of the Python matplotlib library. After creating the figures and adding all plots, I need to save them in a pdf file using PdfPages in matplotlib.backends.backend_pdf. The pdf was created and the figures are displayed correctly. Now I add the pdf file to a dictionary by first encoding it to base64 and updating the dictionary with the figures using mpld3 library' mpld3.fig_to_html() function to convert them to html string. I return them as a JSON response and send it to the client side and use JavaScript to append the figures converted to html string to the page. But in this case, the page is not displaying the figures, I check the DevTools and the following has been appended to the page but the div that should contain the figure is empty. Kindly help me out. Thanks <div id="4ad2c70a-c848-4596-8549-7c82445df602"> <style> </style> <div id="fig_el15321405099995608808193094769"></div> <script> function mpld3_load_lib(url, callback){ var s = document.createElement('script'); s.src = url; s.async = true; s.onreadystatechange = s.onload = callback; s.onerror = function(){console.warn("failed to load library " + url);}; document.getElementsByTagName("head")[0].appendChild(s); } if(typeof(mpld3) !== "undefined" && mpld3._mpld3IsLoaded){ // already loaded: just create the figure !function(mpld3){ mpld3.draw_figure("fig_el15321405099995608808193094769", {"width": 800.0, "height": … -
'NoneType' object has no attribute 'pk' in Django
i was trying to use bulk_create so that i can save to the database, but i have written the code which can save only one data but when i want to save multiple it gives me this error "NoneType object has no attribute 'pk'" I have tried this, and my expectation was to save all shares at once according to number of members def new_share(request): success_count = 0 group = GroupMember.objects.filter(user=request.user).first() attendance = Attendance.objects.filter(group=group,meeting__date=date.today()) config = ConfigurationData.objects.filter(group=group).first() members = Member.objects.filter(group=group, is_active=True) for member in members: member.created_at = member.created_at.strftime('%Y-%m-%d') members_json = json.dumps(list(members.values()),default=str) attendance_data = [ {'member_id': data.member.id, 'attended': data.attended} for data in attendance ] if not attendance: messages.warning(request,f'Please make sure you have take an attendance for this meeting before you buy a share.') if request.method == 'POST': member_ids = [key.split('_')[-1] for key in request.POST.keys() if key.startswith('amount_of_share_')] print(member_ids) instances = [] for member_id in member_ids: member = get_object_or_404(Member,group=group,id=int(member_id)) amount_key = 'amount_of_share_'+ member_id amount = int(request.POST.get(amount_key,0)) print(f'amount is {amount} and for member {member}') if amount > 0: try: instances.append(ShareManagement.buyshare(request,value=amount,member=member.id)) success_count +=1 except Exception as e: messages.error(request,f"Error processing data for {member.memberID}: {str(e)}") print(f'Error processing data for {member.memberID}: {str(e)}') else: print(f'Process the fine for not buying a share for member {member.memberID}') print(instances) Share.objects.bulk_create(instances) if success_count … -
django_filters do not work with the viewset after updating to django 4.2.3 from django 2
I am trying to use django filters to filter results. The worked fine with the previous version but after updating to latest django version 4.2.3 filter is not working. Ordering, paggination and Search Filter works fine but filter based on fields returns all the results. url -> runs/?tags__name=test&status__ni=cancelled,failure,returned INSTALLED_APPS = [ "rest_framework", "django_filters", ] REST_FRAMEWORK = { 'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend') } class RunFilter(FilterSet): tags__name = django_filters.CharFilter(method="filter_by_tag_names") class Meta: model = Run fields = { "id": ["exact", "icontains", "in"], "name": ["exact", "icontains"], "workload__name": ["exact", "icontains"], "status": ["exact", "icontains", "ne", "regex", "ni", "in"], } @classmethod def filter_for_lookup(cls, f, lookup_type): if isinstance(f, models.DateField): return django_filters.CharFilter, {} # use default behavior otherwise return super().filter_for_lookup(f, lookup_type) def filter_by_tag_names(self, queryset, name, value): tags = value.split(",") query = queryset for tag in tags: query = query & queryset.filter(Q(tags__name__exact=tag)) return query class RunViewSet(viewsets.ReadOnlyModelViewSet): queryset = Run.objects.all().distinct() pagination_class = MyLimitOffsetPagination serializer_class = RunSerializer filter_backends = ( filters.DjangoFilterBackend, OrderingFilter, SearchFilter, ) filter_class = RunFilter ordering_fields = "__all__" ordering = ("-id",) search_fields = ( "id", "name", "workload__name", "status", "tags__name", ) Django==4.2.3 django-filter==23.2 -
passing multiple values to a single column name when filtering records in django
I'm trying to filter records in django. The issue is that I want to pass multiple values in the filter method. Example : brand = laptops.object.filter(brand__icontains="apple") In this example, as far as I know, I can pass one value to the brand__icontains. I want to filter the records with more than one value. Like filtering laptops based on brand like apple, dell, hp -
Django. GET request gets triggered after DELETE
I am creating a web app in django for the first time and one of the features is adding and editing vacancies. Some info is added using forms and POST method (title of the vacancy, description, etc.) And other fields are added and removed dynamically to the DOM and database with Fetch api (duties, offers, advantages). When loading the edit vacancy view, the duties, offers and advantages, as well as the form data are pre loaded from the database. The problem arises when trying to remove the pre-loaded duties, offers and advantages from the edit vacancy view. When i send a DELETE request, something is triggering a GET in the edit view, causing everything to reload. This is not ideal, since all previous user input is gone. This only occurs with the edit view, the new vacancy view works as intended with both adding and removing the dynamic fields without page refreshing. How can i prevent the DELETE request from the removeduty triggering the GET on edit ? And why could this be occuring ? edit views.py: @login_required(login_url="/login") def edit(request,id): if request.method =="POST": vacancy = Vacancy.objects.get(pk=id) newtitle = request.POST['title'] newcity = request.POST['city'] newcountry = request.POST['country'] newimage = request.FILES.get('image') newdescription = … -
I am making createDocotr function in angular component, I want to use list based on scpecialty_name and it will save to data specialty_id
i am making a project with DRF framework and Angular, i am stuck at 1 foreign key 'specialty_id' in models 'doctor', i try to load 'specialty_name' in html as a list and it will save itself as 'specialty_id', i have loaded 'specialty_name' on html but can't generate data with 'specialty_id' into models. i want 'specialty_name' field for user in html and it will save to models 'Doctor' with 'specialty_id' please someone help me My Models.py class specialty(models.Model): # chuyên khoa specialty_id = models.AutoField(primary_key=True) specialty_name = models.CharField(max_length=100) class doctor(models.Model): # bác sĩ dt_id = models.AutoField(primary_key=True) dt_name = models.CharField(max_length=100, blank=True) specialty_id = models.ForeignKey(specialty, on_delete=models.CASCADE) email = models.CharField(max_length=100, null=True) phone_dt = models.CharField(max_length=20, blank=False) password = models.CharField(max_length=50, blank=False) usertype = models.CharField(max_length=100, blank=True) image_dt = models.CharField(blank=True, max_length=400) My Serializer.py class specialtySerializer(serializers.ModelSerializer): class Meta: model = specialty fields = ( "specialty_id", "specialty_name", ) class doctorSerializer(serializers.ModelSerializer): specialty_name = serializers.CharField(source="specialty_id.specialty_name",read_only=True) class Meta: model = doctor fields = ( "dt_id", "dt_name", "specialty_id", "specialty_name", "email", "phone_dt", "password", "usertype", "image_dt", ) def to_representation(self, instance): representation = super(doctorSerializer, self).to_representation(instance) # Xóa trường specialty_id và giữ lại specialty_name trong đầu ra representation.pop('specialty_id') return representation My views.py class doctorViewSet(viewsets.ModelViewSet): def list(self, request): pass def retrieve(self, request, pk=None): pass def create(self, request): if request.method == … -
WebSocket Video Streaming Issue: Streamer Video Not Displaying on Viewer End
I'm currently working on a Django project that involves live video streaming using WebRTC and Django Channels. I've set up a WebSocket connection between the streamer and the viewer for exchanging offer and answer data, and the WebSocket connection seems to be working fine. However, I'm facing an issue where the streamer's video is not being displayed on the viewer's end. Here's a simplified overview of my setup: I have a Django application with Django Channels enabled. I'm using WebRTC for video streaming, and I've established a WebSocket connection between the streamer and the viewer. The viewer sends an offer to the streamer using the WebSocket connection, and the streamer responds with an answer. The viewer receives the answer through the WebSocket and sets up the peer connection to display the streamer's video. However, despite the WebSocket connection working correctly and the offer and answer being exchanged, the streamer's video is not being displayed on the viewer's end. I've verified the SDP data exchange and ensured that the MediaStream is assigned to the video element. stream.html {% load static %} <!DOCTYPE html> <html> <head> <title>Streamer Page</title> </head> <body> <h1>Streamer Page</h1> <video id="localVideo" autoplay muted></video> <button id="startStreamButton">Start Streaming</button> <div id="stream-container" data-offer-url="{{ … -
Permission Denied for Gunicorn
I in the middle of deploying a django apps in linode. I am new to this so I just follow tutorial from digital ocean. Link here When I tried to check gunicorn status with this sudo systemctl status gunicorn It will show this error Aug 07 08:29:53 localhost systemd[1]: Started gunicorn daemon. Aug 07 08:29:53 localhost systemd[50433]: gunicorn.service: Failed to execute /home/sammy/luzern_hikvision/myprojectenv/bin/gunicorn: Permission denied Aug 07 08:29:53 localhost systemd[50433]: gunicorn.service: Failed at step EXEC spawning /home/sammy/luzern_hikvision/myprojectenv/bin/gunicorn: Permission denied Aug 07 08:29:53 localhost systemd[1]: gunicorn.service: Main process exited, code=exited, status=203/EXEC Aug 07 08:29:53 localhost systemd[1]: gunicorn.service: Failed with result 'exit-code'. My gunicorn.service file have this [Unit] Description=gunicorn daemon After=network.target [Service] User=sammy Group=sammy WorkingDirectory=/home/sammy/luzern_hikvision ExecStart=/home/sammy/luzern_hikvision/myprojectenv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/run/gunicorn.sock luzern_vms.wsgi:application [Install] WantedBy=multi-user.target I did run chown -R sammy:sammy /home/sammy but still won't work. If I run ls -lah , I will get this total 36K drwxr-x--- 5 sammy sammy 4.0K Aug 7 05:53 . drwxr-xr-x 3 root root 4.0K Aug 7 05:30 .. -rw------- 1 sammy sammy 1.2K Aug 7 06:57 .bash_history -rw-r--r-- 1 sammy sammy 220 Aug 7 05:30 .bash_logout -rw-r--r-- 1 sammy sammy 3.8K Aug 7 05:53 .bashrc drwx------ 3 sammy sammy 4.0K Aug 7 05:51 .cache drwxrwxr-x … -
API arguments don't work together in my django function
Screenshot from Sqlite databaseI have a function which is called jobs_e. Purpose of the function is getting objects from sqlite database and shows with API in JSON form. In my function there are parameters to sort objects. command (to get objects with the same command name.) status (to get objects with the same status value.) API parameters -each (to set how many objects on per page.) -page (to set which page want you see.) FUNCTION: def jobs_e(request): command = request.GET.get('command', '') status = request.GET.get('status', '') per_num_from_user = request.GET.get('each', '') page_number_from_user = request.GET.get('page', 1) records = Result.objects.all().order_by('id') if command and status: records = records.filter(name=command, status=status) elif command: records = records.filter(name=command) elif status: records = records.filter(status=status) default_per_page = 20 if per_num_from_user: default_per_page = per_num_from_user else: pass paginator = Paginator(records, default_per_page) if page_number_from_user: page_number = page_number_from_user else: page_number = 1 current_page = paginator.page(page_number) response_data = { "history": [ { "ID": data.id, "Command Name": data.name, "Status": data.status, "Command": data.command, "Stime": data.start_time, "Etime": data.end_time, "File-DIR": data.file } for data in current_page ], "total_pages": paginator.num_pages, "current_page": current_page.number, "has_next": current_page.has_next(), "has_previous": current_page.has_previous(), } return HttpResponse(json.dumps(response_data, indent=2), content_type="application/json") -
buildx: failed to read current commit information with git rev-parse --is-inside-work-tree
I am getting this error after installing docker inside an existing project. Here is my dockerfile: FROM python:3.11 ENV PYTHONBUFFERED=1 WORKDIR /code COPY re.txt . RUN pip install -r re.txt COPY . . EXPOSE 8001 RUN apt-get update && apt-get install -y git RUN git config --global --add safe.directory . CMD ["python", "manage.py", "runserver"] Here is my docker-compose version: '3.11' services: django: image: leadbracket build: . ports: - "8001:8001" -
Shortlist and reject button not working properly
Whenever I click on buttons only the last one is working rest on the table buttons are not working Here is my html File `<div class="body table-responsive"> <form id="form" method="POST" action = "#"> {% csrf_token %} <table class="table table-hover" id="customers"> <thead> <tr> <th style="width: 1%;" >S No.</th> <th style="width: 10%;" >Name</th> <th style="width: 5%;" >Experience</th> <th style="width: 5%;" >Main Skills</th> <th style="width: 10%;" ><center>#</center></th> </tr> </thead> <tbody> {% for Application in Job.applications.all %} <tr> <th scope="row"> {{ forloop.counter }}</th> <td><a style="font-size: medium;" href="{% url 'application' Application.id %}">{{Application.created_by.username}}</a></td> <td>{{Application.Experience}}</td> <td>{{Application.Skills}}</td> <td><center> <input type="submit" value="Shortlist" name="status" > <input type="hidden" name="Application_id" value= "{{ Application.id }}"> <input type="submit" value="Reject" name="status"> </center></td> </tr> {% empty %} <p>No application for this job yet...</p> {% endfor %} </tbody> </table> </form> </div>` Here is my view file `def JobDashboard(request, jobs_id): Job = get_object_or_404(job, pk= jobs_id, created_by = request.user) print(request.method) if request.method == 'POST': query= Application.objects.get(id=request.POST.get("Application_id")) if request.POST.get("status"): status = request.POST.get('status') print(status) query.save() return render(request, "View_Dashboard_job.html", {"Job":Job})` In print status it gives whatever I clicked but not pushing to the database -
ModuleNotFoundError: No module named 'django_crontab'
I want to use crontab in Django to perform some scheduled tasks, but I'm encountering package import issues.I have already installed the crontab library, but when I add 'django_crontab' to the INSTALLED_APPS in the settings file and start Django, it results in an error. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'systemserver.apps.SystemserverConfig', 'corsheaders', 'openApi.apps.openApiConfig', 'django_crontab', ] Here is the error report: Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib/python3.6/threading.py", line 916, in _bootstrap_inner self.run() File "/usr/lib/python3.6/threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "/usr/local/lib/python3.6/dist-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python3.6/dist-packages/django/core/management/commands/runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "/usr/local/lib/python3.6/dist-packages/django/utils/autoreload.py", line 87, in raise_last_exception raise _exception[1] File "/usr/local/lib/python3.6/dist-packages/django/core/management/__init__.py", line 375, in execute autoreload.check_errors(django.setup)() File "/usr/local/lib/python3.6/dist-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python3.6/dist-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python3.6/dist-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/usr/local/lib/python3.6/dist-packages/django/apps/config.py", line 224, in create import_module(entry) File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked ModuleNotFoundError: No module named 'django_crontab' I tried this method, but it still doesn't work. import … -
Merging multiple data frames in django by pandas caused a problem, which has Nan value in the result
the problem is that when i did merging in the views.py in django, only one raw did not work for merging, the others did merging successfully. so i did same work in colab jupyter notebook,the result is a success, all raw showed proper results. <veiws.py> def analysis(request): memo_all=Memo.objects.all() #convert queryset to dataframe df_memo=pd.DataFrame(list(memo_all.values())) df_list=pd.read_excel(r'C:\Users\이택인\Desktop\KNOU\myproject\media\upload\sample_file.xlsx') df_list=df_list.query('출금액!=0') data=pd.merge(df_list,df_memo,how='left',left_on='적요', right_on='memo') return render(request, 'report/analysis.html', {'df_memo':df_memo.to_html(), 'df_list':df_list.to_html(),'data':data.to_html()}) I am so hurry to complete this work. Any response from you is very helpful. Thank you!! -
Trying to understand django, python, fly.io error Error: failed to fetch an image or build from source
I am trying to deploy my django blog using fly.io. I get the following error output and its talking about psycopg not running. now the thing is I have run pip install psycopg[binary] and pip install psycopg2 commands found here on stack overflow Working on new version of psycopg 3 and while installing psycopg[c] it wont install at all error: (.venv) andrewstribling@Andrews-MBP blog % flyctl deploy ==> Verifying app config Validating /Users/andrewstribling/Desktop/code/blog/fly.toml Platform: machines ✓ Configuration is valid --> Verified app config ==> Building image Remote builder fly-builder-snowy-morning-5375 ready ==> Building image with Docker --> docker host: 20.10.12 linux x86_64 [+] Building 0.5s (12/12) FINISHED => [internal] load build definition from Dockerfile 0.1s => => transferring dockerfile: 32B 0.1s => [internal] load .dockerignore 0.1s => => transferring context: 35B 0.0s => [internal] load metadata for docker.io/library/python:3.11-slim-bullseye 0.3s => [1/7] FROM docker.io/library/python:3.11-slim-bullseye@sha256:52c7a54aa5e5068ce76edaf3f8652a64fb99e378fb89fb0bfbe21a8756d0013c 0.0s => [internal] load build context 0.1s => => transferring context: 38.12kB 0.1s => CACHED [2/7] RUN mkdir -p /code 0.0s => CACHED [3/7] WORKDIR /code 0.0s => CACHED [4/7] COPY requirements.txt /tmp/requirements.txt 0.0s => CACHED [5/7] RUN set -ex && pip install --upgrade pip && pip install -r /tmp/requirements.txt && rm -rf /root/.cache/ 0.0s => CACHED [6/7] COPY … -
Unable to add search or filter functionality to HTML table populated with fetched data. - Django REST API/Svelte
I am trying to add search and filter functionality to a HTML table, which I populated with fetched data. I am using a fetch request inside a Svelte component to retrieve data from a Django REST API. This part is successful, the data populates the table as desired with no issues. Populated Table I have made several attempts to add search and filter functionality to the table. Upon research I've discovered that because the fetch request is asynchronous, the values are not stored on the DOM, thereby when I run a querySelectAll method, an empty nodelist is returned. From there I've made several attempts to try and store the fetched data locally and use that local data to populate the table, but none of my attempts have worked. I've tried pushing the fetched data to an empty list, then using that list to populate the table. I've tried using innerHTML methods to populate the table, as well as a few other attempts that didn't work. please see code snippets below Svelte component script tag <script> import { onMount } from 'svelte'; const endpoint = 'http://localhost:8000/testresults/'; export let results = [] const load = async function () { const jsonResponse = … -
objects.all(): Unresolved attribute reference 'objects' for class 'Products'
I'm starting to learn coding in python and I wanted to create a basic "shop", I seem to get stuck on this problem where the object.all() doesn't get recognized by PyCharm, I've already tried looking at other posts and documents but nothing helped me. I've already tried changing the way I import the "Product" class. PyCharm gives me a warning with a yellow underline under objects.all() where it says: Unresolved attribute reference 'objects' for class 'Product' When I run the views.py code there's an error message: Traceback (most recent call last): File "{my directory}\views.py", line 2, in <module> from .models import Product ImportError: attempted relative import with no known parent package models.py code from django.db import models class Product(models.Model): name = models.CharField(max_length=255) price = models.FloatField() stock = models.IntegerField() image_url = models.CharField(max_length=2083) views.py code from django.shortcuts import render from .models import Product def index(request): products = Product.objects.all() return render(request, "index.html", {"products": products}) Help would be appreciated, I'm really annoyed stuck on this. -
Getting MIME type error when deploying project online
I am getting the following error when I try to load a CSS file in my Django project: Refused to apply style from 'http://127.0.0.1:8000/assets/css/index-b4422385.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. I have tried to fix the problem by changing the MIME type of the file, but this has not worked. Here is my code: <html lang="en"> <head> <meta charset="UTF-8" /> <link rel="icon" type="image/svg+xml" href="/vite.svg" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Vite + React</title> <link rel="stylesheet" href="/assets/css/index-b4422385.css" type="text/css"> </head> <body> <div id="root"></div> <script type="module" crossorigin src="/assets/js/index-580b2f9b.js"></script> </body> </html> Here is my static file configuration: STATIC_URL = "static/" STATICFILES_DIRS = [ os.path.join(BASE_DIR, "staticfiles"), (os.path.join(BASE_DIR, "dist", "assets")), ] I have already built my React app. In my Django logs, I am receiving the following errors: Not Found: /assets/css/index-b4422385.css [06/Aug/2023 22:34:58] "GET /assets/css/index-b4422385.css HTTP/1.1" 404 3999 Not Found: /assets/js/index-580b2f9b.js [06/Aug/2023 22:34:58] "GET /assets/js/index-580b2f9b.js HTTP/1.1" 404 3993 I have tried adding the following setting to my settings.py file, but this has not worked: STATICFILES_MIMETYPES = { ".css": "text/css", } What am I doing wrong? Expected behavior: The CSS file should be loaded without any problems. Actual behavior: The CSS file is not loaded … -
Add to cart without reloading the page in Django with fetch()
i'm currently working in a e-commerce project with django in the backend. I have an "add to cart" functionality already implemented, but as I have it right now it reloads the page every time I add/delete/clear a product to the shopping cart. I'd like to make this without reloading the page. views.py: @login_required(login_url='login') def shopping_cart(request): if request.method == 'POST': customer = request.user.customer data = json.loads(request.body) product_id, action = data['product_id'], data['action'] product = Product.objects.get(id=product_id) order, created = Order.objects.get_or_create( customer=customer, completed=False) product_order, created = ProductOrder.objects.get_or_create( order=order, product=product) # It checks if it is the first time that the product is added to # the shopping cart and sends a messsage if created: sweetify.success(request, 'Product added to the cart', timer=2000) # Checks the button that was clicked (add, remove or clear) # If the action is add checks if there is enough stock of the # product, otherwise sends a message of not enough stock if action == 'add': if product_order.quantity == product.stock: sweetify.warning( request, 'Maximum products available!', timer=2000) else: product_order.quantity = product_order.quantity + 1 product_order.save() # If the action is remove it removes 1 product from the total # in the shopping cart if action == 'remove': product_order.quantity = product_order.quantity - 1 … -
Django project deployed to Google App Engine is 3X as large in GCloud as it is locally
I have a personal Django project that takes up 105.2 MB locally. Having deployed it to Google App Engine using these instructions, I got the following error: Exceeded hard memory limit of 384 MiB with 435 MiB after servicing 0 requests total. Consider setting a larger instance class in app.yaml. I changed the instance to F4 which has more memory than the default, and that fixed it. I'm curious why the app needs another 180MB of memory though. -
Orders and quotes with client register in django
`HTML: `{% csrf_token %} {{ form | crispy }} <select id="id_cliente" name="cliente" onchange="update_cliente_data()"> <option value="">Selecione um cliente...</option> {% for cliente in clientes %} {% with cliente_data=cliente.to_json %} <option id="opcao" value="{{ cliente.id }}" data-cliente="{% for key, value in cliente_data.items %}'{{ key }}': '{{ value|escapejs }}',{% endfor %}">{{ cliente.nome }}</option> {% endwith %} {% endfor %} </select>` SCRIPT: `<script> // Chamar a função update_cliente_data() quando o DOM é carregado document.addEventListener('DOMContentLoaded', function() { console.log('DOM carregado.'); update_cliente_data(); }); function update_cliente_data() { var clienteSelect = document.getElementById('id_cliente'); if (clienteSelect) { var selectedIndex = clienteSelect.selectedIndex; if (selectedIndex !== -1) { var clienteOption = clienteSelect.options[selectedIndex]; //var clienteOpcao = document.getElementById('opcao'); var clienteDataAttr = clienteOption.getAttribute('data-cliente'); //var clienteDataAttr = clienteOpcao.getAttribute('data-cliente'); if (clienteDataAttr) { try { var clienteData = JSON.parse(clienteDataAttr); document.getElementById('id_nome').value = clienteData.nome; document.getElementById('id_cpf').value = clienteData.cpf; document.getElementById('id_email').value = clienteData.email; document.getElementById('id_rg').value = clienteData.rg; document.getElementById('id_cidade').value = clienteData.cidade; document.getElementById('id_telefone').value = clienteData.telefone; document.getElementById('id_numero').value = clienteData.numero; document.getElementById('id_rua').value = clienteData.rua; document.getElementById('id_bairro').value = clienteData.bairro; } catch (error) { console.error('Erro ao analisar os dados do cliente:', error); } } else { console.error('Atributo "data-cliente" não encontrado no elemento selecionado.'); } } else { console.error('Nenhum item selecionado no select.'); } } else { console.error('Elemento com ID "id_cliente" não encontrado no DOM.'); } } </script>`` It all seems correctly for me, but the … -
Create a Profile model for a specific user (Django 4.0)?
Does anybody know how to create a Profile for the user upon completion of the registration form??? (Django) views.py: class UserRegisterView(generic.CreateView): form_class = SignUpForm #Imported from forms template_name = 'registration/register.html' success_url = reverse_lazy('login') def form_valid(self, form): response = super().form_valid(form) return response models.py class Profile(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) #rpg_class = models.CharField(max_length=100) def __str__(self): return str(self.user) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() I tried this and it doesnt work, It says something like Internal Server Error: /CodeRPGappMain/register/ Traceback (most recent call last): File "C:\Users\Admin\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\utils.py", line 89, in _execute return self.cursor.execute(sql, params) File "C:\Users\Admin\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\sqlite3\base.py", line 328, in execute return super().execute(query, params) sqlite3.IntegrityError: NOT NULL constraint failed: CodeRPGappMain_profile.bio Making a Profile manually in the admin isnt going to work So I need it to create itself automatically every time a user signs up, it already creates a user bc of Djangos built in stuff but I need to create its custom model Profile for the user upon completion -
Django Error EnvError Environment Variable Debug Not Set
I am working on Django for beginners and in Django for beginners I am told to create an .env file and have it exisit in the same root directory next to the existing .gitignore file. It teaches that we should never deploy a site into production with DEBUG turned on as it provides a treasure map for hackers to destroy or alter my website. Instead we want debug to be true for local development and false for production. In the instructions it says go into my .env file and set DEBUG=True without spaces and than for my django_project/settings.py file have the DEBUG = env.bool(“DEBUG”) I do this and I get the following error message ERROR MESSAGE: (.venv) andrewstribling@Andrews-MBP blog % python manage.py runserver Traceback (most recent call last): File “/Users/andrewstribling/Desktop/code/blog/manage.py”, line 22, in main() File “/Users/andrewstribling/Desktop/code/blog/manage.py”, line 18, in main execute_from_command_line(sys.argv) File “/Users/andrewstribling/Library/Python/3.9/lib/python/site-packages/django/core/management/init.py”, line 442, in execute_from_command_line utility.execute() File “/Users/andrewstribling/Library/Python/3.9/lib/python/site-packages/django/core/management/init.py”, line 382, in execute settings.INSTALLED_APPS File “/Users/andrewstribling/Library/Python/3.9/lib/python/site-packages/django/conf/init.py”, line 102, in getattr self._setup(name) File “/Users/andrewstribling/Library/Python/3.9/lib/python/site-packages/django/conf/init.py”, line 89, in _setup self._wrapped = Settings(settings_module) File “/Users/andrewstribling/Library/Python/3.9/lib/python/site-packages/django/conf/init.py”, line 217, in init mod = importlib.import_module(self.SETTINGS_MODULE) File “/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/importlib/init.py”, line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File “”, line 1030, in _gcd_import File “”, line 1007, … -
Django Queryset Lookup Encrypted Column
I have these 2 classes to encrypt and decrypt an email address in the postgres database using pgcrypto. They both work. One uses a postgres bytea column while the other uses a postgres varchar column. The problem though I face is though is this: >>> CustomUser.objects.filter(email="jbonte30@sunfuesty.com") <QuerySet []> CustomUser.objects.filter(username="jtwlucas").values_list("email", flat=True) <QuerySet ['jtwlucas@arshopshop.xyz']> >>> CustomUser.objects.filter(username="jtwlucas").values_list("email", flat=True) <QuerySet [None]> select PGP_SYM_DECRYPT(email::bytea, 'SECRET_KEY') from authentication_customuser; jtwlucas@arshopshop.xyz 'jtwlucas@arshopshop.xyz' in CustomUser.objects.values_list('email', flat=True) True` Even though that email address exists in the database. The database shows this for the varchar column: xc30d04090302b95c598cd3d427836dd24c01eb524973d9a2742acb4e24091faf0bb6507c338d97dcfac6fbfda038c34fc6bbd59ccad723acf4235c9825fe14981b7ae2e63fc79277cf442480f30249adefaa964b9f19be3592c9f0c219 The database shows this for the bytea column: [binary data] If possible I want the be able to perform the lookups as I am doing them in this example automatically without needing to change my entire code base's ORM querysets. I do not want to use any third party github libraries. #postgres bytea column class SecureEmail(models.EmailField): """Custom Encrypted Field""" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.secret_key = str(settings.SECRET_KEY) def from_db_value(self, value, expression, connection): # Decrypt value when reading from database if value is not None: cursor = connection.cursor() cursor.execute("SELECT pgp_sym_decrypt(%s::bytea, %s)::text", [value, self.secret_key]) return cursor.fetchone()[0] def get_prep_value(self, value): # Encrypt value when writing to database cursor = connection.cursor() cursor.execute("SELECT pgp_sym_encrypt(%s::text, %s)", … -
Index page from React Router Dom not showing in Django
I have 2 different apps Landing and Main. Both use react build files as templates and static files to render information on the web page. This works fine for the Landing app but not the Main app, which is probably because despite both using React Router Dom, the routes on the Main app redirect the user to /boards instead of having an index page - so the path is http://127.0.0.1:8000/[username]/boards instead of just http://127.0.0.1:8000/[username]. Instead of being redirected to the correct page, all that is shown is a blank page. I already tested this to see if something would be shown on the webpage if there was an index page and there is. The Landing app's routes does have an index page and this works fine. I also tried adding this re_path re_path(r".*") but this doesn't work either. How do I fix this? Main urls.py urlpatterns = [ # path('', views.index, name='index'), re_path(r".*", views.index, name='index') # does not work ] Main App.jsx export default function App() { const [current, setCurrent] = useState(); return ( <> <BrowserRouter> <Routes> <Route path="/" element={<Layout setCurrent={setCurrent} />} > <Route index element={<Navigate to="/boards" />} /> <Route path="boards" element={<Boards />} /> ... </Route> </Routes> </BrowserRouter> </> ); …