Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to fix heroku h10 error for my deployed app
This is the error my heroku logs show anytime I run my app 2022-11-09T16:52:49.620009+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/util.py", line 359, in import_app 2022-11-09T16:52:49.620009+00:00 app[web.1]: mod = importlib.import_module(module) 2022-11-09T16:52:49.620009+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/importlib/init.py", line 127, in import_module 2022-11-09T16:52:49.620010+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2022-11-09T16:52:49.620010+00:00 app[web.1]: File "", line 1030, in _gcd_import 2022-11-09T16:52:49.620010+00:00 app[web.1]: File "", line 1007, in _find_and_load 2022-11-09T16:52:49.620010+00:00 app[web.1]: File "", line 984, in _find_and_load_unlocked 2022-11-09T16:52:49.620011+00:00 app[web.1]: ModuleNotFoundError: No module named 'dlcfogbomoso.wsgi' 2022-11-09T16:52:49.620081+00:00 app[web.1]: [2022-11-09 16:52:49 +0000] [9] [INFO] Worker exiting (pid: 9) 2022-11-09T16:52:49.644507+00:00 app[web.1]: [2022-11-09 16:52:49 +0000] [10] [INFO] Booting worker with pid: 10 2022-11-09T16:52:49.647154+00:00 app[web.1]: [2022-11-09 16:52:49 +0000] [10] [ERROR] Exception in worker process 2022-11-09T16:52:49.647155+00:00 app[web.1]: Traceback (most recent call last): 2022-11-09T16:52:49.647156+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/arbiter.py", line 589, in spawn_worker 2022-11-09T16:52:49.647156+00:00 app[web.1]: worker.init_process() 2022-11-09T16:52:49.647156+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/workers/base.py", line 134, in init_process 2022-11-09T16:52:49.647156+00:00 app[web.1]: self.load_wsgi() 2022-11-09T16:52:49.647157+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/workers/base.py", line 146, in load_wsgi 2022-11-09T16:52:49.647157+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2022-11-09T16:52:49.647157+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/app/base.py", line 67, in wsgi 2022-11-09T16:52:49.647157+00:00 app[web.1]: self.callable = self.load() 2022-11-09T16:52:49.647158+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/app/wsgiapp.py", line 58, in load 2022-11-09T16:52:49.647158+00:00 app[web.1]: return self.load_wsgiapp() 2022-11-09T16:52:49.647158+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp 2022-11-09T16:52:49.647158+00:00 app[web.1]: return util.import_app(self.app_uri) 2022-11-09T16:52:49.647159+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/util.py", line 359, in import_app 2022-11-09T16:52:49.647159+00:00 app[web.1]: mod = importlib.import_module(module) 2022-11-09T16:52:49.647159+00:00 app[web.1]: File … -
create a django serializer to create three model instance at once
{ "product_name": "CRVRVgfhghg", "product_price": "0.01", "product_location": "KIKUYU,KENYA", "product_description": "VFVFVFVFVFVF", "product_category_name": "livestock", "product_farmer_name": "james", "product_category_data": { "product_category_name": "livestock", "product_category_description": "livestock one" }, "product_product_file_data": { "product_file_name": "ok" } } i have three tables: product_category,product and product_product_files...what i want is to populate all the three tables at once using one view and url pattern... is there a way i can do this using serializers?? -
How can I refactor my code to clear off - "local variable 'data' referenced before assignment"
My code returns is intended to return queryset based on selected dates or months however these two are almost similar yet only one works. Here is my both forms.py class DateInput(forms.DateInput): input_type = 'date' class MonthInput(forms.DateTimeInput): input_type = 'month' class DateRangeInputForm(forms.Form): start = forms.DateField(widget=DateInput()) end = forms.DateField(widget=DateInput()) class MonthRangeInputForm(forms.Form): start = forms.DateField(widget=MonthInput()) end = forms.DateField(widget=MonthInput()) This is the query view that works. def milk_records_range_per_day(self, request): if request.method == "POST": form = forms.DateRangeInputForm(request.POST) if form.is_valid(): data = (models.Milk.objects.filter(milking_date__date__range=( form.cleaned_data['start'], form.cleaned_data['end'])) .annotate(date=functions.TruncDate("milking_date")) .values("date") .annotate(amt=Sum('amount_in_kgs'))) labels = [c['date'].strftime("%d-%m-%Y") for c in data] values = [x['amt'] for x in data] ....... Though this one throws a reference error : local variable 'data' referenced before assignment def milk_records_range_per_month(self, request): if request.method == "POST": form = forms.MonthRangeInputForm(request.POST) if form.is_valid(): data = (models.Milk.objects.filter(milking_date__month__range=( form.cleaned_data['start'],form.cleaned_data['end'])) .annotate(month=functions.TruncMonth("milking_date")) .values("month") .annotate(amt=Sum('amount_in_kgs'))) labels = [c['month'].strftime("%m-%Y") for c in data] values = [x['amt'] for x in data] ..... Model: class Milk(models.Model): amount_in_kgs = models.PositiveIntegerField(validators=[MinValueValidator(0), MaxValueValidator(50)]) milking_date = models.DateTimeField(auto_now_add=True) ... -
APIView PUT request being handled as a GET request
I'm building an APIView to handle a PUT request for a model with choicefields as input. Originally, I created a GET and PUT definition for my APIView class, however when my build is deployed, my PUT request is being received as a GET request! On my dev deployment, the request is received as a PUT request every time. When I move it to a production deployment however, the only times I can get the request to properly send a PUT request is by using Postman. When I try any other way the request is received as a GET request. Removing the definition of GET from my APIView does not help, it simply returns a 405 method not allowed. I've looked around and don't seem to see any other people with this issue. What could cause a request to be misinterpreted like this? Where would be a good place to start looking? Can I force the use of PUT at this endpoint? In the meantime I'm going to try moving from APIView to one of the specific generics mixins to see if this resolves my issue. -
How to allow boolean True on just one model in table in Django?
I've got a model where I would like there to be able to have one set as the 'app default'. In this model I added a field named is_app_default in order to help accommodate this. class TreeLevel(models.Model): id = models.BigAutoField(primary_key=True) short_description = models.CharField(max_length=200) long_description = models.TextField() is_app_default = models.BooleanField(default=False) class Meta: verbose_name = "Tree Level" verbose_name_plural = "Tree Levels" class Layer(models.Model): id = models.BigAutoField(primary_key=True) tree_levels = models.ManyToManyField(TreeLevel) description = models.TextField() class Meta: verbose_name = "Layer" verbose_name_plural = "Layers" The Layer model links to TreeLevel with an m2m. Ultimately I would like the is_app_default TreeLevel automatically added to every Layer m2m relationship - which is why there can only be one TreeLevel with is_app_default set as True. My potential solution(s): Users with admin may be creating new TreeLevel objects - so I need to make sure they aren't setting that Boolean in any new models. I think I can override the save() method on TreeLevel to check the DB to see if another with that boolean as True exists - if so? Don't save the 'new' one and return an error. But I think this hits the database - causing unnecessary queries potentially? Then additionally, I would also need to override … -
how to define the environment variable DJANGO_SETTINGS_MODULE?
I am trying to chainedForeignKey using https://django-smart selects.readthedocs.io/en/latest/installation.htmland i got following error : ` django.core.exceptions.ImproperlyConfigured: Requested setting USE_DJANGO_JQUERY, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. ` your text``from django.db import models your textfrom smart_selects.db_fields import ChainedForeignKey Create your models here. your textclass City(models.Model): your textname = models.CharField(max_length = 25, null = True) your textclass Area(models.Model): your textname = models.CharField(max_length = 25, null = True) your textcity = models.ForeignKey(City, on_delete = models.CASCADE) your textclass Store(models.Model): your textstore = models.CharField(max_length = 50) your textcity = models.ForeignKey(City, on_delete = models.CASCADE) your textarea = ChainedForeignKey(Area, chained_field='city', chained_model_field= 'city') -
select instances in manaytomany field using django rest
I'm trying to build a friend add system using Django Rest And these are my codes #models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(max_length=100) pic = models.ImageField(upload_to="img", blank=True, null=True) friends = models.ManyToManyField('Friend', related_name = "my_friends" , blank=True , null=True) def __str__(self): return self.user.username class Friend(models.Model): profile = models.OneToOneField(Profile, on_delete=models.CASCADE) def __str__(self): return self.profile.user.username #serializers.py class FriendSerializer(serializers.ModelSerializer): class Meta: model = Friend fields = ('profile',) class ProfileSerializer(serializers.ModelSerializer): friend = FriendSerializer(many=True, read_only=False) class Meta: model = Profile depth = 3 #this is return foreinkey name instead of id fields = "__all__" def update(self, instance, validated_data): friends_data = validated_data.pop('friend') instance = super(ProfileSerializer, self).update(instance, validated_data) for friend_data in friends_data: friend_qs = Friend.objects.filter(profile = friend_data['profile']) if friend_qs.exists(): friend = friend_qs.first() else: friend = Friend.objects.create(**friend_data) instance.friend.add(friend) return instance #views.py class UserProfile(RetrieveUpdateDestroyAPIView): queryset = Profile.objects.all() serializer_class = ProfileSerializer class UserFriends(RetrieveUpdateDestroyAPIView): queryset = Friend.objects.all() serializer_class = FriendSerializer #urls.py urlpatterns = [ path('' , ArticleList.as_view() , name = 'list'), #we used as_view() cause we used class based views path('<int:pk>' , ArticleDetail.as_view() , name = 'detail'), path('users/' , UserList.as_view() , name = 'user-list'), path('users/<int:pk>' , UserDetail.as_view() , name = 'user-detail'), path('profile/<int:pk>' , UserProfile.as_view() , name = 'user-profile'), ] My intention is to send a json like this -> … -
How to filter queryset from inside the serializer?
I want to always apply a filter to a serializer (filter the queryset). lets say I have: class Company(models.Model): name = models.CharField(max_length=90, unique=True) city = models.CharField(max_length=90,) active = models.BooleanField(default=True) class CompanySerializer(serializers.ModelSerializer): class Meta: model=Company fields=['id', 'name', 'city'] so when I call the serializer for a list filtered by city (or any other fields added in my real code) as shown below it returns Companies from that city and only "active=True" query_set = Company.objects.filter(city=request.POST(city) ) srl = serializers.CompanySerializer(query_set, many=True) return Response(srl.data) because I may want to call the serializer from other parts of the code. and I want to keep the records for reference but never show to any client. I have tryed to modify the queryset from from init but it does not work. I actually print() the modified queryset to make sure it was filtered and it prints the filtered queryset, I do: def __init__(self, instance=None, data=empty, **kwargs): instance.filter(active=False) self.instance = instance print(self.instace) #this prints the filtered queryset OK but it sends the response without the "active=False" filter. -
SEO in django template project
I'm new in django, I'm working on a djanog project and i want to render dynamic meta tags foe SEO and titles for every page in it, but i don't know how can it can help please I want it to be something like this: <title>Veb-studiya bilan aloqa - Eson</title> <meta name="description" content="Veb-studiya Eson - bu professional veb-studiya. Biz o&#039;z ishimizni sevamiz va sizning internet tarmog&#039;idagi biznesingizni rivojlantiriramiz. " /> <meta name="robots" content="index, follow" /> <meta name="googlebot" content="index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1" /> <meta name="bingbot" content="index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1" /> <link rel="canonical" href="https://eson.uz/aloqalar/" /> <meta property="og:locale" content="uz_UZ" /> <meta property="og:locale:alternate" content="ru_RU" /> <meta property="og:type" content="article" /> <meta property="og:title" content="Veb-studiya bilan aloqa - Eson" /> <meta property="og:description" content="Veb-studiya Eson - bu professional veb-studiya. Biz o&#039;z ishimizni sevamiz va sizning internet tarmog&#039;idagi biznesingizni rivojlantiriramiz. " /> <meta property="og:url" content="https://eson.uz/aloqalar/" /> <meta property="og:site_name" content="Eson" /> <meta property="article:publisher" content="https://www.facebook.com/netsonuz" /> <meta property="article:modified_time" content="2022-01-10T07:20:26+00:00" /> <meta name="twitter:card" content="summary_large_image" /> <script type="application/ld+json" class="yoast-schema-graph">{"@context":"https://schema.org", -
Python: Basic OCR / Image to Text library
I have a very simple use case for OCR. .PNG Image then extract the text from the image. Then print to console. I'm after a lite weight library. I am trying to avoid any system level dependency's. Pytesseract is great, but deployment is a bit annoying for such a simple use case. I have tried quite a few of them. They seem to be designed for more complex use cases. Note: White text is not necessarily suitable for OCR. I will change the image format to suit the OCR Library. -
How to create a python listener microservice with flask
I need to build a listener microservice that is going to listen to events through a websocket and I had been assigned to do this task with python+flask. I worked before with Django and I know i can create a command that is always running, but i don't see any documentation about doing something similar with Flask. What i want is understand how to build a flask+python application that is always up and running listening for some events. Any ideas? -
How to host Django Channels (ASGI) with amazon_ec2?
The REST endpoints work completely fine, but the WS endpoints aren’t even registered as WS connection attempts. When I connect to wss://lms-backend-wiomf.ondigitalocean.app/ws/teacher/, it shows [lms-backend] [2021-07-05 03:51:44] Not Found: /ws/teacher/ [lms-backend] [2021-07-05 03:51:44] 10.244.59.39 - - [05/Jul/2021:03:51:44 +0000] "GET /ws/teacher/ HTTP/1.1" 404 2560 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36" how can I successfully host my asgi application on aws-ec2 any one plz help -
Can anyone suggest me a best Logging System for my applications?
I am trying to implement a log system in my flask and django apps. I don't want to store it in a text document. Because these files are keep on storing all the logs and at some stage I can not open/read them because of the larger size. Is there any other way to have a log system apart from this? -
How to run a process in Django view without "Apps aren't loaded yet" error?
In Django view, I'm trying to run a process as shown below. *I use Django 3.1.7: # "views.py" from multiprocessing import Process from django.http import HttpResponse def test(): print("Test") def test(request): process = Process(target=test) process.start() process.join() return HttpResponse("Test") But, I got this error below: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. So, I put the code below to settings.py to solve the error above following this solution: # "settings.py" import django django.setup() But, another error below is raised even though my SECRET_KEY setting is not empty: django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. So, how can I run a process in Django view without Apps aren't loaded yet error: -
No module named 'core' django app deployed in Railway
Hi i'm having this error when i'm trying to make a post through admin, everything else works fine except for this module error. Let me be clear i'm a complete newbie, but i think that maybe is path problem?, but i don't know how to modified or change it while is hosted on Railway. my requirements.txt asgiref==3.5.2 boto3==1.26.4 botocore==1.29.4 Django==4.1.2 django-cors-headers==3.13.0 django-crispy-forms==1.14.0 django-environ==0.9.0 django-storages==1.13.1 environ==1.0 gunicorn==20.1.0 jmespath==1.0.1 Pillow==9.2.0 psycopg2==2.9.5 python-dateutil==2.8.2 s3transfer==0.6.0 six==1.16.0 sqlparse==0.4.3 tzdata==2022.5 urllib3==1.26.12 my procfile: web: gunicorn proyecto_web.wsgi --log-file - Change the path on virtual environment but i don't know how. -
Django Verbatum like template tag to show verbatim and rendered nodes
I am trying to make a template tag that will show a section of code verbatim, and also render it, it is to help me demo some code for my own tooling. Say I have this in a template: {% example %}import * as fancy from "{% static 'jslib/fancy.min.js' %}";{% endexample %} I wish to output it as (I will add some divs and styling, but this is distilling the problem into it's simplest form): import * as fancy from "{% static 'jslib/fancy.min.js' %}"; import * as fancy from "/static/jslib/fancy.min.js"; I looked at the django {% verbatum %} tag and tried to copy the logic: # django.template.defaulttags.py @register.tag def verbatim(parser, token): nodelist = parser.parse(('endverbatim',)) parser.delete_first_token() return VerbatimNode(nodelist.render(Context())) nodelist.render(Context()) prints out text nodes for the django verbatim tag, but if I copy the code my example tag prints out say StaticNodes and other types of nodes. The reason why is I think the django parser has some special checks to see if it is a verbatim node and handles if differently, as shown in the code below: # django.template.base.py -> def create_token if self.verbatim: # Then a verbatim block is being processed. if content != self.verbatim: return Token(TokenType.TEXT, token_string, position, lineno) … -
Django does not recognize my {% endblock %} tag in the html file
I get this error while trying to run my Django project: "Invalid block tag on line 7: 'endblock'. Did you forget to register or load this tag?" I am trying to make a base-template (base.html) and use it on my html file (index.html). The name of my Django project is "mysite", the name of the app in my Django project is "myapp" It looks like Django does not recognize my {% endblock %} tag, but i don't know why. This is the base-template file (base.html): {% load static %} <html lang="en"> <head> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <link rel="stylesheet", href="{% static 'myapp/style.css' %}"> <title>Document</title> </head> <body> <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <a class="navbar-brand" href="#">Navbar</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a> </li> <li class="nav-item"> <a class="nav-link" href="#">Link</a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Dropdown </a> <div class="dropdown-menu" aria-labelledby="navbarDropdown"> <a class="dropdown-item" href="#">Action</a> <a class="dropdown-item" href="#">Another action</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="#">Something else here</a> </div> </li> <li class="nav-item"> <a class="nav-link disabled" href="#">Disabled</a> </li> </ul> <form class="form-inline my-2 my-lg-0"> <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search"> <button … -
How to create order in admin after payment is completed
I'm making a website where you buy stuff and pay through PayPal. I am done with the PayPal part now I am trying to get a situation where after the payment is complete in checkout the item purchased goes to orders in the admin. This is the order model.py: class Order (models.Model): product = models.ForeignKey(Coinpack, max_length=200, null=True, blank=True, on_delete = models.SET_NULL) created = models.DateTimeField(auto_now_add=True) this is the PayPal code part in checkout.html: <script src="https://www.paypal.com/sdk/js?client-id=idexample&currency=USD"></script> <script> function getCookie(name) { let cookieValue = null; if (document.cookie && document.cookie !== '') { const cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } const csrftoken = getCookie('csrftoken'); var total = '{{checkout.price}}' var productId = '{{checkout.id}}' function completeOrder(){ var url = "{% url 'complete' %}" fecth(url, { method: 'POST', headers:{ 'content-type':'aplication/json', 'X-CSRFToken': csrftoken, }, body: JSON.stringify({'productId':productId}) }) } // Render the PayPal button into #paypal-button-container paypal.Buttons({ // Set up the transaction createOrder: function(data, actions) { return actions.order.create({ purchase_units: [{ amount: { value: total } … -
How speech_recognition with base64 audio?
I cannot get the base64 of an audio to extract the text, it shows me the following message "the source must be an audio source". If someone has experience with this library, I would appreciate the support from contextlib import nullcontext from django import http from django.http import HttpResponse, JsonResponse import speech_recognition as sr import base64 class Reconnition(): solicitud = nullcontext method = nullcontext def __init__(self, request, method): self.solicitud = request self.method = method def recognition_voice(self, base64P = ''): error = 'false' try: reconocimiento = sr.Recognizer() if self.method == 'internal': with sr.AudioFile("C:\\Users\\bgonzalez\\Downloads\\audiotesting.wav") as archivo: audio = reconocimiento.record(archivo) texto = reconocimiento.recognize_google(audio, language='es-MX') else: decode_bytes = base64.b64decode(base64P) audio = reconocimiento.record(b''+decode_bytes) # audio = sr. # texto = reconocimiento.recognize_google(audio, language='es-MX') audio = sr.AudioData(decode_bytes) texto = reconocimiento.recognize_google(audio, language='es-MX') error = 'false' except Exception as e: # work on python 3.x error = 'true' texto = str(e) return JsonResponse({'texto': texto, 'error':error}, safe=False, status=200) #HttpResponse("Hola") -
Docker can not find /app/entrypoint.sh: 4: ./wait-for-postgres.sh: not found
My OS is windows. Backend django, frontend React. databa pgadmin. All containers runds but the backend cannot found the entrypoint, but it is indeed here. I try the instruction on stackoverflow with similar issues but none of them fix it. Any one can helo me with this? I attached log file and related fiels here. /app/entrypoint.sh: 4: ./wait-for-postgres.sh: not found 51 static files copied to '/app/static', 142 post-processed. No changes detected Operations to perform: Apply all migrations: accounts, auth, campaigns, cases, common, contacts, contenttypes, django_celery_beat, django_celery_results, django_ses, emails, events, invoices, leads, opportunity, planner, sessions, tasks, teams Running migrations: No migrations to apply. Installed 1 object(s) from 1 fixture(s) Installed 1 object(s) from 1 fixture(s) Installed 1 object(s) from 1 fixture(s) -------------- celery@47bc8292147e v5.2.0b3 (dawn-chorus) --- ***** ----- -- ******* ---- Linux-5.10.16.3-microsoft-standard-WSL2-x86_64-with-debian-11.5 2022-11-09 20:04:14 - *** --- * --- - ** ---------- [config] - ** ---------- .> app: crm:0x7fa12453a080 - ** ---------- .> transport: redis://redis:6379// - ** ---------- .> results: - *** --- * --- .> concurrency: 2 (prefork) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- -------------- [queues] .> celery exchange=celery(direct) key=celery [tasks] . accounts.tasks.send_email . accounts.tasks.send_email_to_assigned_user . accounts.tasks.send_scheduled_emails . … -
KeyError: How to exclude certain parts when a part of the serializer is empty
I have this piece in my serializer which is using a nested serializer field. When i try to submit my form it will return a KeyError if I don't add anything inside "assigned facilities". I tried adding an else statement but that doesn't seem to be helping. The debugger is actually complaining about line two when the field is empty so how do i exclude it when there is no data submited in assigned_facilities field? I`m already using required=False, allow_null=True inside the serializer. def create(self, validated_data): assigned_facilities = validated_data.pop("assigned_facilities") instance = Lead.objects.create(**validated_data) for item in assigned_facilities: instance.leadfacility.create(**item) else: print("No Facilities Added!") return instance -
SSO manager, trying to pass cookies between websites
I have an application in python for SSO purposes. Users redirect from their website to this app, and the app returns an ACCESS_TOKEN to the website the user got redirected from. I want to redirect the user back to his website after the process and return the ACCESS_TOKEN as a COOKIE, but I don't know how to send the cookie to the user's browser. Thanks for any help. -
Define field in Django which can be of any type
Pymodm is being used to define my model for the MongoDB collection in Django. I want to declare a field that can store values of any type (List, String, or Integer). from pymodm import MongoModel, fields class DefinitionEntity(MongoModel): version = fields.IntegerField(required=True) value = fields.CharField(required=True) I want the "value" field to accept multiple types. Please tell me how to define that. Thanks in advance! -
Why isn't the data sent again after resfresh page in a POST request
I have used axios to send a POST request after pressing a button. I want to make sure not to send the data again after refreshing the page or clicking the button right after. When I refresh the page or click the button the data is not being sent. I suppose it's good but I don't know why. I'm using Vue for the front and Django for the back. In Vue: axios.post('http://127.0.0.1:8000/sendAbility/', params).then(response=>{...}) In Django: return Response({'success':'true'}) -
No module named 'graphene_djangographql_jwt'
I got error when I add graphql_jwt.refresh_token.apps.RefreshTokenConfig in INSTALLED_APPS. I ran the command " pip install django-graphql-jwt" but there is still some packages problems. Does anybody know about it? I am expecting to use GraphQL url with Django. I was going to give request access only auth users.