Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Deploy strategy for Celery in ECS
The way we currently deploy Celery in ECS is by calling update-service on every code change. This works fine as far as swapping out the old code for the new. The problematic scenario is when we have long-running Celery tasks, and the deploy causes those to get killed. This is because ECS only gives a container 30 seconds to shutdown (you can increase that to 10 minutes, but even that isn't long enough in some cases). The killed Celery tasks do get successfully restarted by the new Celery worker(s), but you can imagine if you deploy once an hour, and your task takes 1.5 hours to finish, it will never complete. Ideally the deploy would tell the existing Celery worker(s) to stop gracefully, i.e. finish running tasks but don't start any new ones. Then it would start new worker containers with the new code, so you have old and new running at the same time. Then, when the long-running tasks have finished, the containers with the old code would be removed. This seems like a problem that must have been encountered by others but I can't find anything describing this. Scripting this probably wouldn't be too bad but it feels … -
TypeError: 'NoneType' object is not callable using restframework
i'm building a customer user using restframework, but i got this error : TypeError: 'NoneType' object is not callable while making a post request using postman here is traceback: Internal Server Error: /auth/register/ Traceback (most recent call last): File "/home/dailycoding/Desktop/projects/my_env/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/dailycoding/Desktop/projects/my_env/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/dailycoding/Desktop/projects/my_env/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/dailycoding/Desktop/projects/my_env/lib/python3.8/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "/home/dailycoding/Desktop/projects/my_env/lib/python3.8/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/home/dailycoding/Desktop/projects/my_env/lib/python3.8/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/home/dailycoding/Desktop/projects/my_env/lib/python3.8/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/home/dailycoding/Desktop/projects/my_env/lib/python3.8/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "/home/dailycoding/Desktop/projects/myapp/users/views.py", line 7, in post serializer = self.serializer_class(data=user) TypeError: 'NoneType' object is not callable here is models.py from django.db import models from django.contrib.auth.models import(BaseUserManager,AbstractBaseUser,PermissionsMixin) # Create your models here. class UserManager(BaseUserManager): def create_user(self,username,email,password=None): if username is None: raise TypeError("users should have a username") if email is None: raise TypeError("users should have an email") user = self.model(username=username,email=self.normalize_email(email)) user.set_password(password) user.save() def create_superuser(self,username,email,password=None): if password is None: raise TypeError("password should not be none") user = self.create_user(username,email,password) user.is_superuser = True user.is_staff = True user.save() return user class User(AbstractBaseUser): username = models.CharField(max_length=255,unique=True,db_index=True) … -
how to stop djoser from sending activation email when user is updated?
How to stop djoser from sending an activation email when using "users/me" Base Endpoint with a "put" or "patch" methods??? I have a "Boolean field" inside the user model and I want to make updates for this field using the "users/me" Base Endpoint in djoser, but when I do that, djoser sends an activation email to the user account although it is already activated. please someone help -
Django model - how to avoid orphant related objects?
I have a modelling question. Suppose I have the following model: class Person(models.Model): # user = models.OneToOneField(User) name = models.CharField(max_length=50, blank=False, null=False, default=None, unique=True) ratings = models.ManyToManyField('Rating', related_name="persons" ) class Critic(models.Model): # user = models.OneToOneField(User) models.CharField(max_length=50, blank=False, null=False, default=None, unique=True) ratings = models.ManyToManyField('Rating', related_name="critics" ) class Movie(models.Model): title = models.CharField(max_length=50, blank=False, null=False, default=None, unique=True) def __str__(self): return f"{self.title}" class Rating(models.Model): movie = models.ForeignKey(Movie, models.CASCADE) value = models.SmallIntegerField(blank=False, null=False, default=None) def __str__(self): return f"{self.movie}:{self.value}" when I want to populate the Database, it's all fine, but there is one step where a rating object is created, then added to a user's list of ratings, see below. >>> from imdb.models import Person, Critic, Movie, Rating >>> m = Movie(title="Movie1") >>> m.save() >>> p = Person(name="p1") >>> p.save() >>> r = Rating(movie=m,value=5) >>> r.save() >>> p.ratings.add(r) >>> p.ratings.all() <QuerySet [<Rating: Movie1:5>]> Is this a correct pattern? Is it possible to ensure no orphant ratings? I.e. create a rating and add it to a user more or less atomically? I tried the following that didn't work: p.ratings.add(Rating(movie=m3,value=2)) #error p.ratings.add(Rating(movie=m3,value=2).save()) #no error, rating created, but not added Note, that I have a Critic with related ratings too, so not an option to have a user field … -
difficulty setting up django-channels
Please, I have a sample django app that I am building that enables a manager create users as counter or kitchen staff. Counter staff can take orders. When orders are taken by counter staff, it is automatically sent in real-time to the pending screen of all kitchen staff. Kitchen staff can fulfill an order. Manager can see all orders. But I want the orders to be updated real-time, without need to refresh the page, I have tried my best with django-channels but nothing is working. Below are the samples of my code for clarification Views.py from django.shortcuts import render, redirect, get_object_or_404 from django.contrib.auth.decorators import login_required from .forms import NewUserForm, NewOrderForm, UpdateOrderForm from .models import User, Order from datetime import datetime from django.contrib import messages # Create your views here. @login_required def dashboard(request): user = request.user if user.user_type == 'counter_staff': response = redirect('counter_page') return response elif user.user_type == 'kitchen_staff': response = redirect('kitchen_page') return response elif user.user_type == 'manager': response = redirect('manager_page') return response else: messages.error(request, 'You are not authorized to login, contact your manager') return redirect('login') @login_required def kitchen(request): user = request.user if user.user_type != 'kitchen_staff' and user.user_type != 'manager': message = 'You are not authorized to view this page' return … -
Django 3.1 JSONField attempts to deserialized dict
I am running into issues using the new django.db.models.JSONField where it appears the column comes back from the database already deserialized i.e. already a dict. The model attempts to deserialize the value again resulting an exception. TypeError: the JSON object must be str, bytes or bytearray, not dict This exception is being thrown from json.loads call in the from_db_value method on the JSONField class definition. def from_db_value(self, value, expression, connection): if value is None: return value try: return json.loads(value, cls=self.decoder) except json.JSONDecodeError: return value We are running postgres and the column is defined in the database as json i.e. not jsonb. My models that have columns that are jsonb do not appear to have this error. I do not appear to have the issue when the the column on the model is saved as a string. Only when the column is a dict. class MyModel(models.Model): data = models.JSONField() m1 = MyModel(data=json.dumps({"key": "value"}) m1.save() m1.refresh_from_db() m2 = MyModel(data={"key": "value") m2.save() m2.refresh_from_db() # Exception thrown here My guess is that it is being double encoded in this case. Whatever is causing it to be decoded into a dict is decoding it and then it's being decoded into a dict at the model … -
Django variable number of filters on ManyToManyField objects?
I'd like to filter objects on a ManyToManyField using two attributes of the objects that is pointed to by ManyToManyFeild. See the model below, this is a classical user-items relationship from django.db import models class Person(models.Model): # user = models.OneToOneField(User) name = models.CharField(max_length=50, blank=False, null=False, default=None, unique=True) ratings = models.ManyToManyField('Rating', related_name="persons" ) class Movie(models.Model): title = models.CharField(max_length=50, blank=False, null=False, default=None, unique=True) def __str__(self): return f"{self.title}" class Rating(models.Model): movie = models.ForeignKey(Movie, models.CASCADE) value = models.SmallIntegerField(blank=False, null=False, default=None) def __str__(self): return f"{self.movie}:{self.value}" So, I'd like to find all users who gave above certain rating to Movie1 AND above certain rating to Movie2. I can do this with cascading filters: >>> Person.objects\ .filter(ratings__movie__title='Movie1', ratings__value__gte=5)\ .filter(ratings__movie__title='Movie2', ratings__value__gte=1)\ .all() [[A<QuerySet [<Person: Person object (1)>]> But I am looking for a way to filter on any arbitrary number of ratings, not just 2. I have tried with Q (in the case single filter() for all cases), but the following doesn't work: >>> Person.objects.filter( Q(ratings__movie__title='Movie1') & Q(ratings__value__gte=5),\ Q(ratings__movie__title='Movie2') & Q(ratings__value__gte=1) ).all() <QuerySet []> Thanks for help -
Best way to use Index in Django and PostgreSQL
I am using Python, Django and PostgreSQL for my application development. My Database has millions of records and I have to generate reports in real-time (runtime)using those data. While generating those reports the application gets timed out and not able to generate reports. if the data is around 50k it is generating an excel file but when the data is in millions, the query is unable to run. Which is the best way to implement Index through Django Model or PostgreSQL Index? Please help me in optimizing the query to make it faster. Version PostgreSQL 13.1, compiled by Visual C++ build 1914, 64-bit EXPLAIN (ANALYZE,BUFFERS) Select V."MERCHANT_ID",V."ACCOUNT_NUMBER",V."GIFT_LIST_REF",(Select "store_id" FROM vd_store_master WHERE "store_id"=V."GIFT_LIST_REF") as owingin_store_id,(Select "store_name" FROM vd_store_master WHERE "store_id"=V."GIFT_LIST_REF") as owingin_store_name,(Select "franchisee_id" FROM vd_store_master WHERE "store_id"=V."GIFT_LIST_REF") as owingin_franchisee_id,(Select "franchisee_name" FROM vd_franchisee WHERE "franchisee_id"=(select "franchisee_id" FROM vd_store_master where store_id=V."GIFT_LIST_REF") ) as owingin_franchisee_name,(select "merchant_name" from vd_merchant_master where merchant_id=V."MERCHANT_ID") as merchant_name FROM vdaccount_card_assign V WHERE "MERCHANT_ID"='003561002966107' and "CARD_STATUS"='D' "QUERY PLAN" "Seq Scan on vdaccount_card_assign v (cost=0.00..2056093.85 rows=149948 width=1362) (actual time=0.144..7171.425 rows=154405 loops=1)" -
I am getting this error when i run migration with sudo premission in django
*Can anybody help me I get this error when I run migration with Sudo permission * File "/home/dell/.local/lib/python3.6/site-packages/django/db/migrations/graph.py", line 58, in raise_error raise NodeNotFoundError(self.error_message, self.key, origin=self.origin) django.db.migrations.exceptions.NodeNotFoundError: Migration auth.0013_auto_20210105_1445 dependencies reference nonexistent parent node ('auth', '0012_alter_user_first_name_max_length') -
List out of range error in my code in Django. When i go to download a pdf file
I want to download a patients pdf file but when i click in download button this error is come. Please anyone can help me about this error .. views.py def download_pdf_view(request,pk): dischargeDetails = PatientDischarge.objects.all().filter(admitted=pk).order_by('-id')[:1] dict = { 'assign_doctor': dischargeDetails[0].assign_doctor, 'admitted': dischargeDetails[0].admitted.patient_name, 'phone': dischargeDetails[0].admitted.phone, 'address': dischargeDetails[0].admitted.address, 'symptoms': dischargeDetails[0].admitted.symptoms, 'release_date': dischargeDetails[0].release_date, 'medicine_cost': dischargeDetails[0].medicine_cost, 'other_charge': dischargeDetails[0].other_charge, 'days_count': dischargeDetails[0].days_count, 'room_bill':dischargeDetails[0].room_bill, 'total_bill': dischargeDetails[0].total_bill, } return render_to_pdf('hospital/pdf_template.html',dict) models.py: class PatientDischarge(models.Model): assign_doctor = models.ForeignKey(Doctor, on_delete=models.CASCADE) admitted = models.ForeignKey(Admitted, on_delete=models.CASCADE) release_date = models.DateField(auto_now_add=False) medicine_cost = models.IntegerField(null=True) other_charge = models.IntegerField() def __str__(self): return self.admitted.patient_name if all([self.admitted, self.admitted.patient_name]) else 0 def days_count(self): return self.release_date - self.admitted.admited_date if all([self.admitted, self.admitted.admited_date]) else 0 -
Django unable to translate language
I want to translate my website to CH, but no response after I followed the online instruction. Did I miss something? I have changed the language code in setting.py setting.py import os import django_heroku from django.utils.translation import gettext_lazy as _ LANGUAGES = ( ('en', ('English')), ('zh-Hant', _('Traditional Chinese')), ) MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', ... ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMP_DIR], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.i18n', 'django.template.context_processors.debug', ....]} #LANGUAGE_CODE = 'en-us' LANGUAGE_CODE = 'zh-Hant' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True LOCALE_PATHS = [ os.path.join(BASE_DIR, 'locale') ] Added the tag for translation in html base.html: {% load i18n %} <!DOCTYPE html> <html> .... home.html: {% extends "base.html" %} {% load i18n %} {% block content %} {% trans "Let's translate this" %} .... Updated msgstr in ....\locale\zh-Hant\LC_MESSAGESdjango.po: msgid "Let's translate this" msgstr "來翻譯這個" -
How to access Django queryset when for loop is not possible
I'm making my portfolio site. Each project is developed with multiple technologies, such as a "website" created with Python, Django and Bootstrap. So I defined my models like this: class Technology(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class Meta: verbose_name_plural = 'Technologies' class Project(models.Model): name = models.CharField(max_length=200) description = models.TextField() date = models.DateField() technology = models.ManyToManyField(Technology) image = models.ImageField(upload_to='projects') def __str__(self): return self.name views.py: def index(request): projects = Project.objects.all() return render(request, 'homepage/index.html', context={'projects': projects}) Now here's the challenge: In my template I want to display 6 projects with the project name and technologies extracted from the '''queryobject'''. However right now I have only one project. So: How to display one set of HTML tags for first project and another set (placeholders) for the rest? So the first project shows the data from database, and the rest 5 show a "coming soon" (please refer to attached screenshot)? And later when I add the second and third projects to the database, the output update itself accordingly? Since the "technology" field is a manytomany field, there is more than one value in it (Python, Django, Bootstrap for example). How to access it in my template? -
Why does my heroku app not appear on google search results
I have deployed my django project on heroku. I can access my it via my domain www.example.com and I have comfirmed domain ownership on google search console.I have provided sitemaps on google search console and requested indexing. Its been about two days and i can not see my website on google search results. I have also tried using site:my_domain.com but still cannot find any results -
How to Reorder the position of objects in Django?
The code below is getting error AttributeError: 'WSGIRequest' object has no attribute 'request'. I want to reOrder the position of objects using JQuery sortable.js Drag and drop. the drag and drop frontend is working fine but when my code try to save the object position i'm getting the error 'WSGIRequest' object has no attribute 'request'. I would be grateful for any help. @csrf_exempt def sort(self): books = json.loads(self.request.POST.get('sort')) for b in books: book = get_object_or_404(Article, pk=int(b['pk'])) book.position = b['order'] book.save() return HttpResponse('saved') -
controlling/sharing/displaying phone functionality on a django website
I'm trying to build a Django dashboard for my business website where I'd like to be able to connect my phone to the dashboard. I'd like a functionality where if there is an incoming call, the dashboard should display customer details for the phone number and ideally I should also be able to pick up the call on the dashboard. (Lazy, you might think, but the phone isn't always at the desk!) Of course, the website resides remotely, and I'd like to be able to connect the phone over the local network or bluetooth. My implementation is to create a local script which will connect to the phone over bluetooth and when there is an incoming call, send signal to the website server, display on my screen a notification and customer details, then when I press receive on the dashboard send a signal back to the script which will send a signal to the phone which will then pick up the call. I have all the pieces (but still if there is a better implementation, let me know), except how to get a signal from the phone on incoming call on bluetooth. I searched high and low, but could not … -
Using Redis server in pythonanywhere
So I made a Django App that works as a real time chat, this chat works with the redis server, and also with js websockets, the problem is that I would like to know if this chat will work in pythonanywhere and if it works, how can I do it? is it the same process? do I need to add something else? -
retrieve distinct values of manytomanyfield of another manytomanyfield
I have a simple question but multiple google searches left me without a nice solution. Currently I am doing the following: allowed_categories = self.allowed_view.all().difference(self.not_allowed_view.all()) users = [] for cat in allowed_categories: for member in cat.members.all(): users.append(member) return users I have a ManyToManyField to Objects that also have a ManyToManyField for instances of Users. In the code above, I am trying to get all the users from all those categories and get a list of all Users. Later I would like the same in a method allowed_to_view(self, user_instance) but that's for later. How would I achieve this using Django ORM without using 2 for-loops? -
Django-channels error during websocket handshake: unexpected response code: 404 local
When trying to connect to websocket getting response code 404. library versions: channels==3.0.3 channels-redis==3.2.0 Django==3.0.5 django-environ==0.4.5 djangorestframework==3.12.2 djongo==1.3.3 settings.py: ASGI_APPLICATION = "core.asgi.application" CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [("127.0.0.1", 6379)], }, }, } asgi.py: import os import apps.visitors.routings from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from channels.security.websocket import AllowedHostsOriginValidator from django.core.asgi import get_asgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "core.settings") application = ProtocolTypeRouter( { "http": get_asgi_application(), "websocket": AllowedHostsOriginValidator( AuthMiddlewareStack(URLRouter(apps.visitors.routings.websocket_urlpatterns)) ), } ) routings.py: from django.urls import re_path from .consumers import TrackConsumer websocket_urlpatterns = [ re_path(r"ws/track/$", TrackConsumer.as_asgi()), ] consumers.py: from channels.consumer import AsyncConsumer class TrackConsumer(AsyncConsumer): async def websocket_connect(self, event): print("connected", event) await self.send({"type": "websocket.accept"}) async def websocket_receive(self, event): print("receive", event) async def websocket_disconnect(self, event): print("disconnected", event) Redis server is running locally. _._ _.-``__ ''-._ _.-`` `. `_. ''-._ Redis 3.2.9 (00000000/0) 64 bit .-`` .-```. ```\/ _.,_ ''-._ ( ' , .-` | `, ) Running in standalone mode |`-._`-...-` __...-.``-._|'` _.-'| Port: 6379 | `-._ `._ / _.-' | PID: 14918 `-._ `-._ `-./ _.-' _.-' |`-._`-._ `-.__.-' _.-'_.-'| | `-._`-._ _.-'_.-' | http://redis.io `-._ `-._`-.__.-'_.-' _.-' |`-._`-._ `-.__.-' _.-'_.-'| | `-._`-._ _.-'_.-' | `-._ `-._`-.__.-'_.-' _.-' `-._ `-.__.-' _.-' `-._ _.-' `-.__.-' 14918:M 14 Jan 17:14:29.439 # Server … -
Django Fast Access for Time Series Data
I'm working on a web application with Django & PostgreSQL as Backend tech stack. My models.py has 2 crucial Models defined. One is Product, and the other one Timestamp. There are thousands of products and every product has multiple timestamps (60+) inside the DB. The timestamps hold information about the product's performance for a certain date. class Product: owner = models.ForeignKey(AmazonProfile, on_delete=models.CASCADE, null=True) state = models.CharField(max_length=8, choices=POSSIBLE_STATES, default="St.Less") budget = models.FloatField(null=True) product_type = models.CharField(max_length=17, choices=PRODUCT_TYPES, null=True) name = models.CharField(max_length=325, null=True) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name="children") class Timestamp: product = models.ForeignKey(Product, null=True, on_delete=models.CASCADE) product_type = models.CharField(max_length=35, choices=ADTYPES, blank=True, null=True) owner = models.ForeignKey(AmazonProfile, null=True, blank=True, on_delete=models.CASCADE) clicks = models.IntegerField(default=0) spend = models.IntegerField(default=0) sales = models.IntegerField(default=0) acos = models.FloatField(default=0) cost = models.FloatField(default=0) cpc = models.FloatField(default=0) orders = models.IntegerField(default=0) ctr = models.FloatField(default=0) impressions = models.IntegerField(default=0) conversion_rate = models.FloatField(default=0) date = models.CharField(null=True, max_length=25) I'm using the data for a dashboard, where users are supposed to be able to view their products & the performance of the products for a certain daterange inside a table. For example, a user might have 100 products inside the table and would like to view all data from the past 2 weeks. For this scenario, I'll describe the … -
How can I make page for 403 and 404 errors in Django?
In other website like github I saw when the path is not found it returns error template for example look at github.com/ddfushdvbjkvuirfjvscvuiihkbfdsuhkb this page does not exist. Also I want to make for deleted path's that returns 403 error. Please send me some docs I didnt find out :| -
How to hide field from admin change page but keep it in admin add page in Django
I have a data model in which some fields can only be set initially per each instance of the class, and once set, they should never change. The only way that can be allowed to change such an object should be by deleting it and creating a new one. Pseudo code: from django.db import models from django.core.exceptions import ValidationError class NetworkConnection(models.Model): description = models.CharField(max_length=1000) config = models.CharField(max_length=1000) connection_info = models.CharField(max_length=5000) def clean(self): from .methods import establish_connection self.connection_info = establish_connection(self.config) if not self.connection_info: raise ValidationError('Unable to connect') def delete(self): from .methods import close_connection close_connection(self.config) super(NetworkConnection, self).delete() As in the above code, the user should initially input both the config and the description fields. Then Django verifies the config and establishes some sort of network connection based on such configurations and saves its information to another field called connection_info. Now since each object of this class represents something that cannot be edited once created, I need to hind the config field from the admin page that edits the object, leaving only the description field; However, the config field still needs to be there when adding a new connection. How do I do this? The following is an example of my last admin.py … -
How to save a MultipleChoiceField in Django
I was wondering how can I save a MultipleChoiceField to Django's database (in form submission)? models.py class Model1(models.Model): field = models.CharField(max_length=200, null=False, blank=False, default='') forms.py OPTIONS = ( ('Option 1', 'Option 1'), ('Option 2', 'Option 2'), ('Option 3', 'Option 3'), ) class Model1Form(forms.ModelForm): field = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=OPTIONS) class Meta: model = Model1 fields = '__all__' If you need additional information let me know! Thanks for helping out. -
How to integrate paypal in React Js with server side ( Django REST ) payment execution?
I am trying to integrate paypal in my application. My application has to be built using React JS and backend should be in Django. I have done the Client Side Integration using one npm package which is https://www.npmjs.com/package/react-paypal-express-checkout This is my code in React JS import React from "react"; import ReactDOM from "react-dom"; import PaypalExpressBtn from "react-paypal-express-checkout"; import "./styles.css"; function App() { const client = { sandbox: "AXMUBOcaszqCzfEOC-r--Rn7rMVoEbH9c6XbmyKb04nURqcLhpFxWwwnaUytaMR9UTaE2vwLfi5tqKbT", production: "" }; return ( <div className="App"> <h1>Hello CodeSandbox</h1> <h2>Start editing to see some magic happen!</h2> <PaypalExpressBtn client={client} currency={"USD"} total={500} onSuccess={(p) => console.log(p)} /> </div> ); } const rootElement = document.getElementById("root"); ReactDOM.render(<App />, rootElement); I am getting the following response { paid: true cancelled: false payerID: "TLCF8J8F3CZUY" paymentID: "PAYID-MAADRGI6U311288V5285313C" paymentToken: "EC-32J40105H07711055" returnUrl: "https://www.paypal.com/checkoutnow/error?paymentId=PAYID-MAADRGI6U311288V5285313C&token=EC-32J40105H07711055&PayerID=TLCF8J8F3CZUY" address: Object email: "sb-ueclm4695520@personal.example.com" } After the payment, also my sandbox account balance is been deducted. So this is working fine. But I want to do the payment execution securely in server side. How do i achieve it in Django? I have read the docs, they mentioned use SDK. So I have looked into the python sdk which is https://github.com/paypal/Checkout-Python-SDK from paypalcheckoutsdk.orders import OrdersCaptureRequest # Here, OrdersCaptureRequest() creates a POST request to /v2/checkout/orders # Replace APPROVED-ORDER-ID with the actual … -
Error when converting pandas to postgers in django app
Goal: adding data from a fetched json file into a postgres database. Error when running the script: RuntimeError: Model class django.contrib.contenttypes.models.ContentType doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. After fetching the data from a link (json), i convert and edit it with pandas. Once done, the goal is to add it to the databas, but i get the mentioned error. The code snippet i use is taken from this answer. [https://stackoverflow.com/questions/37688054/saving-a-pandas-dataframe-to-a-django-model] second_pipeline.py (gets the error) import pandas as pd import requests fox_url = "https://saurav.tech/NewsAPI/everything/fox-news.json" fox_news = requests.get(fox_url).json() df = pd.json_normalize(fox_news) fox_articles = pd.json_normalize(df["articles"].loc[0]) del fox_articles['source.id'] fox_articles["date_publised"] = pd.to_datetime(fox_articles['publishedAt']) del fox_articles['publishedAt'] import os from django.conf import settings import django os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backend.settings') settings.configure(DEBUG=True) django.setup() from sqlalchemy import create_engine from models import Article user = settings.DATABASES['default']['USER'] password = settings.DATABASES['default']['PASSWORD'] database_name = settings.DATABASES['default']['NAME'] database_url = 'postgresql://{user}:{password}@localhost:5432/{database_name}'.format( # user=user, # password=password, # database_name=database_name, article_author = fox_articles["author"], article_date_publised = fox_articles["date_publised"], article_title = fox_articles["title"], article_description = fox_articles["description"], article_url = fox_articles["url"], article_urlToImage = fox_articles["urlToImage"], article_content = fox_articles["content"], article_network = fox_articles["source.name"], ) engine = create_engine(database_url, echo=False) fox_articles.to_sql(Article, con=engine) models.py class Article(models.Model): article_author = models.CharField(blank=True, max_length=1000) article_date_publised = models.CharField(blank=True, max_length=500) article_title = models.TextField(blank=True) article_description = models.TextField(blank=True) article_url = models.TextField(blank=True) article_urlToImage = models.TextField(blank=True) article_content = models.TextField(blank=True) … -
match two models field (django)
I have a question answer quiz. I want each form to be responsible for each query when I publish the forms in html. For example I have it now current result. I have to choose the question manually. I want it to happen automatically, i.e. no matter how many questions I have so many forms for each question. what i want -> the end result. I do not understand what I have to change, view or formset should I use, please if you can help me change the code. models.py from django.db import models # Create your models here. class Question(models.Model): question=models.CharField(max_length=100) answer_question=models.CharField(max_length=100, default=None) def __str__(self): return self.question class Answer(models.Model): questin=models.ForeignKey(Question, on_delete=models.CASCADE) answer=models.CharField(max_length=100,blank=True) def __str__(self): return str(self.questin) views.py from django.shortcuts import render from django.shortcuts import render, HttpResponse from django.http import HttpResponseRedirect from django.shortcuts import redirect from .forms import QuestionForm,AnswerForm from .models import Question import random def home(request): form=QuestionForm if request.method=='POST': form=QuestionForm(request.POST) if form.is_valid(): form.save() return render(request, "question/base.html", {"form":form}) def ans(request): form=AnswerForm e=Question.objects.all() if request.method=="POST": form=AnswerForm(request.POST) if form.is_valid(): form.save() return render(request, "question/ans.html", {"form":form, "e":e}) forms.py from django import forms from django.contrib.auth.models import User from django.core.exceptions import ValidationError from django.forms import ModelForm from .models import Question,Answer class QuestionForm(forms.ModelForm): class Meta: model=Question fields="__all__" …