Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I filter tags with django-taggit
I'm doing the following to filter the posts by tag. But the problem is when clicking the tag button, I do not see any results. urls.py : urlpatterns =[ ...... path('challengePage/', views.ChallengePage, name ='challengePage'), path('tag/<tag>', views.tag, name='tag_argument'), ] the views.py : def ChallengePage(request): challenges = Challenge_code.objects.prefetch_related('tags').all().order_by('-created_at') tags = Tag.objects.all() context = { 'challenges' : challenges, 'tags':tags, } return render(request,'challengePage.html',context) def tag(request,tag): challenges_tag = Challenge_code.objects.filter(tags__name__in=tag) return render(request, 'tag.html',{'tag':tag, 'challenges':challenges_tag}) the challengePage.html : <div style="text-align: center;"> {% for tag in tags %} <a href="{% url 'tag_argument' tag %}"><button style="text-align: center;" dir="ltr" class="buttonTag buttonTag2" > {{tag.name}}</button></a> {% endfor %} </div> the tag.html : <div class="code_body"> <div class="container_code"> {% for challenge in challenges_tag %} <div class="Box_code"> <p class="title_code"><bdi style=" color: #000;"> {{challenge.title}} <br> {% for tag in challenge.tags.all %} <small>{{tag}}, </small> {% endfor %} </bdi> </p> <a href="{% url 'challenge' challenge.id %}"><button class="button1" style="vertical-align:middle"><span>Join</span></button></a> <p class="name-user"> <bdi> By: {{challenge.auther.username}} </bdi> </p> </div> {% endfor %} -
Django Handling Multiple Image Uploads
I have a simple project that has two different models. One that handles a report and one that stores the images for each report connected by a ForeignKey: class Report(models.Model): report_location = models.ForeignKey(Locations, on_delete=models.CASCADE) timesheet = models.ImageField(upload_to='report_images', default='default.png') text = models.CharField(max_length=999) report_date = models.DateField(auto_now=True) created_by = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return f"{self.report_location, self.report_date, self.created_by}" class TimeSheetAndPics(models.Model): report = models.ForeignKey(Report, on_delete=models.CASCADE) report_images = models.ImageField(upload_to='report_images', default='default.png') date = models.DateField(auto_now=True) def __str__(self): return f"{self.report} on {self.date}" My Goal is to have a user fill out the report and then upload multiple pictures, however i cannot figure out how to handle multiple image uploads. I have two forms for each model: class ReportCreationForm(ModelForm): class Meta: model = Report fields = [ 'report_location', 'text', ] class TimeSheetAndPicForm(ModelForm): report_images = forms.FileField(widget=ClearableFileInput(attrs={'multiple': True})) time_sheets = forms.FileField(widget=ClearableFileInput(attrs={'multiple': True})) class Meta: model = TimeSheetAndPics fields = [ 'time_sheets', 'report_images', ] And this is how i try to handle my views: class NewReport(LoginRequiredMixin, View): def get(self, request): context = { 'create_form': ReportCreationForm(), 'image_form': TimeSheetAndPicForm(), } return render(request, 'rakan/report_form.html', context) def post(self, request): post = request.POST data = request.FILES or None create_form = ReportCreationForm(post) image_form = TimeSheetAndPicForm(post, data) if create_form.is_valid() and image_form.is_valid(): clean_form = create_form.save(commit=False) clean_form.created_by = request.user clean_form.save() clean_image_form = … -
Django pass value to subquery inside annotate in a query set with mptt
i have a class based on ListCreateAPIView where i'm modifing get_queryset method.. i need pass inside a subquery for an annotate a paramether but seem OutherRef dosen't work i'm using Mptt library .... subqueryItem works fine, subqueryNested instead says cannot use OuterRef can be used only inside a subquery def get_queryset(self): queryset = super().get_queryset() subqueryItem = Subquery(Item.objects.filter(category=OuterRef('id')).order_by() .values('category').annotate(count=Count('pk')) .values('count'), output_field=IntegerField()) subqueryNested = Subquery(Item.objects.filter(category__in=ItemCategory.objects.get(pk=OuterRef('id')).get_descendants(include_self=True)).order_by() .values('category').annotate(count=Count('pk')) .values('count'), output_field=IntegerField()) queryset = queryset.annotate( collcount = Coalesce(subqueryItem, 0), collcountdeep = Coalesce(subqueryNested, 0), ) -
ModuleNotFoundError: No module named "tip_administration_app"
I'm trying to set up a complete environment to run a Django application on ubuntu 22.04 with gunicorn and nginx. I use a droplet provided by Digital Ocean and i'm trying to follow this tutorial : https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-20-04 Everything is going well until I have to link gunicorn to my wsgi.py file. When i'm trying this command : gunicorn --bind 0.0.0.0:8000 tip_administration_app.wsgi I have this error : [2022-12-20 14:08:25 +0000] [20676] [INFO] Starting gunicorn 20.1.0 [2022-12-20 14:08:25 +0000] [20676] [INFO] Listening at: http://0.0.0.0:8000 (20676) [2022-12-20 14:08:25 +0000] [20676] [INFO] Using worker: sync [2022-12-20 14:08:25 +0000] [20677] [INFO] Booting worker with pid: 20677 [2022-12-20 14:08:25 +0000] [20677] [ERROR] Exception in worker process Traceback (most recent call last): File "/home/django/the-ideal-partner/myprojectenv/lib/python3.10/site-packages/gunicorn/arbiter.py", line 589, in spawn_worker worker.init_process() File "/home/django/the-ideal-partner/myprojectenv/lib/python3.10/site-packages/gunicorn/workers/base.py", line 134, in init_process self.load_wsgi() File "/home/django/the-ideal-partner/myprojectenv/lib/python3.10/site-packages/gunicorn/workers/base.py", line 146, in load_wsgi self.wsgi = self.app.wsgi() File "/home/django/the-ideal-partner/myprojectenv/lib/python3.10/site-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/home/django/the-ideal-partner/myprojectenv/lib/python3.10/site-packages/gunicorn/app/wsgiapp.py", line 58, in load return self.load_wsgiapp() File "/home/django/the-ideal-partner/myprojectenv/lib/python3.10/site-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp return util.import_app(self.app_uri) File "/home/django/the-ideal-partner/myprojectenv/lib/python3.10/site-packages/gunicorn/util.py", line 359, in import_app mod = importlib.import_module(module) File "/usr/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line … -
How to show GenericRelation object field value in list_display?
models.py class ModelA(models.Model): name = models.CharField(max_length=40) class ModelB(models.Model): name = models.CharField(max_length=100) model_c = GenericRelation("modelc") class ModelC(models.Model): model_a = models.ForeignKey(ModelA, on_delete=models.CASCADE) content_type = models.ForeignKey(ContentType, limit_choices_to={"model__in":["modelb", "modelx", "modely"]}, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() details = GenericForeignKey("content_type","object_id") admin.py class AdminModelB(admin.ModelAdmin): list_display = ("name", "model_a") @staticmethod def model_a(obj): return obj.model_c.model_a # 'GenericRelatedObjectManager' object has no attribute 'model_a' I have ModelB having GenericRelation in field model_c where ModelC contain ContentType as ForeignKey. Now I want to display ModelA.name in list_display of ModelB. I have tried like other foreignkey fields but it gives me an error 'GenericRelatedObjectManager' object has no attribute 'model_a'. -
How to connect my HTML file with CSS file inside of a Django Project
I have a simple html page that works and renders properly on my local browser, but when I reference the static css file the page loads without the styling and I get a 200 Success for the url but 404 for the style.css file I used <link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}"> inside of the HTML file. I have the static folder in the correct spot at the project level and then a css file inside that followed by the style.css file. The Html page: {% load static %} <!DOCTYPE html> <html> <head> <title>My Website</title> <link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}"> </head> <body> <h1>Home</h1> <header> <nav> <ul> <li><a href="{% url 'home' %}">Home</a></li> <li><a href="{% url 'about' %}">About</a></li> <li><a href="{% url 'info' %}">Info</a></li> </ul> </nav> </header> </body> </html> The CSS page: h1 { background-color: orange; } From the research I've done this should get the backgrounds of all the h1 tags orange but it is not working. Any Advice? -
I have a problem with django-taggit persian[farsi-fa]
I have a problem when I put persian tags in the Django admin panel I get this error in template: Reverse for 'post_tag' with arguments '('',)' not found. 1 pattern(s) tried: ['tags/(?P<tag_slug>[-a-zA-Z0-9_]+)/\\Z'] Note: when I put English and other languages tag I don't get this error and it works True. models.py from django.db import model from taggit.managers import TaggableManager class Article(models.Model): ... tags = TaggableManager() views.py from django.views.generic import ListView class ArticleTagList(ListView): model = Article template_name = 'blog/list.html' def get_queryset(self): return Article.objects.filter(tag__slug=self.kwargs.get('tag_slug')) urls.py from django.url import path from .views import ArticleTagList app_name = 'blog' urlpatterns = [ ... path("tags/<slug:tag_slug>/", ArticleTagList.as_view(), name='post_tag'), ... ] blog/list.html ... {% for tag in article.tags.all %} <a href="{% url 'blog:post_tag' tag.slug %}">{{ tag.name }}</a> {% endfor %} ... enter image description here I change django-taggit version to last version bun not working. I'm now using 3.1.0 version. What can I do? Is there any solution for this problem? -
How to make a dropdown unclickable until a value from another dropdown is chosen, and use that value to filter the dropdown in Excel and Pandas
So I have an excel file that I generated with pandas that has a sheet with two columns A and B that are dropdowns (The values of those dropdowns are coming from another sheet in the same excel file), I want B to be unclickable for any row until A has been filled for any row. And after that, I want the value in A to be used to filter the dropdown in B. Does anyone have an idea how to go about it? This help will be greatly appreciated -
Django - Get all Columns from Both tables
models.py from django.db import models class DepartmentModel(models.Model): DeptID = models.AutoField(primary_key=True) DeptName = models.CharField(max_length=100) def __str__(self): return self.DeptName class Meta: verbose_name = 'Department Table' class EmployeeModel(models.Model): Level_Types = ( ('A', 'a'), ('B', 'b'), ('C', 'c'), ) EmpID = models.AutoField(primary_key=True) EmpName = models.CharField(max_length=100) Email = models.CharField(max_length=100,null=True) EmpLevel = models.CharField(max_length=20, default="A", choices=Level_Types) EmpPosition = models.ForeignKey(DepartmentModel, null=True, on_delete=models.SET_NULL) class Meta: verbose_name = 'EmployeeTable' # Easy readable tablename - verbose_name def __str__(self): return self.EmpName This is my models.py file I have 2 tables and want to join both of them. also want all columns from both tables. emp_obj = EmployeeModel.objects.select_related('EmpPosition'). \ only('EmpID', 'EmpName', 'Email','EmpLevel', 'DeptName') I have tried to do this but there is an error saying EmployeeModel has no field named 'DeptName' How can I get all these columns? -
Get value of a variable inside a function inside a class from another file
i'm trying to fetch the value of a variable inside a function inside a class from another file. this is the class in another folder app/views class ReportVisualisations(TemplateView): def clean(self): xyz = 10 print(app.views.ReportVisualisations.clean.xyz) getting the error 'function' object has no attribute 'xyz' and when i'm trying to print link print(stitch.views.ReportVisualisations().clean().xyz) I'm getting the following error 'NoneType' object has no attribute 'xyz' please help me out on this I'm able to print it if it's inside the class but outside the function using print(app.views.ReportVisualisations.xyz) -
django Test discovery Issues
i run ./manage.py test and i got this err ... test_create_default_action_with_deadline (masoon.anomalies.tests.anomaly.AnomalyCreateDefaultAction) ... ok masoon.actions.admin (unittest.loader._FailedTest) ... ERROR masoon.actions.models (unittest.loader._FailedTest) ... ERROR masoon.anomalies.models (unittest.loader._FailedTest) ... ERROR ... ====================================================================== ERROR: masoon.actions.admin (unittest.loader._FailedTest) ---------------------------------------------------------------------- ImportError: Failed to import test module: masoon.actions.admin Traceback (most recent call last): File "/usr/lib/python3.10/unittest/loader.py", line 470, in _find_test_path package = self._get_module_from_name(name) File "/usr/lib/python3.10/unittest/loader.py", line 377, in _get_module_from_name __import__(name) File "/home/vahid/project/py/django/masoon/actions/admin/__init__.py", line 1, in <module> from .actions import ActionsAdmin File "/home/vahid/project/py/django/masoon/actions/admin/actions.py", line 8, in <module> class ActionsAdmin(AbstractBaseAdmin): File "/home/vahid/project/py/django/masoon/.venv/lib/python3.10/site-packages/django/contrib/admin/decorators.py", line 100, in _model_admin_wrapper admin_site.register(models, admin_class=admin_class) File "/home/vahid/project/py/django/masoon/.venv/lib/python3.10/site-packages/django/contrib/admin/sites.py", line 126, in register raise AlreadyRegistered(msg) django.contrib.admin.sites.AlreadyRegistered: The model Action is already registered with 'actions.ActionsAdmin'. filetree: ... ├── actions │ ├── admin │ │ ├── action_report.py │ │ ├── actions.py │ │ ├── answer.py │ │ ├── __init__.py │ ├── api ... │ ├── apps.py │ ├── __init__.py │ ├── models │ │ ├── action.py │ │ ├── action_report.py │ │ ├── answer.py │ │ ├── __init__.py ├── infrastructure │ ├── asgi.py │ │ ... │ ├── urls.py │ └── wsgi.py ├──settings ... │ ├── apps.py │ ├── files.py │ ├── __init__.py │ ├── logging.py │ ├── main.py │ ├── middlewares.py ... ├── manage.py ... but when i run ./manage.py test modulname.tests … -
condition in dict not push correctely
i have 2 type of questions in quiz plateforme, one choice with radiobutton and multichoice with checkbox, when the checkbox is in begin of quiz it's work , if it's in second question or in the last i have an error , and in my consol log the rep in not an array in my html i have data who contain questions ans reps and type of reps: <div class="repsCol"> {% for Question_reponse in Questions_reponses %} <div class = "Question {% if forloop.first %}active{% endif %}"> <div class = "title_section_quiz"> <h2 class="qst">{{Question_reponse.question}}</h2> <div class = "Reponses"> <div class = "img_quiz"> <img src="{% static 'img/sbg1.png' %}" width="300" height="300" alt=""> </div> <div class = "reps_quiz"> {% for rep in Question_reponse.reps %} {% if Question_reponse.question_type == 'normal' %} <label class="container_radio" ><input type="radio" id = "chSub" class="subRep" name = "rep" value="{{rep}}">{{rep}}<span class="checkmark_radio"></span></label> {% elif Question_reponse.question_type == 'multiples' %} <label ><input type="checkbox" id = "chSub" class="subRep" name = "repCheck" value="{{rep}}">{{rep}}</label> {% endif %} {% endfor %} </div> </div> </div> </div> {% endfor %} <div class = "ButtonNext containerButNxt"> <input id = "ButNxt" type="button" onclick="Next()" value = "Question suivate"> </div> </div> and the function next() in jquery : const allData = []; function Next(){ //console.log(document.getElementsByClassName('Question active')[0].getElementsByTagName('p')[0].innerText); … -
Django - missing 1 required positional argument: 'category_slug'
i keep getting this error in every view of my Django project: categoryFilter() missing 1 required positional argument: 'category_slug'. website is my app name. I don't know why I keep getting this error and I'm new in Django, so your helps make me happy. Here is my django views.py, urls.py, models.py and settings.py files, My views.py: from django.shortcuts import render from django.shortcuts import get_object_or_404 from .models import Service, Category # Create your views here. def home(request): return render(request, "website/home.html") def services(request): return render(request, "website/services.html") def allCategories(request): return { 'categories': Category.objects.all() } def portfolio(request): service = Service.objects.all() return render(request, "website/portfolio.html", {'services': service}) def serviceDetail(request, slug): service = get_object_or_404(Service, slug = slug, is_active = True) def categoryFilter(request, category_slug): selected = get_object_or_404(Category, slug = category_slug) service = Service.objects.filter(category = selected) return render(request, 'website/portfolio-category.html', {'category': selected, 'service': service}) My urls.py: from django.urls import path from . import views # app_name = 'website' urlpatterns = [ path('', views.home, name = 'home'), path('index', views.home), path('services', views.services, name = 'services'), path('portfolio', views.portfolio, name = 'portfolio'), path('our-story', views.our_story, name = 'our_story'), path('contact-us', views.contact_us, name = 'contact_us'), path('login', views.login, name = 'login'), path('register', views.register, name = 'register'), path('profile', views.profile, name = 'profile'), path('cart', views.cart, name = 'cart'), path('search/<slug:category_slug>/', views.categoryFilter, … -
Build versioning for django
I would like to build versioning for my django models. I have already tried django-reversion but i think that is not good for my use case and i have problems with many-to-many through models and multi table inheritance. My use case: I have a multi tenant web app. Every tenant have their own pool of resources. The tenants can create documents and reference to the resources. Here is a simple diagram: Now on every update from the document or a resource that is referenced in the document i would create a version of the document. So the version should show all changes of the document and the referenced resources. But on revert to a version only the direct values of the document should reverted and not the resources. For example a document: Now i edit the document and delete the resource_1 with the id 1. Also i change the name from the resource_1 with the id 2. When i revert this document to the first version, it should look like this: But how can i achieve this? I think i can use MongoDB to store complete version of a document as serialized json data on every update. And can create … -
i faced this error : "options.allowedHosts[0] should be a non-empty string." when using PROXY with REACT and Django as backend in LOCALHOST
im facing error while im trying to use proxy in **package.json** on react app and connect to django backend api in local host but when i tried to ```npm start``` i get this error: Invalid options object. Dev Server has been initialized using an options object that does not match the API schema. options.allowedHosts[0] should be a non-empty string. i tried all these steps as shown below and nothing worked pls help. 1- I tried to set HOST in .env file to http://127.0.0.1:8000 but it didnt work! 2- I've tried: "proxy": "http://django:8000", it changed nothing !!! then i found a workaround by using the http-proxy-middleware form: https://sunkanmi.hashnode.dev/how-to-setup-proxy-in-react-with-http-proxy-middleware but i am not looking for a workaround !!! My **package.json** look like this { "name": "frontend", "version": "0.1.0", "proxy": "http://127.0.0.1:8000", "private": true, "dependencies": { 3- i have also tried: "proxy": "http://127.0.0.1:8000", "allowedHosts": [ "127.0.0.1" ], "private":true, didn't work !!! 4- i tried changeing http://127.0.0.1:8000 to http://localhost:8000 didnt work! 5- i tried changeing allowed host in django seetings.py to ['*'] and ['http://127.0.0.1:8000', 'http://localhost:8000'] didnt work ! 6- i tried changeing CORS_ALLOW_ALL_ORIGINS to True and then changing it to CORS_ALLOWed_ORIGINS = [ 'http://localhost:3000' ] didnt work!!! -
Why all permissions checks?
I am new in django and drf in my project I have two group of permissions 1.normal_user group : with view_issue,view_project,view_analyzeissue 2.manager_user : with all permission as possible i have some views that check some permissions for example IssuesViewApi view, this view need to NormalUserPermissions so i created new group with composition of permissions in my tests and send request to the view my new group have view_issue,change_issue when i send request to the IssuesViewApi i get 403 response i have a NormalUserPermissions class class NormalUserPermissions(permissions.BasePermission): def has_permission(self, request: Request, view): if request.user.has_perms(get_group_permissions("normal_user")): return True return False class IssuesViewApi(generics.ListAPIView): class IssueFilter(FilterSet): labels = CharFilter(field_name="labels", lookup_expr='contains') project_id = NumberFilter(field_name="project__id", lookup_expr='exact') user_name = CharFilter(field_name="users__username", lookup_expr='exact') start_date = DateFilter(field_name="updated_at", lookup_expr='gte') end_date = DateFilter(field_name="updated_at", lookup_expr='lte') class Meta: model = Issue fields = ["iid", 'is_analyzed', 'project_id', 'labels', 'user_name', 'start_date', 'end_date'] permission_classes = [IsAuthenticated, NormalUserPermissions] http_method_names = ['get'] pagination_class = StandardPagination queryset = Issue.objects.all() serializer_class = IssueSerialize filter_backends = [OrderingFilter, DjangoFilterBackend] filterset_class = IssueFilter ordering_fields = ['iid', 'weight'] # order fields depend on user request ordering = ['iid'] # default order value def get(self, request, *args, **kwargs): response = super(IssuesViewApi, self).get(request, *args, **kwargs) return Response({ 'data': { 'issues': response.data['results'], }, 'paginationInfo': { "count": response.data['count'], "next_page": response.data['next'], … -
category id is stored as null for the user in django
I have started a django project where users have to select category while creating an account including other credentials. I have given .py file of Category, Post and CustomUser model below. The forms.py file is for the researcher-profile.html file. So when a user will login, the user will be redirected to this researcher-profile. I have set the cid in the CustomUser model as null so that I can create superuser. But for normal user, it is mandatory to select category which is why I gave specialization which is cid as required field in forms.py. But the problem is when a normal user registers an account from the registration page, then in the database it stores null in the cid field even though the user selected a category while registering. How to solve this problem? blog/models.py from django.db import models from django.utils import timezone from django.contrib.auth import get_user_model from ckeditor.fields import RichTextField # Create your models here. class Category(models.Model): cid = models.AutoField(primary_key=True) category_name = models.CharField(max_length=100) def __str__(self): return self.category_name class Post(models.Model): aid = models.AutoField(primary_key=True) image = models.ImageField(default='blog-default.png', upload_to='images/') title = models.CharField(max_length=200) # content = models.TextField() content = RichTextField() created = models.DateTimeField(default=timezone.now) author = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) cid = models.ForeignKey(Category, on_delete=models.CASCADE, verbose_name='specialization') approved … -
Catch initiator request in Django signal handler
I am working on a Python/Django project. I use Django signals in order to do an operation after creation of new instances of a model. The question is: Is there any trick to access the request that has triggered this signal? e.g. to use its user field and do some operations based on it. -
Django Link only opens in new Tab, no Java Script in use
I have the problem, that links in the Djangoproject I created, are not opened by clicking them, but only if I open them in a new tab. I found an answer for this problem, that this could be a problem of java script, but I have no java script in use and I don't know what to do. This is how I enabled the link in my template: ` <a href="{% url 'example' param1 param2 %}" target="_self"<button>Edit</button></a> ` I have used the target attribute of the html tag with no success. -
The Serverless Function exceeds the maximum size limit of 50mb
I am trying to deploy my Django project on Vercel and when I am deplying my project it is giving the error - "The Serverless Function "StockChart/wsgi.py" is 128.14mb which exceeds the maximum size limit of 50mb." I have attached the GitHub repository of my project below - GitHub I have tried to minimise the modules in requirements.txt and only kept the essential modules but then also it is giving the same error. -
How to upload multiple images with flags to Django
I am building a web page where a blog author can write content and upload images. Using an image field, I am allowing the author to upload multiple images and with some Javascript logic, I am displaying the images before upload. Under each image, I have a checkbox that indicates if that is the main image of the post (e.g. the first to show in the slideshow and used as thumbnail of the post itself). On this page I am showing two forms with a shared submit button and it works fine. My problems begin when I try to save the image and also indicate if it is the main one. My images model has multiple helpful methods, thumbnail property for Django admin and a save method that will set all images for a post to false, before editing/adding a new main_image. I had to include a commit argument logic because of my experiments. Please ignore it. The model includes 3 fields: the image, the main flag and a foreign key to the post as follows: class PostImages(models.Model): """ Post images for the blog app. """ image = models.ImageField( verbose_name=_("Изображение"), upload_to='blog/images/', blank=False, null=False, default='blog/images/default.jpg' ) post = models.ForeignKey( to=Post, on_delete=models.CASCADE, … -
PayPal webhooks integration with django
I am integrating Paypal in django-rest- framework. The issue is with paypal webhook response. I get a webhook json response when ever I pay some amount on paypal already created a url path in my application for the same. Sample JSON object response: {'event_version': '1.0', 'create_time': '2022-12-19T18:57:12.343Z', 'resource_type': 'checkout-order', 'resource_version': '2.0', 'event_type': 'CHECKOUT.ORDER.APPROVED', 'summary': 'An order has been approved by buyer', 'resource': {'update_time': '2022-12-19T18:57:02Z', 'create_time': '2022-12-19T18:56:51Z', 'purchase_units': [{'reference_id': 'default', 'amount': {'currency_code': 'USD', 'value': '10.00'}, 'payee': {'email_address': 'mailto:sb-dgfcl23459178@business.example.com', 'merchant_id': ''jkdshfhsjdfhjksfhjsfs'}, 'custom_id': 'e-book-1234', 'shipping': {'name': {'full_name': 'John Doe'}, 'address': {'address_line_1': '1 Main St', 'admin_area_2': 'San Jose', 'admin_area_1': 'CA', 'postal_code': '95131', 'country_code': 'US'}}, 'payments': {'captures': [{'id': '9HW93194EE464044X', 'status': 'COMPLETED', 'amount': {'currency_code': 'USD', 'value': '10.00'}, 'final_capture': True, 'seller_protection': {'status': 'ELIGIBLE', 'dispute_categories': ['ITEM_NOT_RECEIVED', 'UNAUTHORIZED_TRANSACTION']}, 'seller_receivable_breakdown': {'gross_amount': {'currency_code': 'USD', 'value': '10.00'}, 'paypal_fee': {'currency_code': 'USD', 'value': '0.84'}, 'net_amount': {'currency_code': 'USD', 'value': '9.16'}}, 'links': [{'href': 'https://api.sandbox.paypal.com/v2/payments/captures/9HW93194EE464044X', 'rel': 'self', 'method': 'GET'}, {'href': 'https://api.sandbox.paypal.com/v2/payments/captures/9HW93194EE464044X/refund', 'rel': 'refund', 'method': 'POST'}, {'href': 'https://api.sandbox.paypal.com/v2/checkout/orders/4CV868937U646315D', 'rel': 'up', 'method': 'GET'}], 'create_time': '2022-12-19T18:57:02Z', 'update_time': '2022-12-19T18:57:02Z'}]}}], 'links': [{'href': 'https://api.sandbox.paypal.com/v2/checkout/orders/4CV868937U646315D', 'rel': 'self', 'method': 'GET'}], 'id': '4CV868937U646315D', 'payment_source': {'paypal': {}}, 'intent': 'CAPTURE', 'payer': {'name': {'given_name': 'John', 'surname': 'Doe'}, 'email_address': "adsfhjasdfhdajhk@gmail.com" 'payer_id': 'CSNQVZ49MMDA2', 'address': {'country_code': 'US'}}, 'status': 'COMPLETED'}, 'links': [{'href': 'https://api.sandbox.paypal.com/v1/notifications/webhooks-events/WH-65K55150EC946744T-1T312384BP483891G', 'rel': 'self', 'method': 'GET'}, {'href': 'https://api.sandbox.paypal.com/v1/notifications/webhooks-events/WH-65K55150EC946744T-1T312384BP483891G/resend', 'rel': 'resend', 'method': 'POST'}]} … -
OSError: No wkhtmltopdf executable found: "b'' in heroku
I am trying to download a pdf file using pdfkit on a website deployed on heroku. However, it is showing the error whenever I try to download. I have it running on the local server but it does not run on the heroku server. I tried using heroku-18 but it didn't work. -
Django - Ask users to confirm change of PDF file
I got a question regarding Fileupload. I got a form where users can upload PDFs and change the uploaded PDFs. When they change the PDF, I want to add a warning, asking them to confirm the PDF change. Any idea what's the best way of doing it? Right now, I'm trying to solve it with JS in my HTML, like so: <form enctype="multipart/form-data" method="post"> {% csrf_token %} <table> {{ form.as_table }} </table> <input type="submit" value="Submit"> <input class="deleter" type="submit" value="Delete"> {% include "some_html.html" %} </form> <script> // Add event listener to change button function confirmFileChange() { var fileInput = document.getElementById('id_file'); fileInput.addEventListener('change', function() { if (fileInput.value) { if (!confirm('Are you sure you want to change the uploaded PDF?')) { fileInput.value = ''; } } }); } if (document.body.innerHTML.indexOf('Change: ') !== -1) { confirmFileChange(); } </script> But this also displays the warning upon first upload, when the user isn't changing anything. -
how to filter data from parant model based on if there relationship with child model
I have these models class TaskProgress(models.Model): field1 = models.TextField() class BaseTask(models.Model): trees=models.ManyToManyField(Tree, through='TaskProgress') class TaskType1(BaseTask): child1_field = models.TextField() class TaskType2(BaseTask): child2_field = models.TextField() how to get all taskprogress when related to TaskType2 , TaskProgress.objects.filter(???)