Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to add a list of booleans per user to a django model?
In addition to the basic user model I have a second custom model in my django app. This model is called a challenge. I want this challenge object to contain a list of booleans for each user where I can store which users have completed this challenge. This list must be able to do the following things: Whenever a new user is added, each existing challenge object needs to get a new boolean which is set to false. Whenever a user is deleted the corresponding booleans in each challenge must be removed also. Whenever a user completes a challenge the list inside the challenge object must be updated. How do I do this? I think I need to use some sort of ForeignKey of ManyToOne relationship, but I really have no idea how to go about this. I added a ManyToMany field and gave it the paramter User, but that only gave me a list of all Users where I could’t remove any of the users. -
Admin page toggle button bug
Django admin page UI is like this when i added a custom user model. -
Django doesn't recognize my static folder
I just started my django project and i saw that i had to put my static folder in my project folder so i did, i think i did the necessary modifications to settings.py but when a ran my server, the css wasn't applying to my page, i looked at where my css file was looked for and it said "404 /store/static/css/carousel.css" ("store" is my app inside my project) while it should look for "myproject/static/css/carousel.css". So I moved my static folder inside my app folder ("store") at the location the server was looking for (store/static/css/carousel.css) but even if it is now looking at the right location it is still not working. settings.py BASE_DIR = Path(__file__).resolve().parent.parent STATIC_URL = 'static/' STATICFILES_DIR = [os.path.join(BASE_DIR, '/static/')] html page referencing my css file {% extends 'store/base.html' %} {% load static %} {% block head %} <link href="{% static 'css/carousel.css' %}" rel="stylesheet" type="text/css"> {% endblock %} server response Not Found: /store/static/css/carousel.css [07/Aug/2023 10:00:27] "GET /store/static/css/carousel.css HTTP/1.1" 404 2378 i have these directories . ├── myproject │ ├── __init__.py │ ├── asgi.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── db.sqlite3 ├── manage.py └── store ├── __init__.py ├── admin.py ├── apps.py ├── models.py ├── static │ … -
deployment diagram in insurance domain for python language
deployment diagram in insurance domain for python language Iam expecting a architecture diagram using django framework and SQL Server 2022 (Azure) and front end React JS unit tests and integration tests (PyTest) please help me to find out for full architecture diagram for tech stack in python language -
Celery beat with django
I have this code to run my django celery first here the settings.py file under app.app.settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # 'debug_toolbar', 'django_filters', 'django_extensions', 'corsheaders', 'rest_framework', 'auditlog', 'simple_history', 'drf_spectacular', 'django_celery_beat', 'logging', 'core', 'user', 'company', 'erp', 'treasury', ] CELERY_BROKER_URL = config('CELERY_BROKER_URL') CELERY_BROKER_BACKEND = "db+sqlite:///celery.sqlite" CELERY_CACHE_BACKEND = "db+sqlite:///celery.sqlite" CELERY_RESULT_BACKEND = "db+sqlite:///celery.sqlite" CELERY_ACCEPT_CONTENT = ['json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_BEAT_SCHEDULER = 'django_celery_beat.schedulers:DatabaseScheduler' now here the app.app.celery.py file import os from celery import Celery from celery.schedules import crontab os.environ.setdefault("DJANGO_SETTINGS_MODULE", "app.settings") app = Celery("app") app.config_from_object("django.conf:settings", namespace="CELERY") app.autodiscover_tasks() app.conf.beat_schedule = { 'generate_recurring_sale_documents_task': { 'task': 'erp.sale_document.tasks.generate_recurring_sale_documents_task', 'schedule': crontab(hour='11', minute='18'), 'args': ('celer_beat_security_key_to_access_to_tasks',) }, } and under app.erp.sale_document.tasks.py file I have this code import logging from celery import shared_task from .service import generate_recurring_sale_documents logger = logging.getLogger(__name__) @shared_task def generate_recurring_sale_documents_task(secret_key=None): # if secret_key != 'celer_beat_security_key_to_access_to_tasks': # logger.error("Unauthorized access attempt to generate_recurring_sale_documents_task") # return generate_recurring_sale_documents() I run my celery worker and celeyr beat like this python -m celery -A app.celery worker -l info -E --pool=gevent python -m celery -A app.celery beat -l debug here some logs for celery beat __ - ... __ - _ LocalTime -> 2023-08-07 11:22:08 Configuration -> . broker -> amqp://bimauser:**@localhost:5672// . loader -> celery.loaders.app.AppLoader . scheduler -> django_celery_beat.schedulers.DatabaseScheduler . … -
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.