Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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> </> ); … -
hwo can i fix git init problem not working
enter image description here i alredy use git init enter image description here my file not become green and i can not do anything about git. it alway said i nedd permission enter image description here immage below is what i want that i capture from youtuber:Zinglecode enter image description here pls help. i'm very new.this is my first website and i nver learn anything about code before. i need the way to fix this problem. why its become like this. -
gunicorn not picking up changes in django code even after restarting
I have this web application that I built with django, and deployed with gunicorn and nginx on GCP Compute Engine Instance. I serve the static files with nginx. For nginx, whenever I push new code to the server, run collectstatic, and restart nginx, I see the static file update working fine. The problem begins with the server code. Whenever I push code to my django views, or run migrations, or push code to my html file, and restart gunicorn, I don't see the changes right away. It takes about a full day for the change to take effect. I have tried reloading daemon, restarting gunicorn, restarting nginx but the issue persists For the nginx, here is my location settings on nginx configuration location /static/ { alias /home/user/app/backend/static/; } location / { proxy_pass http://127.0.0.1:8000; } There you can see that I serve the static file using nginx, then pass every other request to the app. Then when I push code to my github, pull it into the app, and run python3 manage.py collectstatic Then restart nginx with sudo systemctl restart nginx Everything works great. Now for the part that I think the problem comes from. If I make a change to … -
Unable to run the server after export on another computer (migrations worked)
I am lost with what is probably a very simple issue configuring a django / mysql project. I have a working project on a computer A, which I just want to be able to use with a computer B. On computer A, I have an Eclipse project, using Pydev and Django, a local virtual environnement, and a local database running with Mysql. What I have done: I exported the virtual environnement (including django) and created the same one on computer B; I used Gitlab in order to get all the files with the code ; I installed Mysql, and created a database with the same name, and a user with the same informations (id / pwd). The migrations went well, the tables are created like I expected. However, I cannot find a way to run the server. When I try, I get multiple errors saying one (and only one) of the Apps is not loaded yet, then another error, which seems to be related to the database. Here are some of the messages: Traceback (most recent call last): File "/home/francois/snap/eclipse/67/amd64/plugins/org.python.pydev.core_10.2.1.202307021217/pysrc/_pydev_runfiles/pydev_runfiles.py", line 460, in __get_module_from_str mod = __import__(modname) File "/home/francois/eclipse-workspace/iou/members/forms.py", line 2, in <module> from django.contrib.auth.forms import UserCreationForm, AuthenticationForm, UsernameField File … -
With FileField, opening file before inserting database
I have models, serializer and viewsets with FileField class Drawing(SafeDeleteModel): drawing = f.FileField(upload_to='uploads/') class DrawingSerializer(ModelSerializer): drawing = serializers.FileField() class DrawingViewSet(viewsets.ModelViewSet): queryset = m.Drawing.objects.all() serializer_class = s.DrawingSerializer def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) print("serializer request:",request.data['drawing']) # this is myfile.pdf self.perform_create(serializer) print("serializer seliarizer",serializer.data['drawing']) # myfile_ccA3TjY.pdf try: doc = fitz.open(file_path) # open to check if it is correct pdf except; raise Exception("file is not valid pdf") When uploading file,request.data['drawing'] is myfile.pdf, serializer.data['drawing'] is real name myfile_ccA3TjY.pdf. ( when there is the same name file) So for opening file with fitz, I need to know the real name myfile_ccA3TjY.pdf. I have to do self.perform_create to know the real file name, and it creates the row. However I want to cancel inserting to database when file is not valid pdf. With this code database inserting is executed even file is not correct pdf. Is there any way to open the file without calling self.perform_create? -
My web application dont load styles files when in production
My project in Django https://github.com/alex-martins2305/ToDo4 works very fine in production, bootstrap, css, everything loads perfect. But in deploy to render.com the css file dont load. I already checked: In github the files are avaliable in static/css/styles.css; run collectstatic; cleaned browser data; tryed in mozzila and chrome (desktop and mobile); In chrome i can see in inspection/network the reason to not apply the style file: Refused to apply style from 'https://todo4-hk3r.onrender.com/static/ccs/styles.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.