Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Weasy-print convert to pdf with border image
Im trying to create pdf file for payment receipt. But im not able to figure out how do i set border for it. For border im using this image Like This . But While converting it to pdf next page gets Like this How can i make it constant border for all page Python + Django code: from weasyprint import HTML html_string = render_to_string('receipt.html', DATA) html = HTML(string=html_string) result = html.write_pdf() f = open(str(os.path.join(MEDIA_URL + "invoice_receipt/", 'temp.pdf')), 'wb') f.write(result) file_obj = File(open(MEDIA_URL + "invoice_receipt/" + "temp.pdf", 'rb')) transaction.receipt_file = file_obj transaction.save() receipt.html template: <style> table tbody tr td{ border-top: unset !important; } table tbody tr:nth-child(7) td, table tbody tr:nth-child(8) td, table tbody tr:nth-child(9) td, table tbody tr:nth-child(10) td, table tbody tr:nth-child(11) td, table tbody tr:nth-child(12) td { padding-top: 0; padding-bottom: 0; } .amount-in-words{ border-bottom:3px solid black; } .table thead th { vertical-align: bottom; border-bottom: 4px solid black; } /* .invoice-template{ padding: 20px; border: 20px solid transparent; border-image: linear-gradient(to right,#633363 50%,#f3c53d 50%); border-image-slice: 1; } */ .logo{ margin-top: 2rem; } .logo2{ margin-top: 2rem; height: 160px; width:200px; } .invoice-template{ padding: 20px; background-image: url('https://dev-api.test.com/files/files/DumpData/Frame.png'); background-repeat: no-repeat; background-size: contain; break-inside: auto; } .main-container{ border: 1px solid black; padding: 20px 10px; background: white; } p … -
Form is not valid Django
I am a beginner in Django/Python and whenever I try to submit my form the is_valid() method returns false. I have tried to display the errors using form.errors but it returns nothing or {}. When i try running the following code: form.non_field_errors() field_errors = [(field.label, field.errors) for field in form] I get [('', []), ('Required', [])] form.py class ApplicationForm(forms.ModelForm): email = forms.EmailField(label='', max_length=100, required=True, widget=forms.TextInput( attrs={'class': 'form-group form-control input-lg ', 'placeholder': 'Email'}), ) required = forms.ModelMultipleChoiceField(queryset=Requirements.objects.all(), widget=forms.CheckboxSelectMultiple) class Meta: model = Requirements fields = ['email', 'required'] views.py def application_form(request): try: form = ApplicationForm() context = {'form': form} if request.method == 'GET': return render(request, 'requirements/job_specs.html', context) if request.method == 'POST': print(form.is_valid(), form.errors) if form.is_valid(): form.save() return JsonResponse({'created': True}) form.non_field_errors() field_errors = [(field.label, field.errors) for field in form] print(field_errors) return JsonResponse(form.errors.as_json(), safe=False) except Exception as e: print(e) form = ApplicationForm(request.POST or None) context = {'form': form} return render(request, 'requirements/job_specs.html', context) HTML <form method="POST" id="application-form"> {% csrf_token %} {{ form }} <div class="bg-light row" > <div class="" id="btn-box"> <div class="col-md-12 d-grid gap-2 col-6 "> <button type="submit" class="btn btn-primary btn-lg">Save</button> </div> </div> </div> </form> I have tried to apply solutions from similar posts such as Django forms is not valid or Django forms is … -
Django automatically resubmitting the form on refreshing the page
Whenever I fill the form then I click on submit button of the form to store it in the database it stored the data perfectly but when I refresh the page it again submits. So the problem is it is showing the same data multiple times in the database. Here is my Django Template code <h4 class="text-center alert alert-success">Add New Students</h4> <form action="" method="POST"> {% csrf_token %} {{form.as_p}} <input type="Submit" class="btn btn-success" value="Add"> How can I tackle this ? Here is my view function def add_show(request): if request.method == 'POST': fm = StudentRegistration(request.POST) if fm.is_valid(): nm = fm.cleaned_data['name'] em = fm.cleaned_data['email'] pw = fm.cleaned_data['password'] reg = User(name=nm, email=em, password=pw) reg.save() fm = StudentRegistration() else: fm = StudentRegistration() stud = User.objects.all() return render(request, 'enroll/addandshow.html', {'form': fm, 'stu':stud}) -
Django pagination Listview inside a Detailsview
i'm trying to call listview inside a detailview of two different models and i want pagination of listview but passing paginate_by seem it dosent work, how have to do to? class TagsDetailView(DetailView): model = Tag paginate_by = 50 def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) IL = ItemsListView(tag=tag.tag, paginate_by=8) setattr(IL, 'paginate_by', 8) context['test'] = IL.get_queryset() print(context['test']) return context -
Time out error while sending email in django
Below configs added in my settings.py, since there is no password or user name is required for this email settings, I haven't added the EMAIL_HOST_USER and EMAIL_HOST_PASSWORD settings.py file EMAIL_HOST = 'sample.outlook.com' EMAIL_PORT = 25 EMAIL_USE_TLS = True FROM_EMAIL = 'no-reply@sample.com' when I tried to execute the below comments from shell from django.core.mail import send_mail send_mail("test sub","test_msg","no-reply@sample.com",["ajith@gmail.com"]) getting the below error Traceback (most recent call last): File "<console>", line 1, in <module> File "/home/ubuntu/.local/share/virtualenvs/paralel-P-lwtg7n/lib/python3.8/site-packages/django/core/mail/__init__.py", line 61, in send_mail return mail.send() File "/home/ubuntu/.local/share/virtualenvs/paralel-P-lwtg7n/lib/python3.8/site-packages/django/core/mail/message.py", line 284, in send return self.get_connection(fail_silently).send_messages([self]) File "/home/ubuntu/.local/share/virtualenvs/paralel-P-lwtg7n/lib/python3.8/site-packages/django/core/mail/backends/smtp.py", line 102, in send_messages new_conn_created = self.open() File "/home/ubuntu/.local/share/virtualenvs/paralel-P-lwtg7n/lib/python3.8/site-packages/django/core/mail/backends/smtp.py", line 62, in open self.connection = self.connection_class(self.host, self.port, **connection_params) File "/usr/lib/python3.8/smtplib.py", line 253, in __init__ (code, msg) = self.connect(host, port) File "/usr/lib/python3.8/smtplib.py", line 339, in connect self.sock = self._get_socket(host, port, self.timeout) File "/usr/lib/python3.8/smtplib.py", line 308, in _get_socket return socket.create_connection((host, port), timeout, File "/usr/lib/python3.8/socket.py", line 807, in create_connection raise err File "/usr/lib/python3.8/socket.py", line 796, in create_connection sock.connect(sa) TimeoutError: [Errno 110] Connection timed out -
Django: authenticate & login function works but user isn't actually logged in
i have a problem related to logging a user in in Django. in the lines of code below, i have tried to use the login function to log the user in, but when the user gets to the main page the page tells them to log in (meaning that django told me that they're not authenticated); the login function doesn't raise any errors at all. login/login.py def login_user(request): if request.method == "POST": form = forms.Login(request.POST) if form.is_valid(): username = request.POST['username'] password = request.POST['password'] db_user = AuthBackend().authenticate(request, username=username, password=password) if db_user is not None: login(request, db_user, backend="django.contrib.auth.backends.ModelBackend") return HttpResponseRedirect(reverse("main:index")) else: return render(request, "login/login.html", {"form": form, "error": "Incorrect"}) else: return render(request, "login/login.html", {"form": form}) return render(request, "login/login.html", {"form": forms.Login()}) main/templates/main/index.html <!DOCTYPE html> <html> <head> <title>Timeline</title> </head> <body> {% if user.is_authenticated %} <a href="{% url 'account' %}">Account</a> {% else %} <a href="{% url 'login:login' %}">Log In</a> {% endif %} </body> </html> also, im very new to stack and making questions, so if i have to provide other info i would appreciate the reminder and ill try to be helpful as possible. thanks -
What is the best way to transfer large files through Django app hosted on HEROKU
HEROKU gives me H12 error on transferring the file to an API from my Django application ( Understood its a long running process and there is some memory/worker tradeoff I guess so. ) I am on one single hobby Dyno right now. The function just runs smoothly for around 50MB file. The file itself is coming from a different source ( requests python package ) The idea is to build a file transfer utility using Django app on HEROKU. The file will not gets stored in my app side. Its just getting from point A and sending to point B. Went through multiple discussions along with the standard HEROKU documentations, however I am struggling in between in some concepts: Will this problem be solved by background tasks really? ( If YES, I am finding explanation of the process than the direct way to do it such that I can optimise my flow ) As mentioned in standard docs, they recommend background tasks using RQ package for python, I am using Postgre SQL at moment. Will I need to install and manage Redis Database as well for this. Is this even related to Database? Some recommend using extra Worker other than … -
Django. How to filter posts with a date less than the current post?
I'm new to programming. And I don't understand methods. On the detailview post page I want to display a list of the next posts (i.e. whose time is less than the time of the current post) How do I access the date of the current post? I try: class PostDetailView(DetailView): model = Post slug_field = 'url' context_object_name = 'post' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['earlier_posts'] = Post.objects.filter(publication_date__lte=self.publication_date) return context Then I have an error: 'PostDetailView' object has no attribute 'publication_date' Thank you in advance -
Put Query Parameters in url request Django
I have a query that retrieves all the data but I would like to make another query with another url by adding query parameters in order to target my data search. For example when I request the following url: http://localhost:8000/api/calendars I have this result: [ { "id": 1, "plant_step_id": [ { "id": 3, "plant_id": { "id": 1, "name": "Agropyre" }, "step_title": "Sowing" } ], "start": [ 1 ], "end": [ 3 ] }, { "id": 2, "plant_step_id": [ { "id": 6, "plant_id": { "id": 6, "name": "Aubergine" }, "step_title": "Planting" } ], "start": [ 6 ], "end": [ 7 ] } ] And I would like by requesting this url: http://localhost:8000/api/plant/life/calendars?plant_id=1&step_title=Sowing I would like to have the data concerning what I requested in the url. I tried to achieve this in the view but didn't work. Here is the model: from django.db import models from multiselectfield import MultiSelectField MONTHS = ( (1, 'January'), (2, 'February'), (3, 'March'), (4, 'April'), (5, 'May'), (6, 'June'), (7, 'July'), (8, 'August'), (9, 'September'), (10, 'October'), (11, 'November'), (12, 'December') ) class PlantLifeCalendar(models.Model): plant_step_id = models.ManyToManyField('perma_plant_steps.PlantStep') start = MultiSelectField(choices=MONTHS, max_choices=3, max_length=6) end = MultiSelectField(choices=MONTHS, max_choices=3, max_length=6) Here is the serializer: class PlantSerializer(serializers.ModelSerializer): class Meta: model … -
mod_wsgi-express causing ModuleNotFoundError: No module named "mod_wsgi.server"
I'm trying to deploy the Django 3.2 project with Python 3.10 on CentOS 7 but I am facing issues in it. I'm trying to run the following command to run mod_wsgi-express: mod_wsgi-express start-server django_wsgi.py --server-root /var/www --user apache --group apache --port 80 --host XYZ where XYZ is the IP of the machine i'm running this command on. I had to specify a different server root as my /tmp is noexec. The contents of django_wsgi.py are: import os import sys project_dir=os.path.dirname(__file__) if project_dir not in sys.path: sys.path.append(project_dir) from django.core.wsgi import get_wsgi_application os.environ['DJANGO_SETTINGS_MODULE'] = 'MY_PACKAGE_WHERE_SETTINGS_ARE.settings' application = get_wsgi_application() but I keep getting this error: [mpm_event:notice] [pid 101737:tid 139778434865344] AH00489: **Apache/2.4.52 (codeit) mod_wsgi/4.9.0 Python/3.10** configured -- resuming normal operations [core:notice] [pid 101737:tid 139778434865344] AH00094: Command line: 'httpd (mod_wsgi-express) -f /var/www/httpd.conf -D MOD_WSGI_KEEP_ALIVE -D MOD_WSGI_WITH_LISTENER_HOST -D MOD_WSGI_MPM_ENABLE_EVENT_MODULE -D MOD_WSGI_MPM_EXISTS_EVENT_MODULE -D MOD_WSGI_MPM_EXISTS_WORKER_MODULE -D MOD_WSGI_MPM_EXISTS_PREFORK_MODULE -D FOREGROUND' mod_wsgi (pid=101741): Exception occurred processing WSGI script '/var/www/handler.wsgi'. [wsgi:error] [pid 101741:tid 139778434865344] Traceback (most recent call last): [wsgi:error] [pid 101741:tid 139778434865344] File "/var/www/handler.wsgi", line 7, in <module> [wsgi:error] [pid 101741:tid 139778434865344] import mod_wsgi.server [wsgi:error] [pid 101741:tid 139778434865344] ModuleNotFoundError: No module named 'mod_wsgi.server' The error says "handler.wsgi", I don't know if that is correct or it is not accepting my … -
Share database between local psql and docker compose postgres container
thanks for stopping here. i need some advices to share postgres database between local psql and docker compose postgres container. i'm on debian based linux stack is django 3.2 posgresql 12 so i have a compose file with a docker volume and local driver: version: "3.9" volumes: db_data: name: db_data driver: local services: db: container_name: db image: postgis/postgis:12-3.1 depends_on: - server volumes: - db_data:/var/lib/postgresql/data:rw ports: - "5432:5432" env_file: - "./.env" server: container_name: server build: ./server/ volumes: - ./server:/server ports: - "8000:8000" env_file: - "./.env" both container are running properly but my local psql don't see any database i created or modified: when i run docker-compose exec db psql -U postgres i see my database but locally impossible to link with those data i went through a lot of thread and tutorial and i worked around: container networks with network_mode :'host but didn't work ip addresses mapping changing dependencies of containers to depends_on: - db ... i'm not that experienced, and if you could provide a workaround it would be amazing. i spent days on this issues. Thanks in advance, -
How to include and execute JavaScript in Django templates?
I've read many other questions and answers, and of course the documentation. However, I still can't make my JS code run inside my templates. base.html {% load static %} {% load i18n %} <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>{% block title %}{% translate "DaniMundo" %}{% endblock title %}</title> <link href="{% static 'css/default.css' %}" rel="stylesheet" type="text/css" media="all" /> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> </head> <body> <aside> {% include "navigation.html" %} </aside> <main> {% block content %}{% endblock content %} </main> <script src="{% static 'js/clipboard.js' %}"></script> <script src="{% static 'js/custom.js' %}"></script> </body> </html> blog/article_details.html {% extends "base.html" %} {% load i18n %} {% load custom_filters %} {% block title %}{{ article.title }} | {{ block.super }}{% endblock title %} {% block content %} <article> <header> <h1 class="title">{{ article.title }}</h1> <p>{% translate "Date of publication:" %} {{ article.date_created }}</p> <p>{% include "blog/article_authors.html" %}</p> </header> <p class="summary">{{ article.summary }}</p> {{ article.body|markdown|safe }} {% if article.date_updated != article.date_created %}<p>{% translate "Last update:" %} {{ article.date_updated }}</p>{% endif %}<hr /> <div class="comments"> {% include "blog/comments.html" with article_path=article.get_absolute_url article_slug=article|full_slug %} </div> </article> {% endblock content %} custom.js function checkAnswer(origin) { var question_name = $(origin).attr("data-question"); var correct_answer_element = $(origin).attr("data-correct"); var correct_answer_id = $("#"+correct_answer_element).val(); var correct_answer_label … -
Why does user.user_permissions.all() return an empty queryset in django even if the user has default permissions?
I would like to know the reason behind user.user_permissions.all() returning an empty queryset even if the user has default permissions. I read somewhere that user_permissions are the permissions that are defined explicitly, so I am not exactly sure when to assign these permissions explicitly if the user already has them defined. To demonstrate: from django.contrib.auth.models import Permission from apps.user.models import User user=User.objects.get(id=29) print(user.is_superuser) True # as a superuser has 272 permissions print(len(user.get_all_permissions())) 272 # no explicit assignment, returns an empty queryset print(user.user_permissions.all()) <QuerySet []> Now my main question is if the user has a given permission defined, such as print(user.has_perm('add_company')) True is there any benefit of doing #explicitly adding 'add_company' permission. permission=Permission.objects.get(codename='add_company') user.user_permissions.add(permission) print(user.user_permissions.all()) <QuerySet [<Permission: main | company | Can add company>]> Thanks in advance. -
Django Admin replace field with ModelChoiceField with specific query
I searched the net but did not find an answer - but I also a bloody beginner. I basically have to models from two apps, but I don´t want to make a relation between both because of dependencies. By creating an new sensor object in admin panel, I want that you only can choose between existing customer_names(Customer). I managed to override the field "owner" ins Sensor Admin panel and Django is also saving the values in the database. But everytime I revisit a sensor object in admin panel, owner is showing the default value "--" and I have to choose an owner. (Sensor App)models.py class Sensor(models.Model): owner = models.CharField(max_length=20, null=True) (Customer App)models.py class Customer(models.Model): customer_name = models.CharField(max_length=20, null=True) forms.py class SensorAdminForm(forms.ModelForm): owner = forms.ModelChoiceField(queryset = Customer.objects.all()) class Meta: model = Sensor fields = '__all__' admin.py class SensorAdmin(OSMGeoAdmin): list_display = ('owner',) form = SensorAdminForm admin.site.register(SensorRec, SensorRecAdmin) -
show all likes count in each post django REST API
models.py class Post(models.Model): title = models.CharField(max_length=150) class PostLike(models.Model): like = models.CharField(max_length=20) user = models.ForeignKey(User,on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) Serializer.py class PostSerializer(serializers.ModelSerializer): likes = serializers.SerializerMethodField("like_count") class Meta: model = Post fields = ("__all__") def like_count(self,obj): total_like = self.context.get("like_count") return total_like views.py @api_view(["POST"]) def allpost(request): id = request.data post_list = Post.objects.all() like_count = PostLike.objects.filter(post_id = id ).count() post_serializer = PostSerializer(post_list,many=True,context={"like_count":like_count}) return Response(request,post_serializer.data) output: [ { "id": 1, "likes": 1, "title": "post 1", }, { "id": 2, "likes": 1, "title": "post 2", }, { "id": 3, "likes": 1, "title": "post 3", }, ] db id like post_id user_id 1 1 1 1 2 1 2 1 3 1 1 2 actually in my db likes are: post 1 have 2 likes post 2 have 1 like post 3 don't have any like i want to show this like this . but it's showing the first post likes for every post . how can i fix this .? i know the problem in the like_count in view . but i don't know what to put there instead of id . sorry for my poor English Thanks in advance -
Adding answer count field in Django Rest Framework
I have got 2 models, Questions and Answers. class Question(models.Model): question_subject = models.TextField() question_text = models.TextField(default=None, null=True, blank=True) slug = models.SlugField(max_length=128, unique=True, null=False, editable=False) created_at = models.DateTimeField(editable=False, default=timezone.now) updated_at = models.DateTimeField(default=timezone.now) user = models.ForeignKey('users.CustomUser', on_delete=models.PROTECT) animal = models.ForeignKey('animals.Animal', on_delete=models.PROTECT) class Answer(models.Model): answer = models.TextField() created_at = models.DateTimeField(editable=False, default=timezone.now) updated_at = models.DateTimeField(default=timezone.now) user = models.ForeignKey('users.CustomUser', on_delete=models.PROTECT) question = models.ForeignKey('Question', on_delete=models.PROTECT) number_of_points = models.IntegerField(default=0) moderate_status = models.BooleanField(default=False) The answer is connected to the Question via question field(Foreign key), but now i'm creating API for this and i need to list all the questions and the answer_count related to them. Right now i have a simple class QuestionsSerializer(serializers.ModelSerializer): class Meta: model = Question fields = '__all__' class QuestionsList(generics.ListAPIView): queryset = Question.objects.all() serializer_class = QuestionsSerializer Do you have any idea how to display the count of answers in a Question? In django views i would use something like aggregate count, but it won't work in DRF. -
my form_valid method isn't working properly
I was working in a project and I am having trouble to understand why my form_valid method is not working for ProfileCreateView. I have created a profile model for user. This is the code: # views.py from django.views.generic import CreateView from .models import UserProfile from django.urls import reverse_lazy class ProfileCreateView(CreateView): model = UserProfile template_name = "profile/profile_create.html" fields = ('profile_picture', 'bio', 'occupation', 'hobbies', 'date_of_birth') success_url = reverse_lazy("login") def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) # template {% extends 'base.html' %} {% block title %}Create Your Profile{% endblock title %} {% load crispy_forms_tags %} {% block content %} <div class="container border border-success rounded mt-4 "> <h2 class="display-6 fst-italic mt-3 mb-3">Create Your Profile</h2> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form|crispy}} <button type="submit" class="btn btn-outline-primary mt-4 mb-4">Create my profile</button> </form> {% endblock content %} # models.py from django.db import models from django.contrib.auth import get_user_model import uuid from django.core.files.storage import FileSystemStorage class UserProfile(models.Model): author = models.OneToOneField(get_user_model(), on_delete=models.CASCADE) profile_picture = models.ImageField(upload_to='images/') id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) bio = models.TextField(blank=True) occupation = models.CharField(max_length=100) hobbies = models.TextField(blank=True) date_of_birth = models.TimeField() def __str__(self): return self.author.username + ("'s profile") please tell me how to work this properly! -
TemplateDoesNotExist :/
I don't know why i keep getting this erro TemplateDoesNotExist at / home.html code settings.py `TEMPLATES = { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.media', 'django.template.context_processors.static', ], 'loaders':[ 'django.template.loaders.filesystem.Loader', ] }, },` -
Django webapp // Commenting posts on a webpage
I'm currently building a webapp with Python's django framework. There is one task that I do not really know how to handle. Let's say my page displays different questions of users (like tweets on twitter). Now, I want to provide users with the ability to write answers to the different questions displayed. When the users clicks on an answer button below a particular question, a form is displayed below the question with a textarea that can be submitted. When the filled out form with text is submitted and sent to the backend, I need to create a database relationship between the newly created answer and the question. In order to find the corresponding question in the DB its ID is necessary (primary key). Here is my problem. I do not know where to get the ID from in a safe manner. An easy way would be to put the ID into the html part of the question and then use it with javascript, or to store the IDs as javascript variables. However, as the DOM and the values of javascript variables can be modified by users on the frontend, this does not appear secure to me. If a user changes … -
Django Rest Framework routing with primary key prefix
I'm using DRF DefaultRouter as follows. # urls.py router = DefaultRouter() router.register('book', BookingViewSet, basename='booking') router.register('book/<int:bk>/reservation', ReservationViewSet, basename='reservation') urlpatterns = [ path('', include(router.urls)), ] # view class ReservationViewSet(viewsets.ModelViewSet): serializer_class = ReservationSerializer queryset = Reservation.objects.all() # for testing only But when I visit the URL /book/1/reservation/ it says no url pattern found. lending/ ^book/<int:bk>/reservation/$ [name='reservation-list'] lending/ ^book/<int:bk>/reservation\.(?P<format>[a-z0-9]+)/?$ [name='reservation-list'] lending/ ^book/<int:bk>/reservation/(?P<pk>[^/.]+)/$ [name='reservation-detail'] lending/ ^book/<int:bk>/reservation/(?P<pk>[^/.]+)\.(?P<format>[a-z0-9]+)/?$ [name='reservation-detail'] The current path, lending/book/1/reservation/, didn’t match any of these. I'm using bk to capture book id. -
How can I install pdftex on my app in Heroku?
Folling Create Pdf with Latex and Django My code in view: from django_tex.shortcuts import render_to_pdf from datetime import date def gerar_lista_turma(request, turma_id): if request.user.tipo_user() not in ['Admin', 'Professor']: return redirect('logout') template_name = 'base_lista.tex' context = { 'hoje': date.today().strftime("%d/%m/%Y"), 'escola': 'Name' } return render_to_pdf(request, template_name, context, filename=f'base.pdf') But i get the error: Exception Type: CalledProcessError Exception Value: Command 'pdflatex -interaction=batchmode texput.tex' returned non-zero exit status 127. Exception Location: /app/.heroku/python/lib/python3.9/subprocess.py, line 528, in run -
how to set specific value is first in order from the list in django or python
how to set specific value is first in order from the list in django or python "Ex: 'entity': [ OrderedDict([ ('id', 14), ( 'brand', OrderedDict([('id', 15), ( 'title', 'Golds Gym Long ' 'Branch') ]), OrderedDict([ ('id', 241), ( 'brand', OrderedDict([('id', 230), ( 'title', 'New York Fitness & ' 'Nutrition'), ]), OrderedDict([ ('id', 367), ( 'brand', OrderedDict([('id', 309), ( 'title', 'new distributors')])]); I expected result is given key value is first order, then ordering from list using sorted function in python expected result " -
I want to sort data with date_time after first processing the data with initial sorting of another column
I have football prediction data containing dataframe- df = df[['match_datetime', 'country', 'league', 'home_team', 'away_team', 'home_odds', 'draw_odds', 'away_odds', 'predicted_home_score', 'predicted_away_score']] I have to initially add two columns, predicted_home_score & predicted_away_score to get total predicted goals... df['total_predicted_goals'] = df['predicted_home_score'] + df['predicted_away_score'] Then I have to set_axis- df = df.set_axis(['Match_Datetime', 'Country', 'League', 'Home_team', 'Away_team','home_odds', 'draw_odds', 'away_odds','Predicted_home_score', 'Predicted_away_score', 'total_predicted_goals'], axis=1) Now I sorted the values using total_predicted goals - df1 = df.sort_values(by=["total_predicted_goals"], ascending= False) I only wanted the top 10 numbers so i can slit it into two to predict the top 5 as over 2.5 and the remainder as over 1.5 -- df1 = df1.drop(['home_odds', 'draw_odds', 'away_odds'], axis=1) df1 = df1.head(10) dt = ['Over 2.5', 'Over 2.5', 'Over 2.5', 'Over 2.5', 'Over 2.5', 'Over 1.5', 'Over 1.5','Over 1.5','Over 1.5','Over 1.5'] df1['Prediction'] = dt df2 = df1.drop(['Predicted_home_score', 'Predicted_away_score', 'total_predicted_goals'], axis=1) df2 = df2.style goals = df2.to_html() return render(request, 'over_goals.html', { 'goals': goals}) My problem is that the output date is not in seqeunce. def over_goals(request): df = pd.read_csv("media/csv/predictions_with_gridsearch.csv") df = df[['match_datetime', 'country', 'league', 'home_team', 'away_team', 'home_odds', 'draw_odds', 'away_odds', 'predicted_home_score', 'predicted_away_score']] df['total_predicted_goals'] = df['predicted_home_score'] + df['predicted_away_score'] df = df.set_axis(['Match_Datetime', 'Country', 'League', 'Home_team', 'Away_team','home_odds', 'draw_odds', 'away_odds','Predicted_home_score', 'Predicted_away_score', 'total_predicted_goals'], axis=1) df1 = df.sort_values(by=["total_predicted_goals"], ascending= False) df1 = … -
Django aggregate on JSONB field multiple levels deep
As the title says, I'm trying to aggregate a value in a JSONB field that's a couple of levels deep. For the model Payment, there's a JSONB field Payment.extra_data that contains a data structure like: { "invoice": { "extra": { "net_amount": 100, "tax_amount": 16.63, } } } and I'm trying to find the sum of the net_amount values. So far, I've got to doing: payment_qs = Payment.objects.annotate( net_amount=Func( F("invoice"), Value("extra"), Value("net_amount"), function="jsonb_extract_path_text", output_field=models.DecimalField(), ) ) which, if I then do payment_qs.values('meta_amount') on will give me: <PaymentQueryset [{'net_amount': Decimal('50.0')}]> However, if I try aggregating the queryset then I get: payment_qs.aggregate('net_amount') ProgrammingError: function sum(text) does not exist LINE 1: SELECT SUM("net_amount") FROM (SELECT jsonb_extract_path_te... ^ HINT: No function matches the given name and argument types. You might need to add explicit type casts. I've tried setting the output field payment_qs.aggregate('net_amount', output_field=DecimalField()) but no luck. Any ideas? -
Sockets learning in 2022?
I am very beginner. Is learning websocket programming worth it in 2022? Now there are a lot of abstractions like websocket.io, django channels e.t.c which do the same thing as plain websockets. So learning websockets is waste of time? (unless high-performance required)