Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Microsoft Azure Face API gives APIErrorException: (InvalidRequest) Invalid request has been sent
enter image description here face ID is None Calling Face ID Generation Catching Update Function image URL is /media/missingpersons/IMG_20220827_191210.jpg image Path is C:\Users\Dell\Desktop\FYP\media\missingpersons\IMG_20220827_191210.jpg face ID is None Calling Face ID Generation Internal Server Error: /people/verify-missing-person/1 Traceback (most recent call last): File "C:\Users\Dell\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\Dell\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Dell\AppData\Local\Programs\Python\Python39\lib\site-packages\django\views\generic\base.py", line 84, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\Dell\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\auth\mixins.py", line 73, in dispatch return super().dispatch(request, *args, **kwargs) File "C:\Users\Dell\AppData\Local\Programs\Python\Python39\lib\site-packages\django\views\generic\base.py", line 119, in dispatch return handler(request, *args, **kwargs) File "C:\Users\Dell\Desktop\FYP\people\views.py", line 120, in post response_detected_face=generate_face_id(self.object.photo.path) File "C:\Users\Dell\Desktop\FYP\people\views.py", line 78, in generate_face_id response_detected_face = face_client.face.detect_with_stream( File "C:\Users\Dell\AppData\Local\Programs\Python\Python39\lib\site-packages\azure\cognitiveservices\vision\face\operations\_face_operations.py", line 783, in detect_with_stream raise models.APIErrorException(self._deserialize, response) azure.cognitiveservices.vision.face.models._models_py3.APIErrorException: (InvalidRequest) Invalid request has been sent. [21/Mar/2023 20:58:45,600] - Broken pipe from ('127.0.0.1', 58067) Internal Server Error: /people/verify-missing-person/1 Traceback (most recent call last): File "C:\Users\Dell\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\Dell\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Dell\AppData\Local\Programs\Python\Python39\lib\site-packages\django\views\generic\base.py", line 84, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\Dell\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\auth\mixins.py", line 73, in dispatch return super().dispatch(request, *args, **kwargs) File "C:\Users\Dell\AppData\Local\Programs\Python\Python39\lib\site-packages\django\views\generic\base.py", line 119, in dispatch return handler(request, *args, **kwargs) File "C:\Users\Dell\Desktop\FYP\people\views.py", line 120, in post response_detected_face=generate_face_id(self.object.photo.path) File "C:\Users\Dell\Desktop\FYP\people\views.py", line 78, … -
How to write a chatting app (dating app to be specific) in Python?
I'm trying to figure out how to get started with this because I'm not that good when it comes to programming, I did some projects in Flask but I don't know other frameworks. What I'm doing is a dating app where you create a profile and can message other users. I want the chat to be offline - to look like e-mails basically. I searched for some chatting app projects on GitHub, but the ones that met my needs weren't up to date (especially Django) and it was hard for me to try to change them. What framework would be the best choice here? Django seems like a good fit but like I said, I haven't coded in it. Is it possible to do it in Flask without it being too complicated? Do you have some examples that actually work without having to change the code? If you have any tips feel free to comment! -
Save selection from dropdown menu and display on a redirected page?
I am very new to django. I have a login page which allows you to select either Student, Admin, Instructor. How do I save the value selected and display it on the next page after you press Login? This is what I have so far. I believe my url routings are incorrect which is causing some sort of problem. Here is my file structure: Project file structure. This is what I have so far. In my login.html, I have a drop down menu where it classifies the selction as user_type. {% extends 'base.html' %} {% block title %}Login{% endblock %} {% block content %} <h2>Log In</h2> <form method="post"> {% csrf_token %} <label for="user_type">User Type:</label> <select name="user_type" id="user_type"> <option value="admin">Administrator</option> <option value="instructor">Instructor</option> <option value="student">Student</option> </select> {{ form.as_p }} <button type="submit">Log In</button> </form> <br> <a href="#">Forgot Password?</a> {% endblock %} From there, I need to get the value using a function in views.py. So I wrote this: ef login_view(request): if request.method == 'POST': user_type = request.POST.get('user_type') request.session['user_type'] = user_type return redirect('home') else: return render(request, 'login.html') I believe I also need to retrieve the value so I made another function in views.py def home_view(request): user_type = request.session.get('user_type') return render(request, 'home.html', {'user_type': user_type}) Then … -
set-cookie on http://localhost won't set
I have a react (next.js) project with django+graphql backend. Is it possible to set session cookie while having frontend hosted on http://localhost:5000? I tried setting django variables for httpOnly and secure and I see cookie coming from backend, however it won't set no matter what. Example of response headers: Access-Control-Allow-Credentials: true Access-Control-Allow-Origin: http://localhost:5000 Content-Length: 168 Content-Type: application/json Date: Tue, 21 Mar 2023 15:29:38 GMT Server: WSGIServer/0.2 CPython/3.7.16 Set-Cookie: csrftoken=myCsrfCookie; expires=Tue, 19 Mar 2024 15:29:38 GMT; Max-Age=31449600; Path=/; SameSite=None Set-Cookie: sessionid=mySessionIdCookie; expires=Tue, 04 Apr 2023 15:29:38 GMT; Max-Age=1209600; Path=/; SameSite=None Vary: Cookie X-Frame-Options: SAMEORIGIN -
How to use miniconda as a linux system user
I'd like to run a Django app on a linux machine using miniconda as a tool for managing packages and virtual environment. Systemctl will launch gunicorn as a dedicated system user, say my_app_user. Sources will be on /opt/my_app with permission only for my_app_user. What is the correct / secured way to install miniconda for such use case ? -
Documentation build issues during upgrade netbox
I am upgrading my netbox from 2.11.12 to 3.3.10. PYTHON=/usr/local/bin/python3.9 ./upgrade.sh At this time, a 'utilities' module error occurs in 'mkdocstrings', and I would appreciate it if you could tell me how to solve it. Successfully installed aniso8601-9.0.1 arrow-1.1.1 cython-0.29.33 graphene-3.2.2 graphene-django-3.0.0 graphql-core-3.1.7 graphql-relay-3.1.5 graphql-scalars-0.2.4 griffe-0.25.5 mkdocstrings-python-0.8.3 Skipping local dependencies (local_requirements.txt not found) Applying database migrations (python3 netbox/manage.py migrate)... Operations to perform: Apply all migrations: admin, auth, circuits, contenttypes, dcim, django_rq, extras, ipam, sessions, social_django, taggit, tenancy, users, virtualization, wireless Running migrations: No migrations to apply. Checking for missing cable paths (python3 netbox/manage.py trace_paths --no-input)... Found no missing console port paths; skipping Found no missing console server port paths; skipping Found no missing interface paths; skipping Found no missing power feed paths; skipping Found no missing power outlet paths; skipping Found no missing power port paths; skipping Finished. Building documentation (mkdocs build)... INFO - Cleaning site directory INFO - Building documentation to directory: /opt/netbox-3.3.10/netbox/project-static/docs INFO - The following pages exist in the docs directory, but are not included in the "nav" configuration: - index.md ERROR - mkdocstrings: No module named 'utilities' ERROR - Error reading page 'plugins/development/forms.md': ERROR - Could not collect 'utilities.forms.ColorField' I tried installing various packages/modules with pip, … -
Django form field uploading error bad filename
In that code I try to get the first page to make preview image. def form_valid(self, form): text_book = form.save(commit=False) text_book.owner_id = self.request.user.pk # i'm trying to get the first page to make preview image my_file = self.request.FILES['book_file'].file pdf_file = fitz.open(my_file) page = pdf_file.load_page(0) pix = page.get_pixmap() preview_image = Image.frombytes('RGB', [pix.width, pix.height], pix.samples) preview_image.thumbnail((200, 200)) image_io = BytesIO() preview_image.save(image_io, format='JPEG') image_data = image_io.getvalue() content_file = ContentFile(image_data) text_book.preview_image.save(f'text_book_preview_image{Path(text_book.book_file.name).stem}_preview.jpg', content_file, save=False) text_book.save() return HttpResponseRedirect(self.success_url) Everything works. But when I put that in settings: DATA_UPLOAD_MAX_MEMORY_SIZE = 1024 * 1024 * 500 FILE_UPLOAD_MAX_MEMORY_SIZE = DATA_UPLOAD_MAX_MEMORY_SIZE I get "bad filename". When code works without MAX_MEMORY_SIZE settings, my_file is <tempfile._TemporaryFileWrapper object at 0x7f6491f1ae20> But when I put that settings my_file is <_io.BytesIO object at 0x7f69b6945950> What is wrong? -
Page not found (404) in Django webapp
Am building a CRM application and thing was going fine until I got this roadblock Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/leads//update/ I have tried tweaking the templates and even the view file but to no avail, Here are the views files for the CRUD aspect class LeadListView(ListView): template_name = 'lead_list.html' queryset = Lead.objects.all() context_object_name = 'leads' class LeadDetailView(DetailView): template_name = 'leads/lead_detail.html' queryset = Lead.objects.all() context_object_name = 'leads' class LeadCreateView(CreateView): template_name = 'leads/lead_create.html' form_class = LeadModelForm def get_success_url(self): return reverse('leads:lead_list') class LeadUpdateView(UpdateView): template_name = 'leads/lead_update.html' form_class = LeadModelForm queryset = Lead.objects.all() def get_success_url(self): return reverse('leads:lead_list') And here is the HTML template for detail view <div class="lg:w-1/2 w-full lg:pr-10 lg:py-6 mb-6 lg:mb-0"> <h2 class="text-sm title-font text-gray-500 tracking-widest">LEAD</h2> <h1 class="text-gray-900 text-3xl title-font font-medium mb-4">{{ leads.first_name }} {{ leads.last_name }}</h1> <div class="flex mb-4"> <a href="{% url 'leads:lead_detail' leads.pk %}" class="flex-grow text-indigo-500 border-b-2 border-indigo-500 py-2 text-lg px-1"> Overview </a> <a class="flex-grow border-b-2 border-gray-300 py-2 text-lg px-1"> Reviews </a> <a href="/leads/{{ lead.pk }}/update/" class="flex-grow border-b-2 border-gray-300 py-2 text-lg px-1"> Update Details </a> </div> <p class="leading-relaxed mb-4">Fam locavore kickstarter distillery. Mixtape chillwave tumeric sriracha taximy chia microdosing tilde DIY. XOXO fam inxigo juiceramps cornhole raw denim forage brooklyn. Everyday carry +1 seitan poutine … -
NoReverseMatch at / Reverse for 'produto' with arguments '(1,)' not found. 1 pattern(s) tried: ['produto/<int:pk\\Z']
I'm taking a beginner django course, but I'm having trouble fixing the view and products link NoReverseMatch at / Reverse for 'produto' with arguments '(1,)' not found. 1 pattern(s) tried: ['produto/<int:pk\Z'] I don't really know what to do to resolve this. Index file: <!DOCTYPE html> <html lang="pt-br"> <head> <meta charset="UTF-8"> <title>Django 1 - Index</title> </head> <body> <h2>{{curso}}</h2> <h1>index</h1> <table> <thead> <tr> <th>Produto</th> <th>Preço</th> </tr> </thead> <tbody> {% for produto in produtos %} <tr> <td><a href="{% url 'produto' produto.id %}">{{produto.nome}}</a></td> <td>{{produto.preco}}</td> </tr> {% endfor %} </tbody> </table> </body> </html> view: from django.shortcuts import render from .models import Produto def index(request): produtos = Produto.objects.all() context = { 'curso': 'Programação web com django', 'produtos': produtos } return render(request, 'index.html', context) def contato(request): return render(request, 'contato.html') def produto(request, pk): prod = Produto.objects.get(id=pk) context = { 'produto': prod } return render(request, 'produto.html') produto.html file: <!DOCTYPE html> <html lang="pt-br"> <head> <meta charset="UTF-8"> <title>Produto</title> </head> <body> <h1>Produto</h1> <table> <thead> <tr> <th>Produto</th> <th>Preço</th> <th>Estoque</th> </tr> </thead> <tbody> <tr> <td><a href="{% url 'index' %}">{{produto.nome}}</a></td> <td>{{produto.preco}}</td> <td>{{produto.estoque}}</td> </tr> </tbody> </table> </body> </html> Error message: enter image description here I already try to change the pk for id but it didn't solve -
Django query to count data using starts with for year matching
In Django, I am querying for the year count. but when I run the below query it is not returning the exact result. I am not sure what I am doing wrong here can anyone please help me or suggested me the solution to? date_list = ['2022','2023'] def yearly data(date_list, qFilter): all_dict = [] for i in range(0,len(date_list)): week_list = date_list[i] count = Stats.objects.filter(Q(StartDate__startswith = week_list) & Q(Server__startswith = qFilter)).values('StartDate').annotate(dcount=Count('StartDate')) all_dict.append({"date" : date_list[i], "count" : count}) return all_dict As a result I am getting the below output: [{'date': 2022, 'count': <QuerySet [{'StartDate': '2022-03-01', 'dcount': 1}]>}, {'date': 2023, 'count': <QuerySet [{'StartDate': '2023-01-09', 'dcount': 50}, {'StartDate': '2023-01-23', 'dcount': 89}, {'StartDate': '2023-02-12', 'dcount': 3}, {'StartDate': '2023-02-22', 'dcount': 37}, {'StartDate': '2023-03-01', 'dcount': 1}]>}] Expected result: [{'date': 2022, 'count': <QuerySet [{'Year': '2022', 'dcount': 1}]>}, {'date': 2023, 'count': <QuerySet [{'Year': '2023', 'dcount': 10}]>}] Can anyone please help me to solve this ? Thanks in advance -
Paginate not working with select value from frontend
I have select from front end to choose object and change json queryset by that object_name When i try to use paginate by its not working, i mean django show me only 5 objects from json data and when i try to use paginate and go to page=2 i got an error "that page contains no results" and when i delete params=payload in my response, everything works fine with paginate by I can understand that i need to put mb something in my url but i dont know what i should put in there views.py class ShowProjectBudgetList(ListView): login_url = '/login/' redirect_field_name = '' template_name = 'customer/customer_home.html' context_object_name = 'json_data' paginate_by = 5 allow_empty = True def get_queryset(self): url = config('REPORT_PROJECT_BUDGET') if 'selection' in self.request.POST: select_front = self.request.POST['selection'] else: select_front = False payload = {'ObjectGUID': select_front, } response = requests.get(url, auth=UNICA_AUTH, params=payload) print(response.url) response_json = None try: response_json = response.json() except json.JSONDecodeError as e: print('EMPTY JSON ERROR') queryset = [] if response_json is None: print('JSON IS EMPTY') return queryset else: for item in response_json: my_js = json.dumps(item) parsed_json = ReportProjectBudgetSerializer.parse_raw(my_js) obj = parsed_json.ObjectGUID for budget in parsed_json.BudgetData: budget.SectionGUID = CleanSections.objects.get(GUID=budget.SectionGUID) budget.СompletedContract = budget.СompletedContract * 100 budget.СompletedEstimate = budget.СompletedEstimate * 100 queryset.append(budget) … -
Use BytesIO instead of NamedTemporaryFile with openpyxl
I understand that with openpyxl>=3.1 function save_virtual_workbook is gone and preferred solution is using NamedTemporaryFile. I want it to be done without writing to filesystem, only in memory, just like BytesIO did. Before update I had: wb = Workbook() populate_workbook(wb) return BytesIO(save_virtual_workbook(wb)) Now I need: wb = Workbook() populate_workbook(wb) tmpfile = NamedTemporaryFile() wb.save(tmpfile.name) return tmpfile As in https://openpyxl.readthedocs.io/en/3.1/tutorial.html?highlight=save#saving-as-a-stream As I'm using django probably I could use InMemoryUploadedFile but I don't want to. How can I use BytesIO or something similar in elegant fashion ie. without hacks and additional packages? -
The QuerySet value for an exact lookup must be limited to one result using slicing. Django
I'm new to Django and query sets. I'm trying to delete a column when user press delete button. I have user model and usecase_assign and I'm trying to execute this method: DELETE FROM usecase_assign WHERE usecase_assign.user_email = 'nmubarak.c'; My usecase_assign model: class UsecaseAssign(models.Model): usecase_assign_date = models.DateTimeField(primary_key=True, auto_now_add=True) usecase = models.ForeignKey(Usecase, models.DO_NOTHING) user_email = models.ForeignKey('User', models.DO_NOTHING, db_column='user_email') usecase_role_id = models.CharField(max_length=20) my view: if request.method=='POST' and 'delete_user' in request.POST: assigned_id = UsecaseAssign.objects.values_list('user_email__user_name') assigned_user = UsecaseAssign.objects.filter(user_email=assigned_id).delete() if assigned_user: messages.success(request, "user was deleted successfully!") return HttpResponseRedirect(reverse('usecase-details', args=[ucid])) else: messages.error(request, "Some Error was occurred!") return HttpResponseRedirect(reverse('usecase-details', args=[ucid])) my template: <form action="/usecase-details/{{result.usecase_id}}" method="POST" style=" display: inline !important;"> {% csrf_token %} <label class="mb-card h5" for="user_email">Assigned users:</label> {% for user in usecase_assigned %} <div class="btn-group me-2 mb-2"> <button type="button" class="btn btn-outline-danger">{{user|join:', '}}</button> <button type="submit" class="btn btn-danger" name="delete_user"> <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-file-x-fill" viewBox="0 0 16 16"> <path d="M12 0H4a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V2a2 2 0 0 0-2-2zM6.854 6.146 8 7.293l1.146-1.147a.5.5 0 1 1 .708.708L8.707 8l1.147 1.146a.5.5 0 0 1-.708.708L8 8.707 6.854 9.854a.5.5 0 0 1-.708-.708L7.293 8 6.146 6.854a.5.5 0 1 1 .708-.708z"></path> </svg> </button> </div> {% endfor %} </form> I'm trying to allow the … -
Django 2 different api calls for 2 different tables in postgres
I have 2 API's, they are working with different tables in the same db. But when I call them at the same time, they are working not parallelly but one after other. How can I solve this? -
Try to install dlib but unable to install it also getting legacy error
I had Python: 3.8.10 and install everything like Cmake Visual Studio C++ codes update them too Cmake path but when i install using pip install dlib it shows (venv) G:\Attendance-Management-System-Using-Face-Recognition-main\Attendance-System-Using-Face-Recognition>pip install dlib==19.4 WARNING: Ignoring invalid distribution -ip (g:\attendance-management-system-using-face-recognition-main\attendance-system-using-face-recognition\venv\lib\site-packages) WARNING: Ignoring invalid distribution -ip (g:\attendance-management-system-using-face-recognition-main\attendance-system-using-face-recognition\venv\lib\site-packages) Collecting dlib==19.4 Downloading dlib-19.4.0.tar.gz (4.0 MB) |████████████████████████████████| 4.0 MB 67 kB/s Using legacy 'setup.py install' for dlib, since package 'wheel' is not installed. WARNING: Ignoring invalid distribution -ip (g:\attendance-management-system-using-face-recognition-main\attendance-system-using-face-recognition\venv\lib\site-packages) Installing collected packages: dlib Running setup.py install for dlib ... error ERROR: Command errored out with exit status 1: command: 'g:\attendance-management-system-using-face-recognition-main\attendance-system-using-face-recognition\venv\scripts\python.exe' -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = ' "'"'C:\Users\Raja G\AppData\Local\Temp\pip-install-ka5lwkdk\dlib_eadc87d4273644db8319eaeaa8beacf2\setup.py'"'"'; file='"'"'C:\Users\Raja G\AppData\Local\Temp\pip-install-ka5lwkdk\dlib_ea dc87d4273644db8319eaeaa8beacf2\setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(file) if os.path.exists(file) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.re ad().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' install --record 'C:\Users\Raja G\AppData\Local\Temp\pip-record-dm7gz1\install-record.txt' --single-ver sion-externally-managed --compile --install-headers 'g:\attendance-management-system-using-face-recognition-main\attendance-system-using-face-recognition\venv\include\site\python3.8\dlib' cwd: C:\Users\Raja G\AppData\Local\Temp\pip-install-ka5lwkdk\dlib_eadc87d4273644db8319eaeaa8beacf2 Complete output (33 lines): running install running build Detected Python architecture: 32bit Detected platform: win32 Configuring cmake ... F:\python38\lib\subprocess.py:848: RuntimeWarning: line buffering (buffering=1) isn't supported in binary mode, the default buffer size will be used self.stdout = io.open(c2pread, 'rb', bufsize) C:\Users\Raja G\AppData\Local\Temp\pip-install-ka5lwkdk\dlib_eadc87d4273644db8319eaeaa8beacf2\setup.py:298: DeprecationWarning: isAlive() is deprecated, use is_alive() instead while t.isAlive(): -- Building for: NMake Makefiles CMake Warning (dev) in … -
Arabic characters are shown in a generated PDF as black blocks in a Django project using xhtml2pdf
I am building a Django/React project with mySQl database which has a collation utf8_general_ci. I want to generate a PDF based on given data in Arabic using xhtml2pdf. When I generate the PDF I find that the Arabic Characters are shown as black blocks or squares although I am using charset utf-8 in the HTML file and in the rendering function itself and I am using a font that is written in the official documentation of xhtml2pdf that it can be used for Arabic content. I have also used many other Arabic fonts but nothing worked. in utils.py: from django.http import HttpResponse from django.template.loader import get_template from xhtml2pdf import pisa from io import BytesIO from fpdf import FPDF def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("utf-8")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return HttpResponse('notworking') in views.py: from .utils import render_to_pdf import io from django.http import FileResponse from reportlab.pdfgen import canvas def ResultList(request): template_name = "frontend/thepdf.html" theentry = entry.objects.get(id = 2) return render_to_pdf( template_name, { "entry": theentry }, ) in thepdf.html: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html dir="rtl" lang="ar"> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <head> <style type="text/css"> @font-face {font-family: RTLFont; src: … -
Django admin integer field with '+' '-' on either side to increment/decrement value
Im stuck in a client's requirement. He wants to have a field in django admin panel like the screenshot I have attached I have a field in my model landing_page_btn_text_size = models.CharField(verbose_name=_("Button Text Size"), max_length=255, default="20px") Now he want if i click '-' it subtracts 1 from the value and if '+' it adds 1 to the value. Any help would be appreciated, thanks. -
Azure - Django deployment Static Files
I try to deploy my django app to Azure App Services. I create App in Azure and deploy my app to Azure. But when i open app i can't see staticfiles (images). However I can see it in locally. By the wat I use sqlite for the database. This is my settings.py file: STATIC_URL = "/static/" MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images') MEDIA_URL = '/images/' STATICFILES_DIRS = [ BASE_DIR / 'static' ] # Deployment STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') And also this is urls.py file: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # Deployment urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) First I fogot DEBUG=True, but I change it to DEBUG=False. It does not work also. -
The term 'py' is not recognized as the name of a cmdlet
I have been trying to create a virtual environment for django project but I have been meeting the error below. py : The term 'py' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 py --version ~~ CategoryInfo : ObjectNotFound: (py:String) [], CommandNotFoundException FullyQualifiedErrorId : CommandNotFoundException Attached is also the graphic of the error as it appears on my system. I have added python to path in environmental variables yet it's not working. -
Installed Django 4 but project runs Django 2
I've been using django for a while and today when starting a new project I noticed that when I run: django-admin startproject mysite The settings.py generated file says: Generated by 'django-admin startproject' using Django 2.2.19 and the code is not the new one. I have projects written in django 4 and in django 2 and the code generated is equal to the django 2 I also ran: python -m django --version which returns: 4.1.7 Python version is 3.11 Anyone else have this issue? -
The products are not removing from the shopping cart after ordering in python-django
I am trying to make an e-commerce website. There is 1 problem which has been very hard to fix. The problem: After ordering, products are supposed to be deleted from the shopping cart. But it is not working. There are no syntaxis errors but there is still products remaining after ordering. Here is the part my views.py for it: if not request.user.is_authenticated: session = request.session cart = session.get(settings.CART_SESSION_ID) if cart is not None: del session[settings.CART_SESSION_ID] else: customer = request.user.customer order, created = Order.objects.get_or_create( customer=customer, complete=False) order_products = OrderProduct.objects.filter(order=order) if order_products: order_product = order_products[0] else: order_product = OrderProduct.objects.create(order=order) order.save() messages.success(request, 'Заказ успешно оформлен. Проверьте свою электронную почту!!!') session = request.session cart = session.get(settings.CART_SESSION_ID) if cart is not None: del session[settings.CART_SESSION_ID] session.modified = True return redirect('product_list') I really hope someone can help me, please. Someone answered this question about 3 days ago but their answer wasn't right. I commented on their answer but they are not answering. You can check my previous question if you need their answer. IT IS NOT WORKING! -
I am finding it difficult to run any py command on my django project
py -m venv myworld 'py' is not recognized as an internal or external command, operable program or batch file. I have been battling with the above error. Adding python to path in environmental variable -
Celery is not able to find my django module
I’m facing the below error when I try to start the celery using the command celery -A blogger.celery worker. I’m running the command from my package directory where I have my celery.py ModuleNotFoundError: No module named 'blogger' ———————— blogger/celery.py from celery import Celeryfrom django.conf import settings os.environ.setdefault("DJANGO_SETTINGS_MODULE", "blogger.settings") app = Celery('blogger') app.conf.enable_utc = Falseapp.conf.update(timezone='Asia/kolkata') app.config_from_object(settings, namespace='CELERY') —————— blogger/init.py from .celery import app as celery_app all = ('celery_app', ) ———————— blogger/setting.py CELERY_BROKER_URL = 'redis://127.0.0.1:6379'CELERY_ACCEPT_CONTENT = ['application/json']CELERY_RESULT_SERIALIZER = 'json'CELERY_TASK_SERIALIZER = 'json'CELERY_TIMEZONE = 'Asia/kolkata'CELERY_RESULT_BACKEND = 'django-db'CELERY_BEAT_SCHEDULER = 'django_celery_beat.schedulers:DatabaseScheduler'————————— Please help me to resolve this error Please help me resolve this issue -
Django cannot create a new project
I have installed python and django, when i run this command django-admin startproject testproject The command run well but it does not create any folder with the name (testproject) or files. and there is no error messages. I am using Python 3.11.2 and Django v. 4.1.7 I tried to run the command and I expected it will create a project but it does not create the folder and no error messages. When I run the command again it give this CommandError: 'D:\DjangoProjects\testproject' already exists but there is NO folder in the directory. -
Creating a button to change a boolean using htmx
I am trying to create a workflow using django and htmx were a user needs to accept an entry by clicking a button. In the backend this is supposed to change a boolean from False to True. I followed this tutorial HTMX 09 - Like e unlike com HTMX trying to adapt the "Like" functionality to my purposes, however in my case there is no template (at least non that makes sense to me) and this results in a 403 error. What is my error of thought here? <models.py> from django.db import models from django.db.models import Model class PurchaseOrder(Model): name = models.CharField(max_length=200) approved = models.BooleanField(default=False) <views.py> from .models import PurchaseOrder from django.views.decorators.http import require_http_methods @require_http_methods(['POST']) def po_accept(request, pk): order = get_object_or_404(PurchaseOrder, pk=pk) order.approved_accounting = True order.save() context = {'order': order} return render(request, context) def my_approvals(request): orders = PurchaseOrder.objects.all() template = 'procurement/my_approvals.html' context = {'orders': orders} return render(request, template, context) <urls.py> from django.urls import path from . import views app_name = 'procurement' urlpatterns = [ path('', views.index, name='index'), path('my_approvals/', views.my_approvals, name='my_approvals'), path('po_accept/<int:pk>', views.po_accept, name='po_accept') ] <my_approvals.html> {% for order in orders %} {{ order.name }} <button type="button" class="btn btn-success m-3" hx-post="{% url 'procurement:po_accept' order.pk %}" > Accept </button> {% endfor %}