Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
TOKEN_LIMIT_PER_USER in django rest knox is not working
Everything was working fine until I created a custom user for my django project and since then, time limit per user is no longer working but the expiry date for the token is working fine, I have been searching online to find any solution but I can find any so I'm stack and don't know how to go about it to fix it so I flush my database and do the makegrations and migrate again but none of them worked -
How to add clipboard module to QuillField() in django for using in django admin?
Copying and pasting are not handling correctly on the Quill Editor. Is there any additional instructions which are needed when using the QuillField() in django to properly enable it, specially for copying text documents with images? This is how I am doing it: class Post(models.Model): customer = models.ForeignKey(Customer,on_delete=models.DO_NOTHING,related_name='post_customer') title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete= models.DO_NOTHING,related_name='posts_author') updated_on = models.DateTimeField(auto_now= True) created_on = models.DateTimeField(auto_now_add=True) asset = models.IntegerField(choices=POST_ASSET, default=0) status = models.IntegerField(choices=POST_STATUS, default=0) article = QuillField(blank=True, null=True) -
How would I perform post-setup init steps in Django?
Where would I put steps I'd like to perform AFTER Django's setup() call? I expected this would already be a Django signal (like post_migrate). It seems like making my own versions of get_wsgi_application, etc. with callbacks is the next best option. Since that code is rarely touched I can imagine that it could fail silently and no one would know why. For a little background, I'm making my own task runner on lambda using Django on Postgres. Being able to dynamically define scheduled python functions with their own arguments is a key feature. At start up, I need to connect database entries for functions and their definitions in code. The way I get around this problem today is at the image entrypoint: if not python_function_registry.is_registry_initialized(): python_function_registry.registry_setup() There are several places I do this today. It seems like there are several potential benefits to a post_setup signal (or something similar), so I expect it must already exist? Thanks for your help! -
why the @property django decorator doesn't work
I need to pass the 'def get_sale' method to the model in views to sort the products by get_sale, but after passing it an error comes out models.py @property def get_sale(self): '''Расчитать стоимость со скидкой''' price = int(self.price * (100 - self.sale) / 100) return price views.py class SortItems(GoodsHome):#сортировка товара def get_queryset(self): sort_types = { '0': '-time_create', '1': 'time_create', '2': 'get_sale', '3': '-get_sale', } sort_type = sort_types[self.kwargs['sort_type']] if 'query' in self.kwargs: query = self.kwargs['query'] return super(SortItems, self).get_queryset().filter(Q(artist__icontains=query) | Q(album__icontains=query)).order_by(sort_type) return super(SortItems, self).get_queryset().order_by(sort_type) -
Django Rest Framework Serializer giving error for Foriegn key field can not be null
I am working on a restframework api using DRF but while executing perform create its showing error for a foriegn key field "can not null" Serializer : `class StyleEditProductSerializer(ModelSerializer): class Meta: model = StyleEditProduct fields = '__all__' read_only_fields = ('style_edit',)` Model : `class StyleEditProduct(BlankModel): product = fields.default_fk_field(Product, related_name='style_edits') sort_order = models.IntegerField(default=0) style_edit = fields.default_fk_field(StyleEdit) class Meta: unique_together = ('product', 'style_edit')` Views : `class StyleEditProductMultipleView(CreateAPIView): serializer_class = StyleEditProductSerializer def create(self, request, *args, **kwargs): style_edit = get_object_or_404(StyleEdit, id=self.kwargs.get('style_edit_id')) style_edit_products = [] for product in request.data['data']: product['style_edit_id'] = style_edit.id style_edit_products.append(product) print(style_edit_products) serializer = self.get_serializer(data=style_edit_products, many=True) serializer.is_valid(raise_exception=True) try: self.perform_create(serializer) return Response(serializer.data, status=status.HTTP_201_CREATED) except Exception as e: print(e) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)` Error : [{'sort_order': 1, 'product': 1, 'style_edit_id': 2}] (1048, "Column 'style_edit_id' cannot be null") I am not able to understand I am passing the data for the style_edit_id in the serializer but still giving the error, Can anyone help me in this I have tried to check in model and in serializer but I am facing this issue and I can't understand why its giving error -
Django admin restrict max inline forms by parent field
I have the following two models in Django. Model Contest has questions and Questions is another django model: class Contest(models.Model): min_questions = models.IntegerField() class Question(models.Model): contest = models.ForeignKey(Contest, on_delete=models.CASCADE, related_name="questions") question = ... Then I add the questions as an inline in the contest admin: class QuestionInlineForm(forms.ModelForm): class Meta: model = Question fields = \['question'\] class QuestionInline(NestedStackedInline): model = Question form = QuestionInlineForm extra = 1 inlines = \[AlternativeInline\] #Igonre this class CustomContestAdmin(NestedModelAdmin): inlines = \[QuestionInline,\] This let me create the questions inside the contests form, the problem is that I want to restrict the number of questions to create using the field min_questions of the Contest model, so that the form doesn't let me create a contest if the total amount of questions is less than the field min_questions. Is there a way to achieve this? I'm using the nested_admin library and I tried the method clean but the questions count shows as 0 because the questions have to be added after the instance of contest is created. I think this could be done by using transactions so I can create the Contest, then add the questions and before saving to the database check if the questions count is … -
Dynamic background change depending on the incoming link
I'm currently writing a site in django and I want to create a dynamic link page where the background depends on what comes from the link. I know I can make templates for each background, but I have over 500 of them, so this method seems inappropriate. Is there a better way to do it? I tried join static and dinamic paths and also send prepared path from backend but this both and some other way were unsuccessful at least in my code -
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.