Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Docker and CloudSQL proxy
I'm having problems connecting my Django server to my Postgres database hosted on Google Cloud through CloudSQL Proxy with Docker. Currently, I have a Docker compose file that looks like this version: '3' services: cloud-sql-proxy: image: gcr.io/cloudsql-docker/gce-proxy command: /cloud_sql_proxy --dir=/cloudsql -instances=gamr-335802:us-central1:gamr=tcp:0.0.0.0:5432 -credential_file=/django_backend/gamr-335802-e8f23fcc176c.json ports: - "5432:5432" volumes: - /cloudsql:/cloudsql - ./gamr-335802-e8f23fcc176c.json:/django_backend/gamr-335802-e8f23fcc176c.json restart: always gamr-backend: build: ./ command: ./runner.sh volumes: - .:/django ports: - "8000:8000" depends_on: - cloud-sql-proxy I think it may be an issue with the volumes of the cloud-sql-proxy but I'm not certain. I get an error that looks like this cloud-sql-proxy_1 | 2021/12/28 22:21:17 current FDs rlimit set to 1048576, wanted limit is 8500. Nothing to do here. cloud-sql-proxy_1 | 2021/12/28 22:21:17 using credential file for authentication; email=serviceacc@gamr-335802.iam.gserviceaccount.com cloud-sql-proxy_1 | 2021/12/28 22:21:18 Listening on 0.0.0.0:5432 for gamr-335802:us-central1:gamr cloud-sql-proxy_1 | 2021/12/28 22:21:18 Ready for new connections cloud-sql-proxy_1 | 2021/12/28 22:21:18 Generated RSA key in 389.763737ms gamr-backend_1 | Performing system checks... gamr-backend_1 | gamr-backend_1 | System check identified no issues (0 silenced). gamr-backend_1 | Traceback (most recent call last): gamr-backend_1 | File "/usr/local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 230, in ensure_connection gamr-backend_1 | self.connect() gamr-backend_1 | File "/usr/local/lib/python3.8/site-packages/django/utils/asyncio.py", line 25, in inner gamr-backend_1 | return func(*args, **kwargs) gamr-backend_1 | File "/usr/local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 211, in connect … -
Django TypeError: InstagramBot() takes 1 positional argument but 2 were given
I am confused as to why I am getting to 2 positional arguments when I simply just run the code below, it works perfectly fine but when I receive the inputs from Django I have 2 positional arguments. Test.py from InstagramBot import InstagramBot X = InstagramBot("equinox_api", "Blast123!") InstagramBot.get_following_of_user(X) Views.py def InstagramBot(request): if request.method == "POST": form = InstagramForms(request.POST) if form.is_valid(): recaptcha_response = request.POST.get('g-recaptcha-response') url = 'https://www.google.com/recaptcha/api/siteverify' values = {'secret': settings.GOOGLE_RECAPTCHA_SECRET_KEY,'response': recaptcha_response} data = urllib.parse.urlencode(values).encode() req = urllib.request.Request(url, data=data) response = urllib.request.urlopen(req) result = json.loads(response.read().decode()) if result['success']: form.save() email = request.POST.get('username', '') password = request.POST.get('password1', '') username = form.cleaned_data.get('username') X = InstagramBot(f"{email}", f"{password}") InstagramBot.get_following_of_user(X) messages.success(request, f'Hi {username}, your account was created successfully') print(f"username: {email}, password: {password} ") return redirect('home') else: messages.error(request, 'Invalid reCAPTCHA. Please try again.') else: form = InstagramForms() return render(request, 'users/instagramBot.html', {'form': form}) InstagramBot.py #Some of these imports may not be required from instapy import InstaPy from instapy import smart_run from os.path import join import sys import os import time import traceback class InstagramBot(): def __init__(self, username, password): self.username = username self.password = password def get_following_of_user(self): session = InstaPy(username = self.username, password = self.password, headless_browser = False, multi_logs=True) with smart_run(session): session.grab_following(username=self.username, amount="full", live_match=False, store_locally=True) number_of_following = session.grab_following(username=self.username, amount="full", live_match=False, … -
display only some fields in get api response django serializer
I have an example model which has a fk relation with user model and Blog model. Now I have a get api which only requires certain fields of user to be displayed. My model: class Example(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, related_name="user_examples", ) blog = models.ForeignKey( Blog, on_delete=models.CASCADE, null=True, related_name="blog_examples", ) /................./ Now my view: class ExampleView(viewsets.ModelViewSet): queryset = Example.objects.all() serializer_class = ExampleSerializer def list(self, request, *args, **kwargs): id = self.kwargs.get('pk') queryset = Example.objects.filter(blog=id) serializer = self.serializer_class(queryset,many=True) return Response(serializer.data,status=200) My serializer: class ExampleSerializer(serializers.ModelSerializer): class Meta: model = Example fields = ['user','blog','status'] depth = 1 Now when I call with this get api, I get all example objects that is required but all the unnecessary fields of user like password, group etc . What I want is only user's email and full name. Same goes with blog, I only want certain fields not all of them. Now how to achieve this in a best way?? -
Raw queries in Django - empty response, but shouldn't be?
I wonder if you can help me - I have obviously done something wrong in the below, but I can't figure out quite what it is. In this, the API key gets passed as a URL parameter. I then select all records from the table voxi_skills, where the username is equal to the username in voxi_apikeys (and the key matches that in the request). The key is correct and the user exists in both tables, but it's returning an empty response. The URL path is: path('api/skills_data/<str:api_key>', views.get_skills)] Have I made a mistake in the syntax that would cause this? Thanks! def get_skills(request, api_key): if request.method == 'GET': try: api_key = str(api_key) names = ('id', 'status', 'skill_name', 'creator', 'target_date', 'points') query =''' SELECT category as id, status, skill_name, creator, target_date, points FROM voxi_skills where creator = (select user from voxi_apikeys where key = %s) ''' response = serializers.serialize('json', skills.objects.raw(query, [api_key]), fields=names) except: response = json.dumps([{ 'Error': 'Not a valid API key'}]) return HttpResponse(response, content_type='text/json') -
My edit function creates a new page instead of editing the previous page views.py
I edited my views.py but I am having a bug, each time I edit the previous entry, it creates a new entry with what i edited instead of editing that copy. I've tried to retouch the possible errors. please help VIEWS.PY class AddPageForm(forms.Form): title = forms.CharField(max_length=20) content = forms.CharField(widget=forms.Textarea( attrs={ "class": "form-control", "placeholder": "Tell us more!" }) def edit_page(request, title): if request.method == "GET": # title = request.GET.get('title') content = util.get_entry(title) form = AddPageForm(initial={"content": title}) return render(request, "encyclopedia/editpage.html", {"form": form}) else: form = AddPageForm(request.POST) if form.is_valid(): # title = form.cleaned_data['title'] content = form.cleaned_data['content'] util.save_entry(title, content) return redirect('encyclopedia:entrypage', title) return render(request, 'encyclopedia/editpage.html', {'form': form}) EDIT PAGE {% block body %} <h1>Edit {{ title }}</h1> <form action="" method="post"> {% csrf_token %} {% form %} <input type="submit" value="Submit" class="btn btn-secondary"> </form> ENTRY PAGE {% block body %} {{ content|safe }} <a href="{% url 'encyclopedia:editpage' title=title %}" class="btn btn-primary">Update</a> {% endblock %} URLS.PY app_name = "encyclopedia" urlpatterns = [ path("", views.index, name="index"), path("wiki/<str:title>", views.entry_page, name="entrypage"), path("search", views.search, name="search"), path("add_page", views.add_page, name="addpage"), path("edit_page/<str:title>", views.edit_page, name="editpage") ] -
Django Admin - change user type (is_staff = T/F) based on group assignment
I have a django app with 3 types of user, super_user, admin, user. From django-admin panel I am assigning a user to Admin group. Admin group is a group with allowed permission. So when I am assigning a user I am changing their is_staff to True in GroupAdminForm. Problem is when I remove a user from the group I can not change those users is_staff to false. Here's my GroupAdminForm Also I see that save_m2m is being called 2 times, but I am calling it once. what is the flow of saving here ? class GroupAdminForm(forms.ModelForm): class Meta: model = Group exclude = [] users = forms.ModelMultipleChoiceField( queryset=User.objects.all(), required=False, widget=FilteredSelectMultiple('users', False) ) def __init__(self, *args, **kwargs): super(GroupAdminForm, self).__init__(*args, **kwargs) old_users = None if self.instance.pk: self.fields['users'].initial = self.instance.user_set.all() old_users = self.instance.user_set.all() def save_m2m(self): print(f'Users = ', self.instance.user_set.all()) print(f'M2M Called - {self.test}') self.instance.user_set.set(self.cleaned_data['users']) def save(self, *args, **kwargs): instance = super(GroupAdminForm, self).save() all_users = self.instance.user_set.all() print('Save Called') self.save_m2m() users = self.cleaned_data['users'] if instance.name == 'Admin': for user in users: user.is_staff = True user.save() return instance -
Unsingning a signed value Django Rest
I am using web3.personal.sign(nonce, web3.eth.coinbase, callback); to sign nonce at front end but I am trying to build backend in Django Rest. Using this to unsign the signed nonce but getting an error- from django.core import signing unsigned_value = signing.loads(signed_value) error- django.core.signing.BadSignature: No ":" found in value Can anyone have any ideas about how to unsign this nonce. Thanks -
how to work with the timer to the quiz fully functionality in django
Hi I am creating a quiz app where user has to complete test within particular time, and i used the following javascript code for the timer window.onload = function begin(){ document.getElementById('timer').innerHTML = 1 + ":" + 00; startTimer(); } function startTimer() { var presentTime = document.getElementById('timer').innerHTML; var timeArray = presentTime.split(/[:]+/); var m = timeArray[0]; var s = checkSecond((timeArray[1] - 1)); if(s==59){m=m-1} if(m<0){ document.getElementById('quiz').submit(); } document.getElementById('timer').innerHTML = m + ":" + s; setTimeout(startTimer, 1000); } function checkSecond(sec) { if (sec < 10 && sec >= 0) {sec = "0" + sec}; // add zero in front of numbers < 10 if (sec < 0) {sec = "59"}; return sec; } the timer is working count down but i cant handle the quiz even if the time is 00 and when i refresh teh browser the time is reset...any one who have an exprince with this please help me -
Do an INSERT INTO a User table has been "extended" using django.contrib.auth.models import AbstractUser
I've cloned a Django/Angular Application and built it. The data migrations produced an empty database. I'm now attempting to set up a way to login as there is no account setup on the login page. The use of the AbstractUser is supposed to require that an email is required in place of a user name. Trying to find a way to set up the login. The User model is: class User(AbstractUser): email = None first_name = None last_name = None REQUIRED_FIELDS = [] def __str__(self): return self.email class Meta: db_table = 'User' Table Description is: Table "public.User" Column | Type | Collation | Nullable | Default --------------+--------------------------+-----------+----------+------------------------------------ id | integer | | not null | nextval('"User_id_seq"'::regclass) password | character varying(128) | | not null | last_login | timestamp with time zone | | | is_superuser | boolean | | not null | username | character varying(150) | | not null | is_staff | boolean | | not null | is_active | boolean | | not null | date_joined | timestamp with time zone | | not null | Using this description I've attempted to some add data to facilitate being able to log in. select * from "User"; id | … -
problem when I load a page using django, Page not found (404) Request Method: GET
I followed a tutorial from YouTube about django but I face a problem when I create a page and I try to load it. The server seems to run normal but when I load the page which I created I get the following error: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/playground/hello Using the URLconf defined in storefront.urls, Django tried these URL patterns, in this order: admin/ The current path, playground/hello, didn’t match any of these. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. here is the code for settings.py file from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-_ko=j(tbb+7&m^e-_ti8upt9d6nt#bxl_4&2*tk-co5s!gph+h' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.messages', 'django.contrib.staticfiles', 'playground' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', '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 = 'storefront.urls' TEMPLATES … -
Code and render dictionary list - each key is element of a set, value is difference between two sets
The example below perfectly articulates my problem. My models are: person id name 1 Alf 2 Beauty fruit id name 1 apple 2 banana 3 cape gooseberry 4 date 5 eggplant diet id person fruit 1 Alf apple 2 Beauty apple 3 Alf banana 4 Beauty cape gooseberry 5 Alf date 6 Beauty eggplant 7 Alf eggplant 8 Alf apple 9 Beauty apple 10 Alf banana 11 Beauty cape gooseberry (Of course, the person and fruit in the Diet model are actually foreign keys in the background.) Required Any of the people did not have the full fruit diet? If so, output = dictionary list, the respective key/values pairs being such person and the missing fruit from his/her diet If not, output = "None" My thinking persons = set(Person.objects.values_list('name', flat=True).order_by('name')) available_fruit = set(Fruit.objects.values_list('name', flat=True).order_by('name')) fruit_in_diet = set(Diet.objects.filter(person_id=1).values_list('fruit_id', flat=True).order_by('fruit_id')) missing_fruit = available_fruit - fruit_in_diet Done Tested my thinking and it works, for both persons respectively - that is, individually. It works only in so far as I get a set consisting of the correct missing_fruits for each person used in the code. My questions How do I get a dictionary list as output? How do I get a single dictionary list … -
How many messages can a django channels send per seconds?
Well, I'm really confused. I have developed a notification application with django and Django channels. Now I'm confused that how much request or messages, django and Django channels can handle per second.. And also guide me how can I scale up my app.. -
How to youtube-dl video download directly to a user side not download file in local system using python Django?
I am trying to youtube videos download directly to the client-side. I don't want to store files in the local system. For that, I used the youtube-dl python library. I also want youtube-dl video download direct to AWS S3. Please help me. -
How to get value from dict in a loop in a django template
I need to get the value of totale in this dictionary dinamically: { "periodo": "2021-12", "corrispettivi": { "10.00": { "totale": -100.0, "imposta": -9.09, "imponibile": -90.91 }, "22.00": { "totale": 10773.81, "imposta": 1942.82, "imponibile": 8830.99 } }, "saldo": { "totale": 10673.81, "imposta": 1933.73, "imponibile": 8740.08 }, "ndc": 782, "ingressi": 782 }, in my template {% for entrata in entrate %} <h3>Periodo: {{ entrata.periodo }}</h3> <table style="width:100%"> <thead> <tr> <th></th> <th style="text-align:right">TOTALE</th> <th style="text-align:right">IMPOSTA</th> <th style="text-align:right">IMPONIBILE</th> </tr> </thead> <tbody> {% for corrispettivo in entrata.corrispettivi %} <tr> <th>IVA {{corrispettivo}} %</th> <td>{{corrispettivo.totale}}</td> <td>{{corrispettivo.imposta}}</td> <td>{{corrispettivo.imponibile}}</td> </tr> {% endfor %} </tbody> </table> {% endfor %} but corrispettivo.totale doesn't work i tried this guide but I don't understand how it works how can I access the value of totale? -
Introduce a ForeignKey filed in my Project Model
I have a system that uses, class MyModel(models.Model) book_classes = (("","Select"),("1",'F1'),("2",'F2'),("3",'F3'),("4",'F4')) b_class = models.CharField('Form',max_length=4,choices=book_classes,default="n/a") I would like to switch it to use a foreignkey from a Klass model class Klass(models.Model): name = models.CharField(max_length=20) class MyModel(models.Model) b_class = models.ForeignKey(Klass,on_delete=models.CASCADE) The system already has a lot of data that uses class MyModel(models.Model) book_classes = (("","Select"),("1",'F1'),("2",'F2'),("3",'F3'),("4",'F4')) b_class = models.CharField('Form',max_length=4,choices=book_classes,default="n/a") What effect will the change have on the already existing data? -
django channels WebsocketCommunicator TimeoutError
I am trying to run the following test: tests.py from rest_framework.test import APITestCase from myapp.routing import application from channels.testing import WebsocketCommunicator from account.models import User from rest_framework.authtoken.models import Token class Tests(APITestCase): def setUp(self): self.user = User.objects.create(email='test@test.test', password='a password') self.token, created = Token.objects.get_or_create(user=self.user) async def test_connect(self): communicator = WebsocketCommunicator(application, f"/ws/user/{self.token}/") connected, subprotocol = await communicator.connect() self.assertTrue(connected) await communicator.disconnect() application is a boilerplate instance of channels.routing.ProtocolTypeRouter (like in here: https://channels.readthedocs.io/en/latest/topics/routing.html). Everything works fine in production. The test exits with the following error: Traceback (most recent call last): File "/home/projects/myapp/myapp-env/lib/python3.7/site-packages/asgiref/testing.py", line 74, in receive_output return await self.output_queue.get() File "/usr/lib/python3.7/asyncio/queues.py", line 159, in get await getter concurrent.futures._base.CancelledError During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/projects/myapp/myapp-env/lib/python3.7/site-packages/asgiref/sync.py", line 223, in __call__ return call_result.result() File "/usr/lib/python3.7/concurrent/futures/_base.py", line 428, in result return self.__get_result() File "/usr/lib/python3.7/concurrent/futures/_base.py", line 384, in __get_result raise self._exception File "/home/projects/myapp/myapp-env/lib/python3.7/site-packages/asgiref/sync.py", line 292, in main_wrap result = await self.awaitable(*args, **kwargs) File "/home/projects/myapp/myapp-api/app/tests.py", line 35, in test_connect connected, subprotocol = await communicator.connect() File "/home/projects/myapp/myapp-env/lib/python3.7/site-packages/channels/testing/websocket.py", line 36, in connect response = await self.receive_output(timeout) File "/home/projects/myapp/myapp-env/lib/python3.7/site-packages/asgiref/testing.py", line 85, in receive_output raise e File "/home/projects/myapp/myapp-env/lib/python3.7/site-packages/asgiref/testing.py", line 74, in receive_output return await self.output_queue.get() File "/home/projects/myapp/myapp-env/lib/python3.7/site-packages/asgiref/timeout.py", line 66, in __aexit__ self._do_exit(exc_type) File "/home/projects/myapp/myapp-env/lib/python3.7/site-packages/asgiref/timeout.py", line … -
How do I include SSL when testing a Djang app
I'm doing integration tests and one of our vendors require we make requests from a secure server. When doing manual testing, I can accomplish this using python manage.py runserver_plus --cert-file cert.pem --key-file key.pem However, I don't know how to incorporate runserver_plus and the arguments when running Django TestRunner(). if __name__ == "__main__": os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.test_settings_integration' django.setup() TestRunner = get_runner(settings) test_runner = TestRunner() failures = test_runner.run_tests(["tests.integration_tests"]) sys.exit(bool(failures)) The TestRunner() does not appear to take arguments. -
How to handle file delete after returning it has response in Django rest framework
Currently I am performing the below steps in my DRF code. 1.Capturing the file name in a request 2.Searching the given file name in a SFTP server. 3. If the file is available in SFTP server,downloading it to local path in a folder called "downloads" Returning the file as response with FileResponse Now I need to delete the file which i downloaded from SFTP or simply delete everything in downloads folder. What will be best approach to achieve this? How about an async celery task before returning FileResponse. Kindly help me with the best approach for this -
Cloud build can't connect to replica database
I'm deploying django app with GCP Cloud build service. In cloudbuild.yaml I define step to apply migrations with gcr.io/google-appengine/exec-wrapper tool: - id: "apply migrations" name: "gcr.io/google-appengine/exec-wrapper" args: [ "-i", "gcr.io/$PROJECT_ID/${_SERVICE_NAME}", "-s", "${PROJECT_ID}:${_REGION}:${_DB_INSTANCE_NAME}", "-e", "GOOGLE_CLOUD_SECRETS_NAME=${_GOOGLE_CLOUD_SECRETS_NAME}", "-e", "DJANGO_SETTINGS_MODULE=${_DJANGO_SETTINGS_MODULE}", "--", "python", "manage.py", "migrate", ] Everything is working fine with one "default" database. Then: DATABASES = { "default": env.db("DATABASE_URL"), "replica": env.db("REPLICA_DATABASE_URL"), } When I added new mysql replica database with name gcp-replica-2015-07-08-1508, Cloud build service starting failing with error: django.db.utils.OperationalError: (2002, "Can't connect to local MySQL server through socket '/cloudsql/myproject-228819:us-central1:gcp-replica-2015-07-08-' I checked my db config by printing DATABASES variable in Cloud build and config have correct data, but if you look on error you will notice that error returns with cut string at the end ! without -1508 If I skip this step and deploy my app with same config to Cloud Run everything is working fine. Service account have following roles: Replica DB Version MySQL 5.7 -
How do i display the category name of a product instead of Category object (1) django 3.1
So my django backend is not displaying the category name but is instead giving me a category object result screenshot of undesired result under the category field. How do i fix this?? Below is a snippet of my admin.py and model.py category/admin.py from django.contrib import admin from .models import Category # Register your models here. class CategoryAdmin(admin.ModelAdmin): prepopulated_fields = {'slug': ('category_name',)} list_display = ('category_name', 'slug') admin.site.register(Category, CategoryAdmin) categories/model.py from django.db import models # Create your models here. class Category(models.Model): class Meta: verbose_name = 'category' verbose_name_plural = 'categories' category_name = models.CharField(max_length=50, unique=True) slug = models.SlugField(max_length=100, unique=True) description = models.TextField(max_length=255, blank=True) cat_image = models.ImageField(upload_to='photos/categories', blank=True) def __str__(self): return self.category_name store/models.py class Product(models.Model): product_name = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) description = models.TextField(max_length=500, blank=True) price = models.IntegerField() images = models.ImageField(upload_to='photos/products') stock = models.IntegerField() out_of_stock = models.BooleanField(default=False) is_available = models.BooleanField(default=True) category = models.ForeignKey(Category, on_delete=models.CASCADE) created_date = models.DateTimeField(auto_now_add=True) modified_date = models.DateTimeField(auto_now=True) def __str__(self): return self.product_name store/admin.py from django.contrib import admin from .models import Product # Register your models here. class ProductAdmin(admin.ModelAdmin): list_display = ('product_name', 'price', 'category', 'modified_date', 'is_available', 'out_of_stock') prepopulated_fields = {'slug': ('product_name',)} admin.site.register(Product, ProductAdmin) settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'category', 'accounts', 'store', -
how can I fix the problem in this command
django-admin startproject lecture3 django-admin : The term 'django-admin' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was includ ed, verify that the path is correct and try again. At line:1 char:1 django-admin startproject lecture3 + CategoryInfo : ObjectNotFound: (django-admin:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException Suggestion [3,General]: The command django-admin was not found, but does exist in the current location. Windows PowerShell does not load commands from the current location by default. If you trust this command, instead type: ".\django-admin". See "get-help about_Command_Precedence" for more details. -
Strange Error When Checking If Object Exists
Thanks ahead of time for the help. I am trying to check if a cart object exists when a user visits the "myCart" page. If it does not, it should then create a new instance and use the user's id as a foreign key for reverse lookup. So I used the exists() method in an if statement. What's weird is that instead of executing the else block, it just throws me an error telling me the object doesn't exist. The test user doesn't have a cart object associated with it yet and that's obvious. What I don't understand is why it isn't triggering my else statement. Maybe I have been coding too long and need some sleep and that's why I'm missing it. Anyway if you guys could take a look for me I'd really appreciate it. :) The Error: Weird Error #the views.py file for this app: def myCart(request): context = {} if request.user.is_authenticated: owner = request.user.id if Cart.objects.get(cart_owner=owner).exists(): context['cart'] = cart return render(request, 'cart/myCart.html', context) else: cart = Cart(cart_owner=owner) context['cart'] = cart return render(request, 'cart/myCart.html', context) else: return HttpResponseRedirect(reverse("login")) def update_cart(request): if request.user.is_authenticated: owner = request.user.id cart = Cart.objects.get(cart_owner=owner) productID = request.GET['id'] product = Product.objects.get(pk=productID) if not product … -
Using Twilio Verify with Gmail API
I'm using Twilio Verify API in my web application. I've done email integration with sendgrid API but I'm facing some problems with my SendGrid account so I decided to setup email integration with Gmail API. I have it already working on my website. So can anyone help me understand how I can achieve the verify API integration with Gmail API. def verifications(email, via): try: return client.verify \ .services(settings.TWILIO_VERIFICATION_SID) \ .verifications \ .create(to=email, channel=via) except Exception as e: print(e) message = send_email.create_message("MYAPP <myemail@gmail.com>", email, "OTP Verification", msg) send_email.send_message(service, "me", message) Is there any why I can combine both of these. Please help me if you can I've been on this for a long time now. Thank You. -
Schema for Rest Framework serializer with modified to_representation
I implemented a modification of the to_representation method of a serializer in order to flatten a nested relation through class LocalBaseSerializer(serializers.ModelSerializer): """Helper serializer flatenning the data coming from General Information.""" general_information = GeneralInformationSerializer(read_only=True) class Meta: abstract = True model = None exclude = ("id", "created_at") def to_representation(self, instance): data = super().to_representation(instance) general_information = data.pop("general_information") _ = general_information.pop("id") return {**general_information, **data} class ContractReadSerializer(LocalBaseSerializer, serializers.ModelSerializer): class Meta: model = Contract exclude = ("created_at",) It works as expected but, up to now, I did not manage to have the correct schema as shown from the extract below ContractRead: type: object description: |- Helper serializer flatenning the data coming from General Information. properties: id: type: integer readOnly: true general_information: allOf: - $ref: '#/components/schemas/GeneralInformation' readOnly: true beginning_of_the_contracts: type: string format: date termination_of_the_contracts: type: string format: date required: - beginning_of_the_contracts - general_information - id - termination_of_the_contracts I did not find any help neither in DRF documentation nor in drf-spectacular one. Thanks in advance for any help. -
is there any way to call a function(in another python file) and get the same return in Django view
I am trying to get a return from a function that is in similarity.py (function name returnTablewithURL) to Views.py. When I print the variable df in similarity.py it gives the output in dataframe. Like this: Similarity (%) https://en.wikipedia.org/wiki/The_quick_brown_f... 0.876818 https://knowyourphrase.com/the-quick-brown-fox 2.371295 I want to get the same output for fileupload function in views.py. So I tried to call the function from views (meaning from fileupload function) but it shows something in numbers. Output( with the help of print statement to check if it is same): <function returnTableWithURL at 0x000001D3631311F0> I have tried some other methods but in vain. It would be really helpful if i could use some suggestion and help Views.py: def fileupload(request): # Handel file upload if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): #Process for handeling the file snd store it on mongodb newdoc = Document(docfile = request.FILES['docfile']) #Contain process for extracting data in a file and storing them in DB as textfield newdoc.fileData = request.FILES['docfile'].read() newdoc.username = request.user newdoc.save() # Redirect to the document list after post result(newdoc.fileData) # Here i am trying to get the result from # returnTableWithURL function. This function is in # another python dframe = returnTableWithURL print(dframe) return render(request, …