Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use django signal inside async function?
I have the following async function that notify users when the DB changed. I tried to skip using async function and use normal function instead but I can't do that. I must use django signals inside the async function and return the signal from inside it. async def liveSignals_generator(obj, info): while True: @receiver(post_save, models.Post) def do_stuff(instence): print('test=======') yield instence.id problem when I use the receiver inside async function it act like it does not exist at all. Also, is it possible to use await inside liveSignals_generator before do_stuff? Goal any possible approach to to return/yield the new signals data from inside the liveSignals_generator. Maybe we can create an external function that connect these .... -
graphene-django: Why ENUMS in grahene-django returns the value instead of key?
When i create candidate, It return the value of the enum instead of the key. e.g. When i select "FRESH_AND_LOOKING" in mutation to create candidate it returns"Unemployed. Looking for job". I need the actual key of enum instead of value This is model class Candidate(models.Model): class JobStatus(models.TextChoices): FRESH_AND_LOOKING = "Unemployed. Looking for job" WORKING_BUT_LOOKING = "Working but looking for new opportunities" NOT_LOOKING = "Not looking for job" date_of_birth = models.DateField() address = models.CharField(max_length=300) job_status = models.CharField(max_length=100, choices=JobStatus.choices) This is enums class JobStatusEnum(graphene.Enum): FRESH_AND_LOOKING = "Unemployed. Looking for job" WORKING_BUT_LOOKING = "Working but looking for new opportunities" NOT_LOOKING = "Not looking for job" This is arguments class CandidateInput(graphene.InputObjectType): date_of_birth = graphene.Date() address = graphene.String(required=False) job_status = graphene.Field(JobStatusEnum, required=False) This is type class CandidateType(DjangoObjectType): class Meta: model = Candidate fields = "__all__" This is mutation class CreateCandidate(graphene.Mutation): _candidate = graphene.Field(CandidateType) class Arguments: input = CandidateInput(required=True) @classmethod def mutate(cls, root, info, input=None): candidate = Candidate.objects.create(**input) return CreateCandidate(_candidate=candidate) -
Sending the response of an API from one server, through API of another server
Below is the response from a endpoint of a server(server1). I need to build an API and send the same response through different server(server2). Reason being I cannot expose anything related to server1. Problem is,how to point the doc_url file links which are coming from server1 to server2. I'm trying to do this using Django Rest Framework CBV. "data": [ { "issue_date": "2019-06-13", "attachments": [ { "doc_name": "three.pdf", "doc_url": "http://server_url/_uploads/person/39/three.pdf } ] }, { "issue_date": "2019-06-13", "attachments": [ { "doc_name": "two.pdf", "doc_url": "http://server_url/_uploads/person/39/two.pdf" }, { "doc_name": "one.jpg", "doc_url": "http://server_url/_uploads/person/39/one.jpg" }, ] } ] -
TypeError at / 'NoneType' object is not iterable Request Method: GET Request URL: http://localhost:8000/
When I run my Django application I get this error TypeError at / 'NoneType' object is not iterable Request Method: GET Request URL: http://localhost:8000/ Django Version: 3.2.8 Exception Type: TypeError Exception Value: 'NoneType' object is not iterable , line 32, in user_login_request return render(request=request, template_name="auth/tg_login.html", context=context) In my views.py this is what I have def user_login_request(request): print('calling user_login_request') if request.method == "POST": print('calling user_login_request POST') # a form bound to the POST data login_form = TGArchiveUserLoginForm(request.POST) if login_form.is_valid(): # print('calling login_form.is_valid()') username = login_form.cleaned_data.get("user_login_name") password = login_form.cleaned_data.get("user_login_password") user = authenticate(request, username=username, password=password) if user is not None: login(request, user) # print("You have logged in as " + request.user.username) messages.info(request, f"You are now logged in as {username}.") return redirect(reverse('members:dashboard')) else: messages.error(request, "Invalid username or password.") return redirect('/') else: messages.error(request, "Invalid username or password.") context = { 'user_login_form': TGArchiveUserLoginForm() } return render(request=request, template_name="auth/tg_login.html", context=context) I have changed the template name and send a blank context to the template and still get the same error code. -
run daphne with fabric without blocking the terminal
I installed Daphne on my Django app and it works fine. But when I run Daphne from fabric, fabric does not return to the line on the termial. I would like to run daphne and not be blocked by fabric. i have this to : I have to do a ctrl c to return to the line but i want it to do it automatically And i would like to have this after start : here is the fabric code : def _start(c, server="dev", con=None): """start asgi server""" con = con if con else get_con(server, user=DEFAULT_WEB_USER, enrich=True) con.run("daphne -p 8000 myproject.asgi:application") -
Django - Serialized model of type User is not JSON serializable
I'm currently trying to find out how setup a API for my app using the django rest framework. Currently I have the following two files: serializers.py: from rest_framework import serializers, permissions from App_Accounts.models import User class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('user',) views.py from rest_framework import permissions from rest_framework.decorators import api_view, permission_classes from rest_framework.response import Response @api_view(['GET']) @permission_classes((permissions.AllowAny,)) def current_user(request): user = request.user return Response({ 'user': user, }) When I open: http://localhost/api/current_user/ it just get the following error returned at my console: File "/usr/local/lib/python3.9/json/encoder.py", line 179, in default raise TypeError(f'Object of type {o.__class__.__name__} ' TypeError: Object of type User is not JSON serializable I don't know how important it is but I'm using a custom User model -
Too long select if using JSON fields
There are two connected models from django.contrib.postgres.indexes import GinIndex from django.db import models class Model(models.Model): name = models.CharField(max_length=128, db_index=True) attributes = models.JSONField(null=True) class Meta: db_table = 'models' indexes = [GinIndex(fields=['attributes'])] class Offer(models.Model): price = models.DecimalField(decimal_places=2, max_digits=8, db_index=True) quantity = models.SmallIntegerField() model = models.ForeignKey('Model', related_name='offers', on_delete=models.CASCADE) class Meta: db_table = 'offers' indexes = [GinIndex(fields=['attributes'])] When I make queries using several offer attributes, it takes to many time. What wrong with this code? I have about 5000 models and about 300 000 offers in my db. Query takes about 20 seconds. If I use only one attribute from offer it's ok. result = ( Model.objects .prefetch_related('offers') .filter(attributes__param1='value1') .filter(attributes__param2=False) .filter(offers__attributes__width='255') .filter(offers__attributes__height='55') .filter(offers__attributes__diameter='16') ) -
ModuleNotFoundError: No module named 'myproject.settings'
So, i try to upload my python django website to PYTHONANYWHERE, and when i try to run the website is error they say Something Went Wrong, so i try to look at the logs, and that logs say this 2021-10-07 12:11:37,339: ModuleNotFoundError: No module named 'myproject.settings' 2021-10-07 12:11:37,339: File "/var/www/webtest_pythonanywhere_com_wsgi.py", line 29, in <module> 2021-10-07 12:11:37,340: application = get_wsgi_application() 2021-10-07 12:11:37,340: 2021-10-07 12:11:37,340: File "/home/webtest/.virtualenvs/mynenv/lib/python3.9/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application 2021-10-07 12:11:37,340: django.setup(set_prefix=False) 2021-10-07 12:11:37,340: 2021-10-07 12:11:37,340: File "/home/webtest/.virtualenvs/mynenv/lib/python3.9/site-packages/django/__init__.py", line 19, in setup 2021-10-07 12:11:37,340: configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) 2021-10-07 12:11:37,340: 2021-10-07 12:11:37,340: File "/home/webtest/.virtualenvs/mynenv/lib/python3.9/site-packages/django/conf/__init__.py", line 82, in __getattr__ 2021-10-07 12:11:37,341: self._setup(name) 2021-10-07 12:11:37,341: 2021-10-07 12:11:37,341: File "/home/webtest/.virtualenvs/mynenv/lib/python3.9/site-packages/django/conf/__init__.py", line 69, in _setup 2021-10-07 12:11:37,341: self._wrapped = Settings(settings_module) 2021-10-07 12:11:37,341: 2021-10-07 12:11:37,341: File "/home/webtest/.virtualenvs/mynenv/lib/python3.9/site-packages/django/conf/__init__.py", line 170, in __init__ 2021-10-07 12:11:37,341: mod = importlib.import_module(self.SETTINGS_MODULE) 2021-10-07 12:11:37,342: *************************************************** 2021-10-07 12:11:37,342: If you're seeing an import error and don't know why, 2021-10-07 12:11:37,342: we have a dedicated help page to help you debug: 2021-10-07 12:11:37,342: https://help.pythonanywhere.com/pages/DebuggingImportError/ 2021-10-07 12:11:37,342: *************************************************** And,i research in google and youtube and i get this way to solve the error, and i try that way. So i run this python -m venv myproject command in the root directory, with mynenv running,still not working … -
Not Found: /callback/ Error. i want my payment_reponse function to update order.paid to True, save to database and return a done.html page
#orders.view# The payment completes successfully. but instead of setting order.pad=True, saving and redirecting to the orders:done and orders:canceled it returns "Not Found: /callback/" error from django.shortcuts import render, redirect from django.urls import reverse from cart.cart import Cart from .models import OrderItem, Order from .forms import OrderCreateForm from .tasks import order_created from django.views.decorators.csrf import csrf_exempt from django.http import HttpResponse from django.shortcuts import get_object_or_404 from django.views.decorators.http import require_http_methods from django.template import loader from decimal import Decimal import environ import random import math import requests env = environ.Env() environ.Env.read_env() def order_create(request): cart = Cart(request) if request.method == 'POST': form = OrderCreateForm(request.POST) total_cost = cart.get_total_price() if form.is_valid(): name = form.cleaned_data['last_name'] email = form.cleaned_data['email'] amount = f'{total_cost:.2f}', phone = form.cleaned_data['phone'] order = form.save() for item in cart: OrderItem.objects.create(order=order, product=item['product'], price=item['price'], quantity=item['quantity']) # clear the cart cart.clear() # launch asynchronous task order_created.delay(order.id) request.session['order_id'] = order.id return redirect(str(process_payment(name, email, amount, phone))) else: form = OrderCreateForm() return render(request, 'orders/order/create.html', {'cart': cart, 'form': form}) def process_payment(name, email, amount, phone): auth_token = env('SECRET_KEY') hed = {'Authorization': 'Bearer ' + auth_token} data = { "tx_ref": ''+str(math.floor(1000000 + random.random()*9000000)), "amount": amount, "currency": "NGN", "redirect_url": "http://localhost:8000/callback", "payment_options": "card", "meta": { "consumer_id": 23, "consumer_mac": "92a3-912ba-1192a" }, "customer": { "email": email, "phonenumber": phone, "name": name … -
Post non-persisting model with dictionary attribute with REST Framework in Django
I want to make a post request where I request an object containing free text, process it, and respond with another object containing a collection with the corrections per word. In Django, every model.Models class gets a DB table, but I do not want to store either the request or the response. I just want to use the server to compute the spell checker. The class I want to request is the following: class FreeText(models.Model): text = models.TextField() class Meta: db_table="free_text" Even though here I use a models.Model, It may be a regular class. The class I want to respond with is the following: class SpellCheckedText(): def __init__(self, text: str, spell_dict: dict): self.text = text self.spell_dict = spell_dict To serialize it, I tried something like the following, but I do not see any field type fitting of a dictionary. class CommentSerializer(serializers.Serializer): text = serializers.TextField() spell_dict = serializers.... How should I build the serializer and the post request? -
Django_Crontab does not seem to run
hoping I can get some guidance on django crontab. I have the following set up: in settings.py: INSTALLED_APPS = [ 'django_crontab', ........ ] #other settings not related to crontab CRONJOBS = [ ('*/1 * * * * ', 'my_app.cron.cronjob') ] in my my_app/cron.py(for now I have a model with the name 'name'): def cronjob(): total_ref = models.Count.objects.get(name='name') total_ref.total += 1 total_ref.save() return() in my my_app/models.py: class Count(models.Model): name = models.CharField(max_length=100, blank=True, null=True) total = models.IntegerField(blank=True, null=True) def __str__(self): return self.name When i run the following: $ python manage.py crontab add crontab: no crontab for user adding cronjob: (26ea74b6ee863259e86bcab90f96ec1a) -> ('*/1 * * * * ', 'ms_app.cron.switch_count') And when i check to see if it is in my crontab $ crontab -l */1 * * * * /Path_to_env/bin/python /Path_to_my_app/my_project/manage.py crontab run 26ea74b6ee863259e86bcab90f96ec1a # django-cronjobs for myl_project i am running python 3.8.2 with Django 3.2.5 and django_crontab 0.7.1 With all of this checked I still do not get any changes when I go and check my model entry (total) -
Storing likes and follows informations in different models gives me error: most likely due to a circular import
I have two models: Product and User class Product(models.Model): #here are information fields about Product likes = models.ManyToManyField( User, related_name="product_likes", blank=True) object = models.Manager() productobjects = ProductObjects() def __str__(self): return self.name class User(AbstractBaseUser, PermissionsMixin): #here are information fields about User followed = models.ManyToManyField( Product, related_name="followed_products", blank=True) objects = CustomAccountManager() object = models.Manager() def __str__(self): return self.email Inside Product I need to have a likes filed ManyToMany which store which users liked the product. Inside User I need to have followed field ManyToMany which store which products the user follow. I have an error: cannot import name 'Product' from partially initialized module 'product.models' (most likely due to a circular import). How can I fix it? Or maybe can I do this differently? The problem is that inside product.models I import: from users.models import User and inside users.models I import: from product.models import Product. (I am using the likes filed just to GET number of likes, but from followed I need to GET all the products that specified user follow and informations about them) -
How can I install djangoshop-sendcloud?
I'm trying to install djangoshop-sendcloud package by using pip. But following error occure. UnicodeDecodeError: 'cp950' codec can't decode byte 0xe2 in position 529: illega l multibyte sequence How can I fix this error and install package. -
django UniqueConstraint error in email field (sendgrid verification email)
I am tryting to implement sendgrid email verification to my django project. I have been following https://www.twilio.com/blog/send-dynamic-emails-python-twilio-sendgrid tutorial. I have models and views setup accordingly however, I am facing UniqueConstraint error when trying to use the same email address twice (although my model has Email Field set to unique = True. My error: Exception Type: IntegrityError Exception Value: UNIQUE constraint failed: newsletter_newsletteruser.email My models.py: from django.db import models class NewsletterUser (models.Model): email= models.EmailField(unique=True) date_added = models.DateTimeField(auto_now_add=True) conf_num = models.CharField(max_length=15) confirmed = models.BooleanField(default=False) def __str__(self): return self.email + " (" + ("not " if not self.confirmed else "") + "confirmed)" my admin.py from .models import NewsletterUser, MailMessage # Register your models here. class NewsletterAdmin(admin.ModelAdmin): list_display = ('email','date_added','conf_num', 'confirmed') admin.site.register(NewsletterUser, NewsletterAdmin) admin.site.register(MailMessage) my views.py from django.db.models.fields import EmailField from django.shortcuts import render, redirect from sendgrid.helpers.mail.bcc_email import Bcc from django.http import HttpResponse from .forms import NewsletterUserForm, MailMessageForm from django.contrib import messages from django.contrib.auth.decorators import login_required import os from sendgrid import SendGridAPIClient from sendgrid.helpers.mail import Mail, Email, Content, To from .models import NewsletterUser from django import forms import pandas as pd from django.shortcuts import render from django.http import HttpResponse from django.conf import settings from django.views.decorators.csrf import csrf_exempt import random from sendgrid import SendGridAPIClient # … -
Unable to add authtoken to request user
I am trying to add authtoken to request user but it return tuple. I need to add knox token "not simple token". from knox.models import AuthToken user = request.user token = AuthToken.objects.create(user=user) print(token) print(user.auth_token) This is the result (<AuthToken: 7c08e0867b36353dd0a99b8c5a3ce9d16edea0db121b0c46cde35b7b1117fd35d226aa084aac0136c3a2dbbf202626e99a1940a93089dc6b2236366127ccf238 : ali>, 'bb0935da5ace12d54f4f879645656196585d1314ea53061130db5c3b3cfc1f6b') User has no auth_token. -
Heroku H10 error while deploying django app
The following error shows up every time! Any fixes for the same? 2021-10-07T10:47:31.133956+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=zturlshortener.herokuapp.com request_id=c2f90e55-52f5-4955-a1d6-4028456cfddb fwd="103.199.173.31" dyno= connect= service= status=503 bytes= protocol=https Procfile web: gunicorn UrlShortener.wsgi --log-file - Settings.py import os from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent DEBUG = False ALLOWED_HOSTS = ['127.0.0.1', 'zturlshortener.herokuapp.com'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'UrlShortApp' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'UrlShortener.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'UrlShortener.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') DISABLE_COLLECTSTATIC=1 DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' wsgi.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'UrlShortener.settings.dev') application = get_wsgi_application() -
why am i getting redirecting to wrong view in django?
I am trying to render to different page using URLs in django,I have written all codes as the tutorials as well, urlpatterns = [ path('admin/', admin.site.urls), path('', views.index,name="index"), path('', views.register,name="register"), path('', views.login,name="login") ] def index(request): print("hello index") return render(request,'index.html') def register(request): return render(request,'register.html') def login(request): print("hello login") return render(request,'login.html') but, whenever I hit that register link on my HTML it just always takes me to index.html. <ul class="nav"> <li><a href="{% url 'index' %}"> Home</a></li> <li><a href="{% url 'register' %}"> Register</a></li> <li><a href="{% url 'login' %}"> Login</a></li> </ul> I have also tried putting something in the routes urlpatterns = [ path('admin/', admin.site.urls), path('index', views.index,name="index"), path('register', views.register,name="register"), path('login', views.login,name="login") ] but this time it gives errors like The empty path didn’t match any of these. I have worked on different django project using the above pattern and it was working perfectly fine.Where am I making it wrong? Any help would greatly be appreciated! -
how to display values related to items in django
let us consider when we filter batch and area we get items for example let us consider batch = 1000 and area = A01 and when filtering the Items tables with these batch and area as a result we get 3 items id item_name season_support 1 small tree [u'Winter', u'Year round'] 2 medium tree [u'Spring', u'Autumn'] 3 big tree [u'Summer', u'Rainy'] Now while printing in the pdf let us consider my index.html as {% for item in items %} <table> <tr> <td>Item id - {{ item.id }}</td> <td>Item name - {{item.item_name}} </td> <td>Season support - {{ item.season_support }} </td> </tr> </table> now please help to write views.py where i can print the season_support that are related those items only -
Is it possible to select what you want to delete in Django API PUT?
I have the following page: This pages does the following, edit data by keying new inputs provided by user and also a table which has the interface registered and each of the interface has it's own checkbox. In case user want to delete certain interface, the user can select the checkbox and press save button for the code to do the changes. I was wondering if in the Django API framework, is it possible to something similar to this? I already created an API view to edit the part where user can type in new data to update existing data but i was wondering if within the API, can the deletion be done done ? If can, how is it done? Below are my codes : models.py class DeviceDetail(models.Model): SUBNET_CHOICES = ( ('16','16'), ('17', '17'), ('18','18'), ('19','19'), ('20','20'), ('21', '21'), ('22', '22'), ('23', '23'), ('24', '24'), ('25', '25'), ('26', '26'), ('27', '27'), ('28', '28'), ('29', '29'), ('30', '30'), ) DEV_MODS =( ('Catalyst 9606R', 'Catalyst 9606R'), ('C9300L-48T-4X', 'C9300L-48T-4X') ) mgt_interface = models.CharField(max_length=50) subnetmask = models.CharField(max_length=2, choices = SUBNET_CHOICES) ssh_id = models.CharField(max_length=50) ssh_pwd = models.CharField(max_length=50) enable_secret = models.CharField(max_length=50) dev_mod=models.CharField(max_length=50, choices = DEV_MODS) ##device_model replacement DD2DKEY = models.ForeignKey(Device, on_delete=models.CASCADE) ##The key to link … -
Uncaught TypeError: Cannot read properties of undefined (reading 'start')
Started getting this error today on my Django project. Found a fix which I think can help others. -
Refrain Django Models from creating an object after a specific count of that object in db is reached, for a specific user
I want to have a method to somehow show an error/prompt to the front end (could be json response), whenever user tries to add an object, in my case, 1 user cannot have more than 50 tasks stored inside the db, my db model is simple, it's just a task model, and a user model, each task has a foreign key user_id. I was doing it in golang-gorm using hooks, is there any similar method in Django to do so efficiently? -
Creating sub-categories in Django Admin without creating a new app
I was wandering wether it is possible to create sub-categories for models in the Django administration panel. Let's assume I have an app called "MyApp" which contains 2 model classes called "foo" and "bar". In my admin panel I will see the name of the the app and my two models listed under it (once registered in admin.py). What I want is to create a sub-category in the admin panel which would look like this: MyApp first model name --> new sub category foo second model name --> new sub cateogry bar Thank you for your time, Cheers -
Using RequestFactory in testing views that are not in urls.py
I would like to test my custom decorator (just a custom protection, similar to @login_required). For this purpose, I am creating two dummy views: def foo(request): return JsonResponse('ok', safe=False) @my_custom_decorator def protected_foo(request): return JsonResponse('ok', safe=False) Obviously, they are not mentioned in urls.py - they are just a simple views to be used in the unit test. What I will try to do, is to just: request = RequestFactory().get() <== this is wrong response = foo(request) assert response.status_code == 200 # check if decorator works when no value is provided failed_response = protected_foo(request) assert failed_response.status_code == 403 # check if decorator works when the value is provided in GET request = RequestFactory().get(f'?SECRET_VALUE={the_secret_value}') <== this is wrong response = protected_foo(request) assert response.status_code == 200 # check if decorator works when the value is provided in GET request = RequestFactory().post('', {'SECRET_VALUE': the_secret_value}) <== this is wrong response = protected_foo(request) assert response.status_code == 200 My question is - how to pass data to RequestFactory craft a GET or POST request containing values, when the views are not connected to the urls.py? In other words - what should be in lieu of the lines containing this is wrong? -
How to connect Postgres Database with Django and show the result on HTML?
I'm new to Django. Currently, I'd like to make a simple web app using Django and Postgre SQL (localhost). Currently, I want to show the connection result ("success/not") on an HTML page and retrieve the data from DB using rest API (next task). This is my project structure: C:. ├───DBD │ └───__pycache__ ├───demopage │ ├───migrations │ │ └───__pycache__ │ ├───templates │ └───__pycache__ ├───restapi │ ├───migrations │ │ └───__pycache__ │ └───__pycache__ └───src └───__pycache__ I create a DB connection module DbLoader.py in src folder. import psycopg2 import json class DbLoader: def __init__(self, host, port, dbname, user, password): # postgres self.host = host self.port = port self.dbname = dbname self.user = user self.password = password def connectDB(self): # connection information conn = 'host = {host} port = {port} dbname = {dbname} user = {user} password = {password}'.format( host = self.host, port = self.port, dbname = self.dbname, user = self.user, password = self.password ) # establish connection print(conn) self.db = psycopg2.connect(conn) self.cur = self.db.cursor() def view_connDB(self): sql = 'SELECT VERSION()' self.cur.execute(sql) result = self.cur.fetchone() self.db.close() # return connection result and show in HTML ! return result def view_table(self): sql = """SELECT table_name FROM information_schema.tables WHERE table_schema = 'public'""" self.cur.execute(sql) result = self.cur.fetchall() cols = … -
Use regular class with Django
I want to make a post request where I request an object containing free text, process it, and respond with another object containing a collection with the corrections per word. In Django, every model.Models class gets a DB table, but I do not want to store either the request or the response. I just want to use the server to compute the spell checker. I cannot seem to figure out how to build a serializer from a regular class.