Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django REST Framework how to aggregate from related models
I have 3 models: class Book_type(models.Model): type_name = models.CharField(max_length=40,unique=True) class Author(models.Model): author_id = models.AutoField(unique=True, primary_key=True) author_name = models.CharField(max_length=30, unique=True) class Book(models.Model): book_id = models.AutoField(unique=True, primary_key=True) book_type = models.ForeignKey(book_type, on_delete=models.CASCADE, to_field='type_name') book_value = models.PositiveIntegerField(default=0, verbose_name='book value') book_unit = models.CharField(max_length=100, blank=True, verbose_name='book unit') book_time = models.DateTimeField(auto_now=False, verbose_name='book time') author = models.ForeignKey(verbose_name='author', to='author', to_field='author_id', on_delete=models.CASCADE) Both Book_type and Author are foreign keys to Book. Now in the views.py I want to return the following aggregate statistics for each author: mininum book value, grouped by author and book type average book value, grouped by author and book type And annotate each set of aggregate statistics with the author's ID and name. Code: from .serializers import BookSerializer,AuthorSerializer,Book_typeSerializer class AggregateListView(ListAPIView): queryset = Book.objects.all() serializer_class = BookSerializer def get_queryset(self): mininum_qs = self.get_queryset().min(book_value) average_qs = self.get_queryset().average(book_value) return new_qs.union(mininum_qs, average_qs, all=True) While coded here I totally no clew how to continue, any friend can help ? -
Integrated dash-app (using django_plotly_dash) does not get enough space
I am integrating a dash-app into django for the first time. I use django_plotly_dash for this. I think I am doing it the standard way: urls.py from django.urls import path, include from . import views urlpatterns = [ path('trial',views.trial,name='trial'), ] views.py from django.shortcuts import render from django.http import HttpResponse import my_first_dash_plotly_app.simple_dash_app def trial(request): return render(request, 'my_first_dash_plotly_app/trial.html') simple_dash_app.py import dash_core_components as dcc import dash_html_components as html import plotly.express as px import pandas as pd from django_plotly_dash import DjangoDash app = DjangoDash('SimpleExample1') # assume you have a "long-form" data frame # see https://plotly.com/python/px-arguments/ for more options df = pd.DataFrame({ "Fruit": ["Apples", "Oranges", "Bananas", "Apples", "Oranges", "Bananas"], "Amount": [4, 1, 2, 2, 4, 5], "City": ["SF", "SF", "SF", "Montreal", "Montreal", "Montreal"] }) fig = px.bar(df, x="Fruit", y="Amount", color="City", barmode="group") app.layout = html.Div(style={}, children=[ dcc.Graph( id='example-graph-2', figure=fig ) ]) trial.html {%load plotly_dash%} {%plotly_app name="SimpleExample1"%} This is just the standard-example from the plotly/dash-introduction. It works somehow but looks really ugly. You have to scroll to see the plot completely. If I remember correctly I have seen this behaviour before outside of the django-world. Is there an easy fix? Should I file a bug-report on that or is it just me doing something completely wrong? I … -
Django - get autocomplete search result from 2 models
I have written a function that enables users to look for titles in my Product and Article model I am using trevoreyre autocomplete-js library to handle autocomplete live search. The problem I am currently facing is that I want to include titles from Article and Product models in my autocomplete search bar. From what I read JsonResponse doesn't take context as a parameter. My question is how can I include the title field from both models without context parameters? views.py from product.models import Product from articles.models import Article from django.db.models import Q from django.contrib.auth.decorators import login_required from django.shortcuts import render from django.http import JsonResponse @login_required def search_address(request): title = request.GET.get('title') payload = [] if title: address_objects = Article.objects.filter(title__icontains=title) for address_object in address_objects: payload.append(address_object.title) return JsonResponse({'status':200, 'data': payload}) @login_required def search_results(request): query = request.GET.get('q') article = Article.objects.all() product = Product.objects.all() if query is not None: lookups = Q(title__icontains=query) article = Article.objects.filter(lookups) product = Product.objects.filter(lookups) context = { 'article_list': article, 'product_list': product } return render(request, 'search/search_view.html', context) base.html <!DOCTYPE html> <html lang="en"> <head> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" /> <meta name="description" content="Starlab platform" /> <meta name="author" content="Pathfinder 23" /> <title>Starlab - {% block title %}{% endblock %}</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"> … -
Django signals not working, tried every possible solution
signals.py @receiver(user_logged_in, sender=User) def when_user_logs_in(sender, request, **kwargs): print('user_logs_signal is called') LoggedInUser.objects.get_or_create(user=kwargs.get('user')) @receiver(user_logged_out, sender=User) def when_user_logs_out(sender, request, **kwargs): print('user logs out signal iscalled') LoggedInUser.objects.get_or_create(user=kwargs.get('user')).delete() models.py class LoggedInUser(models.Model): user = models.OneToOneField(User, related_name='logged_in_user', on_delete =models.CASCADE, null=True, blank=True) session_key = models.CharField(max_length=32, null=True, blank=True) def __str__(self): return self.user.username apps.py class AccountsConfig(AppConfig): default_auto_field = "django.db.models.BigAutoField" name = "accounts" def ready(self): import accounts.signals I have done anything that i found to solve signals now working but it didnt solve i have even added "accounts.apps.AccountsConfig" in my settings.py but still it not firing i am currently logged_in and using jwt based authentication , needs help -
Django: Submitting two forms on one page and using data from first form in second form
so currently I have a web page where the user can select stats they want and then generate a march madness bracket. If they decide they like the bracket they can name it and save it. I want to save the bracket as well as the stats chosen. My issue is that I have two forms on one page, so when the user presses the save button, the stats variables are all empty since their values were assigned in the request for the other form. Basically the second form clears all data from the first form, but I want to use data from the first form in the second form. Here is my code. HTML: <form method="GET"> {% csrf_token %} <label for="stat1">Most Important Stat:</label> <select name="stat1" id="stat1"> <option value="Stat 1">Stat 1</option> <option value="Stat 2">Stat 2</option> <option value="Stat 3">Stat 3</option> <option value="Stat 4">Stat 4</option> <option value="Stat 5">stat 5</option> </select> <label for="stat2">Second Most Important Stat:</label> <select name="stat2" id="stat2"> <option value="Stat 1">Stat 1</option> <option value="Stat 2">Stat 2</option> <option value="Stat 3">Stat 3</option> <option value="Stat 4">Stat 4</option> <option value="Stat 5">stat 5</option> </select> <label for="stat3">Third Most Important Stat:</label> <select name="stat3" id="stat3"> <option value="Stat 1">Stat 1</option> <option value="Stat 2">Stat 2</option> <option value="Stat 3">Stat 3</option> <option value="Stat 4">Stat … -
400. That’s an error. Your client has issued a malformed or illegal request. That’s all we know - Google App Engine Django App
I have been programming an API using Django and djangorestframework for deployment in Google App Engine. The API is basically a package registry, so you can create, update, get, and delete packages with the API. All the endpoints seem to work except for one. The only endpoint that doesn't work is one that display a paginated list of all packages in the online registry. All the endpoints are working, but for some reason, when I hit the specific endpoint '/packages/', GCP gives me the error 400. That’s an error. Your client has issued a malformed or illegal request. That’s all we know When I run the application locally on my computer, all the endpoints work perfectly. The application only stops working for that specific route when I deploy it on Google App Engine.The API payload should be: [ { "Name": "*" } ] I am completely lost on this one and would appreciate any help. VIEWS.py import django.db.utils from rest_framework.decorators import api_view from rest_framework.response import Response from django.core.paginator import Paginator, EmptyPage import registry.models from .serializers import * from .models import * # Create your views here. @api_view(['GET']) def apiOverview(request): api_urls = { 'List': '/package-list/', 'Create': '/package-create/', 'Update': '/package-update/', 'Delete': '/package-delete/', … -
While Calling Django Api On React Error is No 'Access-Control-Allow-Origin' header is present on the requested resource
Anyone Please Help me I need to submit my project this week I am getting a problem for a week. Error is :--> Access to XMLHttpRequest at 'http://127.0.0.1:8000/list/single/2' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Please Help me 😢 -
Update or create bunch of rows - Django
I'm trying to find the most efficient way to update or create a bunch of rows (around 10K to 30k) from a json in my database. I'm grabbing a json with the data I want to put in my database. I tried Django atomic transactions but it is still very slow. I'm currently using this library but it is very slow: it takes around 1 hour to update 15k rows. But this is the shortest way I've found today. I read a lot of questions and articles but I can't find a fastest way to do it. This is how my update methods look like (using the library): def update_data_in_db(data): objs = [] for item in data: try: objs.append(Item( id=item['id'], name=item.get('name'), slug=item.get('slug'), except Exception as err: logger.exception(err) print(err) try: Currency.objects.bulk_update_or_create(objs, ['name', 'slug'], match_field='id') except Exception as err: print(err) return [obj.id for obj in objs] -
Django add filter to ForeignKey drop-down
In my Django application I have Items and Locations. Each Item could be linked to a Location. On the Item view, I want that the user can only select Locations he owns. Given the following models: from django.conf import settings from rules.contrib.models import RulesModel # Create your models here. class Location(RulesModel): name = models.CharField(max_length=200) description = models.TextField(blank=True) owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) class Item(RulesModel): name = models.CharField(max_length=200) description = models.TextField(blank=True) location = models.ForeignKey( Location, on_delete=models.SET_NULL, null=True, blank=True ) owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) How can I specify a filter to restrict the Locations available in the view? from django.views import generic from django.contrib.auth.mixins import LoginRequiredMixin # Create your views here. from .models import Item class ItemCreateView(LoginRequiredMixin, generic.CreateView): model = Item fields = [ "name", "description", "location", "owner", ] success_url = reverse_lazy("item:item-list") def get_initial(self): return {"owner": self.request.user.id} I've tried to add def __init__() to the view and specifying limit_choices_to in the model, both without success. Any other idea? -
Module 'module' has no attribute 'celery'
I need to use Celery at my project but i got some errors when i try to install at my project. I've read the Celery's doc for Django, but i've been taking the same error. My tree project : 📂 src 📄 __init__.py 📄 celery.py 📂 core 📄 __init__.py 📂 project_auth 📄 __init__.py 📄 serializer.py 📄 tasks.py 📄 settings.py 📄 urls.py 📄 wsgi.py 📄 texto.md src/_init_.py : # This will make sure the app is always imported when # Django starts so that shared_task will use this app. from .celery import app as celery_app __all__ = ('celery_app',) src/celery.py : import os from celery import Celery from django.conf import settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'src.settings') app = Celery('src') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) @app.task(bind=True) def debug_task(self): print(f'Request: {self.request!r}') src/settings.py : INSTALLED_APPS = [ #Django apps : 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', #Meus apps : 'src.core', 'src.project_auth', 'src.product', #Apps de terceiros : 'django_celery_results', 'rest_framework', "rest_framework.authtoken", ] CELERY_CONFIG = { "CELERY_TASK_SERIALIZER": "json", "CELERY_ACCEPT_CONTENT": ["json"], "CELERY_RESULT_SERIALIZER": "json", "CELERY_RESULT_BACKEND": None, "CELERY_TIMEZONE": "UTC", "CELERY_ENABLE_UTC": True, "CELERY_ENABLE_REMOTE_CONTROL": False, } docker-compose.yml: version: "3.8" services: web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - 8000:8000 depends_on: - db tty: true container_name: ${COMPOSE_PROJECT_NAME}_app db: container_name: ${COMPOSE_PROJECT_NAME}_db image: postgres:14 environment: … -
How to solve "IndexError at / list index out of range" when there is an empty list
I was wondering what the simplest way is to return null in Django when there is an empty list coming from an API "leverage_buy": [],: my views.py from django.shortcuts import render from meal_app.models import Kraken import requests def get_krakens(request): all_krakens = {} url ='https://api.kraken.com/0/public/AssetPairs' response = requests.get(url) data = response.json() for i in data['result'].values(): kraken_data = Kraken( altname = i['altname'], leverage_buy = i['leverage_buy'][0], ) kraken_data.save() my models.py from django.db import models class Kraken(models.Model): altname = models.CharField(max_length=50, blank = True, null = True) leverage_buy = models.IntegerField(blank=True, null=True) Postman response { "error": [], "result": { "1INCHEUR": { "altname": "1INCHEUR", "leverage_buy": [], I researched and tried thoroughly many similar cases here, but none had the example of an API empty list. -
Django querySet order by date closest to today
I have a simple view that returns event dates and then is presented within a table on my page. I need to order the data by the date closest to the current date only for dates in the future, not for dates that have passed. This is my view def dashboard_view(request): now = datetime.datetime.now().date game_list=Game.objects.all() event_list = Event.objects.all().order_by('event_date') return render(request,"dashboard.html",{"game_list":game_list, "event_list": event_list}) I was thinking of using datetime.datetime.now() but I can't figure out the logic/syntax to do this. Thanks -
Search filter using Vuejs and Django
I am doing my website search-filter part using Django rest-framework and VueJs. I used django-filter. My problem is that I don't know how to set url or change on Vue when data is changed for example if I input max-price, url be like that http:/.../api/v1/search/?max_price=150 and when I check is-online status to true url should be changed to http:/.../api/v1/search/?max_price=150&is_online=true. Is there any approach for this? Thanks in advance filters.py from django_filters import rest_framework as filters from .models import Announcement class AnnouncementFilter(filters.FilterSet): min_price = filters.NumberFilter(field_name="price", lookup_expr="gte") max_price = filters.NumberFilter(field_name="price", lookup_expr="lte") class Meta: model = Announcement fields = ['subcategory', "is_online", "owner"] views.py from django_filters import rest_framework as filters from .filters import AnnouncementFilter class AnnouncementFilterList(generics.ListAPIView): queryset = Announcement.objects.all() serializer_class = AnnouncementSerializer filter_backends = [filters.DjangoFilterBackend] filterset_class = AnnouncementFilter Search.vue export default { name: "Search", data() { return { announcements: [], is_online: false, min_price: "", max_price: "", ... } }, methods: { async search() { await axios .get(`api/v1/announcements/search/?max_price=${this.max_price}`) .then(response => { this.announcements = response.data console.log(response.data) }) .catch(error => { console.log(error) }) } That's what I did so far.. -
How send value from django html to django views
I want to make a section with goods in which you can "+" and "-" increase or decrease the quantity of goods And then, depending on the amount, "sell" it. Now we need to pass the value {{ el.id }} to django views My code: html: <form method="POST"> {% csrf_token %} {% for el in form3 %} {% if el.count > 0 %} [ {{ el.count }}шт. ] <br> [ {{ el.title }} ]<br> <a id="minus{{ el.id }}" href="#"><b>[ - ]</b></a> <span id="value{{ el.id }}">0</span> <a id="plus{{ el.id }}" href="#"><b>[ + ]</b></a> <br> Function where i + or - from count <script> $(function(){ var valueElement = $('#value{{ el.id }}'); function incrementValue(e){ valueElement.text(Math.max(parseInt(valueElement.text()) + e.data.increment, 0)); return false; } $('#plus{{ el.id }}').bind('click', {increment: 1}, incrementValue); $('#minus{{ el.id }}').bind('click', {increment: -1}, incrementValue); }); </script> {% endif %} {% endfor %} </form> how can i get the values with "span id=value{{ el.id }}" -
How to return a separate, related value from a Django form?
I am working on a simple appointment scheduling system where customers can bring their vehicle in for service. Customers can have multiple vehicles and have a login with all of their vehicle information saved. Most of the customers track their vehicle by a 'unit' number. When they fill out the form, they select the branch (service center) where they want the work performed, the date, the timeslot, and they select their vehicle based on the unit number. On the backend, the unit and VIN are tied together. However, currently when they submit a service request, only their unit number comes through. I need the associated VIN to come through automatically. I have tried to return separate values from the vehicle model (I can't figure that out), I've tried to return them with f' but that returns it as one string with the unit and VIN together. I've spent probably 3-4 hours trying to get this figured out. Any help is appreciated!! Models.py class Vehicle(models.Model): unit = models.CharField(max_length=10, help_text="Unit number for the vehicle") vin = models.CharField(max_length=17, unique=True, validators=[MinLengthValidator(17)], help_text="VIN of the vehicle") engine = models.ForeignKey(Engine, on_delete=models.SET_NULL, null=True) engineMfg = models.ForeignKey(engineMfg, on_delete=models.SET_NULL, null=True) sold_to = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True) mileage = models.IntegerField(default=0, … -
How to change the name of a field generated with a function in list_display in admin.py
i have a modelAdmin in admin.py. i want to display a value which i generated from a function in the model. here is the code: admin.register(Salary) class Salary(admin.ModelAdmin): list_display=('Category','BasicPA','BasicBM','Grade','Step','total') def BasicBM(self,instance): return instance.get_BasicBM() def total(self,instance): return instance.total() fieldsets =( ('Grade Salary Information',{ 'fields':('Category','BasicPA','RentP','TransportP','MealG','UtilityP','WeighInP','CSAP','TSAP','CallG','HazardG','RuralAllG','ShiftG','DomesticLawG','StateCounselG','Grade','Step') }), ) This works but it shows 'BasicBM' on the list_display title and i want to change it to 'Basic B/M'. i can't change it because i think the name of the string in list_display list has to match the name of the function in the class Salary in admin.py for this to work and the name of a function can't contain '/' or spaces. please, how do i achieve this? Thanks in Advance! -
display background color based on the conditions in the Django template
Let us consider the color codes red - #FFDADA amber - #FFC200 green - #90EE90 gold - #FFFF00 here is my index.html <td style="background-color:{% if qualification.is_past_due %}#FFDADA{% elif qualification.is_past_month %}#FFC200{% elif not qualification.validated %} #FFFF00 {% else %}#90EE90{% endif %};" Here if qualification is is_past_due = red if qualification is is_past_month (near to expire 30 days) = amber if qualification date is in future and qualification.validate = Green if qualification.expiry date is in future and not qualification.validate = Gold if no expiry_date the white let us consider my models.py class Qualification(models.Model): expiry_date = models.DateField(null=True,verbose_name="Expiry Date", blank=True) validated = models.BooleanField(default=False) def is_past_due(self): try: date1 = datetime.combine(self.expiry_date, datetime.min.time()) date2 = pytz.utc.localize(date1) return date2 and timezone.now().date() > localtime(date2, timezone=self.user.get_user_timezone()).date() except: return '' def is_past_month(self): try: expiry_date = self.expiry_date+relativedelta(months=-1) date1 = datetime.combine(expiry_date, datetime.min.time()) date2 = pytz.utc.localize(date1) return date2 and timezone.now().date() > localtime(date2, timezone=self.user.get_user_timezone()).date() except: return '' def today_date(self): try: today = timezone.now().date() return today except: return '' class Meta: ordering = ['expiry_date'] Let us consider my database records as id expiry_date validated 1 08-11-2019 1 (# alredy expired so red) 2 24-11-2021 0 (# near to expiry so amber ) 3 22-12-2021 1 (# future date and validated(1) so green ) 4 28-12-2021 0 … -
Why does my Django object being deleted with no reason?
Okay, so I know this question may not be in appropriate shape, but I have no other way to describe it. I have a Django project, deployed with Heroku. I'm using Postgres add-on. The problem is, few of the objects that my users created is being deleted for some reason. I tried to see if there's a pattern with this issue, but I haven't found one. It happens randomly. So I started wondering if there could be something wrong with Heroku or the Postgres add-on I'm using. This is a quite serious issue, but I can't figure out what the problem is. Has anyone experienced similar issue or knows the answer to this? Thank you very much. -
Django message history
I wonder if you have any ideas on this I present messages as below - it works great, when there is an error it shows the error. But, how do I retain these messages - so the user can see all of the errors they had since their session started? I.e. if I working for a while, I might want to review all my form validation failures at the end. Thanks messages.error(request, ('ERROR: Your milestone was not created. Milestone points must be numeric. Please try again.')) -
django form dynamic drop-down list
I am a newbie in Django. I want to create a dropdown list which can be created from django-admin dynamically without editing coding multiple times. I don't know how to do it. Thanks in advance. -
cannot install msqlclient on win 10. fatal error C1083: Cannot open include file: 'mysql.h' No such file or directory
To install mysqlclient using pip I download visual c++ and install it. but when i run this code: pip install mysqlclient I get this error: fatal error C1083: Cannot open include file: 'mysql.h' No such file or directory. I have win10 and python version 3.10.0 on my system. Please help me with this error. -
How to speed up stacked queries in Django using caching
Current in my project, I have a layer of models as such: Sensor class: which stores different sensors Entry class: which stores whenever a new data entry happens Data class: which stores data pairs for each entry. Generally, that additional class was used since I have different fields for different sensors and I wanted to store them in one database, so how I was doing that was through two methods, one for entry to get the data for it, and one in the sensor as follows: class Data(models.Model): key = models.CharField(max_length=50) value = models.CharField(max_length=50) entry = models.ForeignKey(Entry, on_delete=CASCADE, related_name="dataFields") def __str__(self): return str(self.id) + "-" + self.key + ":" + self.value class Entry(models.Model): time = models.DateTimeField() sensor = models.ForeignKey(Sensor, on_delete=CASCADE, related_name="entriesList") def generateFields(self, field=None): """ Generate the fields by merging the Entry and data fields. Outputs a dictionary which contains all fields. """ output = {"timestamp": self.time.timestamp()} for entry in self.dataFields.all(): if field is not None: if entry.key != field: continue try: value = float(entry.value) if math.isnan(value) == True: return None else: output[entry.key] = float(entry.value) except: pass return output class Sensor(models.Model): . . . def generateData(self, fromTime, toTime, field=None): fromTime = datetime.fromtimestamp(fromTime) toTime = datetime.fromtimestamp(toTime) entries = self.entriesList.filter(time__range=(toTime, fromTime)).order_by( "time" … -
Django limit choice of user field foreign key based on the user that logged in
I have a model called Client with user field as a foreign key: class Client(models.Model): name = models.CharField(_('Client Name'), max_length=100) address = models.CharField(_('Client Address'), max_length=100, blank=True) demand = models.PositiveIntegerField(_('Client Demand')) location = models.PointField(_('Client Location')) created_at = models.DateTimeField(auto_now=True) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) class Meta: default_permissions = ('add', 'change', 'delete', 'view') def __str__(self): return self.name I want to limit the choice of the user field in the admin form based on who logged in for example, here I logged in as agung, so I want the select box choice of user field limit only to agung, but here I can access other username like admin and rizky. I tried this class ClientAdminForm(forms.ModelForm): class Meta: model = Client fields = "__all__" def __init__(self, request, *args, **kwargs): super(ClientAdminForm, self).__init__(request, *args, **kwargs) if self.instance: self.fields['user'].queryset = request.user but it seems that it can't take request as an argument (I guess because this is not an Http request) -
Losing image files saved by users after deployment updates to AWS
My Django App have a CRUD where users can save news with an image. All my static files like banners and css files are working good. When the app is running and users create News, everything works fine too. My problem starts when I need deploy updates to production. After deployment, the app is losing all image files uploaded by users. When users upload images, it are saved inside project folder and I think deployments are overwriting all project folder. What can I do to solve this? Some configs in my Settings.py which I think are important: MEDIA_ROOT = os.path.join(BASE_DIR, 'Setup/media') MEDIA_URL = '/media/' DEBUG = False I Already tried change the image path to outside project folder. But this don't work in production, because I don't have access to folders outside project in AWS. -
Checking the payment status from an payment APi
Am trying to verify user transaction on paystack. After a user makes payment, I want what to append the reference to the Api URL to check if the payment was succcessful. If the payment is successful then save the model. import requests from django.conf import settings class Paystack: PAYSTACK_SECRET_KEY = "sk_test_3cd83d64a1de3a7334bdad47e3fdfa01bf16a059" base_url = "https://api.paystack.co" def verify_payment(self, reference, *args, **kwargs): path = f'/transaction/verify/{reference}' headers ={ "Authorization": f"Bearer {self.PAYSTACK_SECRET_KEY}", "Content-Type":'application/json' } url = self.base_url + path response = requests.get(url, headers=headers) if response.status_code == 200: response_data = response.json() return response_data['status'], response_data['data'] response_data = response.json() return response_data["status"], response_data["message"] def process_payment(request, slug, amount, award, votes): reason = request.GET.get('reason') transaction_id = request.GET.get('reference') amount = (str(int(amount) / 100)) paystack = Paystack() status = paystack.process_payment(self.reference) if status == "success": transaction = SuccessfulTransactionHistory( nominee_name=slug, transaction_id=transaction_id, amount=amount, award=award ) transaction.save() Nomination.objects.filter(slug=slug).update(votes=F('votes') + votes) Award.objects.filter(slug=award).update(amount=F('amount') + amount) return redirect('vote:paymentsuccess', slug=slug) else: context = { 'error': reason } transaction = FailedTransactionHistory( nominee_name=slug, transaction_id=transaction_id, amount=amount, award=award ) transaction.save() return render(request, 'payment_error.html', context=context) This is the eeror i get AttributeError at /payment/Paul/000000000020/halotech-award-8/1/ 'Paystack' object has no attribute 'process_payment'