Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Use of same serializer class for post and get request in Django rest framework
I have a Student model which has some fields. What I need is I want to create a student object using post API with certain fields and however needs to show some other fields while doing get request. For eg: My model: class Students(models.Model): name = models.CharField(max_length=255,blank=True) email = models.EmailField(unique=True) phone = models.CharField(max_length=16) address = models.CharField(max_length=255,blank=True) roll = models.IntegerField() subject = models.CharField(max_length=255,blank=True) college_name = models.CharField(max_length=255,blank=True) Now my serializer will look like this. class StudentSerializer(serializers.ModelSerializer): class Meta: model = Student fields = ['id','email','name','phone','roll','subject','college_name', 'address'] Suppose, I have a view that handles both post and get api (probably using APIView), then what I need is, to create a student object I only need name, phone and email. So for post api call, I only need three fields whereas while calling the get api I only need to display the fields name, roll, subject, and college_name not others. In this situation, how can I handle using the same serializer class?? -
Django & Flutter How to fix CORS and broken pipe problem?
I want to connect Djnago API with flutter app, but I have lots of problem. I'll show flutter and django code both. Settings.py """ Django settings for crawler project. Generated by 'django-admin startproject' using Django 3.2.6. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ 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/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-)4%#q5&d3^5=0!bauz62wxmc9csk*_c09k!jl2g1a-0rxsa--j' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'crawling_data', 'rest_framework', 'corsheaders', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', '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 = 'crawler.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], '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 = 'crawler.wsgi.application' # Database # https://docs.djangoproject.com/en/3.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': … -
Django 'failed connection' between two containers
I'm currently trying to make a connection between two of my docker containers (The requesting container running Gunicorn/Django and the api container running kroki). I've had a look at other answers but seem to be coming up blank with a solution, so was hoping for a little poke in the right direction. Docker-compose: version: '3.8' services: app: build: context: ./my_app dockerfile: Dockerfile.prod command: gunicorn my_app.wsgi:application --bind 0.0.0.0:8000 --access-logfile - volumes: - static_volume:/home/app/web/staticfiles expose: - 8000 environment: - DJANGO_ALLOWED_HOSTS=localhost 127.0.0.1 kroki env_file: - ./.env.prod depends_on: - db db: image: postgres:13.0-alpine volumes: - postgres_data:/var/lib/postgresql/data/ env_file: - ./.env.prod.db nginx: build: ./nginx volumes: - static_volume:/home/app/web/staticfiles ports: - 1337:80 depends_on: - app kroki: image: yuzutech/kroki ports: - 7331:8000 volumes: postgres_data: static_volume: settings.py ALLOWED_HOSTS = os.environ.get("DJANGO_ALLOWED_HOSTS").split(" ") Requesting code in django url = 'http://kroki:7331/bytefield/svg/' + base64_var try: response = requests.get(url) return response.text except ConnectionError as e: print("Connection to bytefield module, unavailable") return None I'm able to access both containers via my browser successfully, however initiating the code for an internal call between the two throws out requests.exceptions.ConnectionError: HTTPConnectionPool(host='kroki', port=7331): Max retries exceeded with url: /bytefield/svg/<API_URL_HERE> (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f286f5ecaf0>: Failed to establish a new connection: [Errno 111] Connection refused')) I've had a go accessing … -
Internal server error in heroku after deploying django project
I have deployed a project in heroku. The deployment was successful but now I am getting interal server error. After going through the logs i got this 2021-10-29T12:31:11.513605+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/importlib/__init__.py", line 127, in import_module 2021-10-29T12:31:11.513605+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2021-10-29T12:31:11.513606+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1014, in _gcd_import 2021-10-29T12:31:11.513606+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 991, in _find_and_load 2021-10-29T12:31:11.513606+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked 2021-10-29T12:31:11.513607+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 671, in _load_unlocked 2021-10-29T12:31:11.513607+00:00 app[web.1]: File "<frozen importlib._bootstrap_external>", line 843, in exec_module 2021-10-29T12:31:11.513607+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed 2021-10-29T12:31:11.513607+00:00 app[web.1]: File "/app/jgs/urls.py", line 24, in <module> 2021-10-29T12:31:11.513608+00:00 app[web.1]: path('', include('home.urls')), 2021-10-29T12:31:11.513608+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/django/urls/conf.py", line 34, in include 2021-10-29T12:31:11.513608+00:00 app[web.1]: urlconf_module = import_module(urlconf_module) 2021-10-29T12:31:11.513611+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/importlib/__init__.py", line 127, in import_module 2021-10-29T12:31:11.513612+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2021-10-29T12:31:11.513612+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1014, in _gcd_import 2021-10-29T12:31:11.513612+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 991, in _find_and_load 2021-10-29T12:31:11.513612+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked 2021-10-29T12:31:11.513613+00:00 app[web.1]: ModuleNotFoundError: No module named 'home.urls' 2021-10-29T12:31:11.513613+00:00 app[web.1]: 2021-10-29T12:31:11.513613+00:00 app[web.1]: During handling of the above exception, another exception occurred: 2021-10-29T12:31:11.513613+00:00 app[web.1]: 2021-10-29T12:31:11.513613+00:00 app[web.1]: Traceback (most recent call last): 2021-10-29T12:31:11.513614+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner 2021-10-29T12:31:11.513614+00:00 app[web.1]: … -
Count objects on the basis of foreign key
Suppose class Model1(models.Model): post = models.ForeignKey(Post,...) author = models.ForeignKey(User,...) ... Now how do i get a list of model1 objects with author id and number of objects of model1 where author is author. For Example [{userid: 1, noofposts: 5}, {userid: 2, noofposts" 1}, ...] I want to use that code in django serializers. Thanks in Advance! -
Django-React Blog Post Problem With Rendering Markdown Blog Text
I'm building a blog post page using django and react. I have a problem with rendering text content using markdown. Here is Django models code class BlogPost(models.Model): longDescription = MarkupField(default_markup_type='markdown', null = True) I already installed django-markupfield and followed their documentation and everything seems working on the backend when I make a get request from react I get this response as JSON { "longDescription": "<p>Hello World</p>" } and I'm trying to show the text without p tags on my page but react render this as a string I tried using JSON.parse() to parse it but it shows cross origin error Here is my react code : <ReactMarkdown source= {JSON.parse(blogPost.longDescription)} className="mt-6 prose prose-indigo prose-lg text-gray-500 mx-auto" /> from : import React, { useEffect } from 'react'; import { useDispatch, useSelector } from 'react-redux'; import Loader from '../components/Loader'; import Message from '../components/Message'; import { listBlogPostDetails } from '../actions/blogActions'; import ReactMarkdown from "react-markdown"; export default function BlogScreen({ match }) { const dispatch = useDispatch(); const blogDetails = useSelector(state => state.blogDetails); const { loading, error , blogPost} = blogDetails useEffect(() => { dispatch(listBlogPostDetails(match.params.id)) },[dispatch,match]) return ( <div className=" pt-1 mb-10"> { loading? <Loader /> : error ? <Message>{error}</Message> :( <div className="relative mb-20 py-16 max-w-5xl … -
Django ORM Query with 'having' and 'group by'
This is the raw sql query I'm trying to write in Django ORM. SELECT cf, sum(fee) FROM public.report where report_date = '2021-11-01' group by cf having sum(fee) > 500000 I've tried this, but I miss the having part: Report.objects.filter(report_date=date_to).values('cf').annotate(Sum('fee')) I've also tried this, but here I miss the other part to group by fiscal code. Report.objects.filter(report_date=date_to).aggregate(fee=Sum('fee', filter=Q(fee__gte=50000))) I need to join this 2, to make a unique query. -
Django-3.12, Swagger Issue
I am working on Django & Swagger. I built update method for users Model. but Swagger doesn't show 'data' field in Form Pls help me on this. class UserSerializer(serializers.ModelSerializer): label = "Users" allow_null = False[![enter image description here][1]][1] class Meta(object): model = User fields = ('id', 'email', 'first_name', 'last_name', 'is_superuser', 'is_active', 'is_staff', 'position', 'company') read_only_fields = ['email'] def update(self, instance, validated_data): """ This text is the description for this API param1 -- A first parameter param2 -- A second parameter """ return instance -
Python websockets keepalive ping timeout; no close frame received
I have 20-50 users from whom I want real-time information about whether they are connected to the Internet or have a weak Internet I wrote a Python script that checks the connection and sends the information to the web server in Django django-channels script run in the Windows scheduler from 9 am to 6 pm Script async def main(): username = get_username() url = "{}{}/".format(LOG_SERVER, username) async with websockets.connect(url) as websocket: # send info to server while True: try: loop = asyncio.get_event_loop() data = await loop.run_in_executor(None, lambda:get_data(username)) await websocket.send(json.dumps(data)) await asyncio.sleep(30) except websockets.ConnectionClosed as e: print(f'Terminated', e) continue except Exception as e: logging.error(e) if __name__ == "__main__": asyncio.run(main()) WebSockets pack: https://websockets.readthedocs.io/ Send information ping min, max, avg every 30 seconds And make sure that the client is connected as long as it is connected to the server Django Consumer async def connect(self): try: self.username = self.scope['url_route']['kwargs']['username'] await database_sync_to_async(self.update_user_incr)(self.username) except KeyError as e: pass ...... async def disconnect(self, close_code): try: if(self.username): await database_sync_to_async(self.update_user_decr)(self.username) except: pass ....... The problem is that python script occasionally locks up with the message sent 1011 (unexpected error) keepalive ping timeout; no close frame received no close frame received or sent and I can't call back automatic … -
passing access token to the mqtt broker
access_token = 'mytoken' mqttc = mqtt.Client(clientId) mqttc.username_pw_set(username=access_token, password="") mqttc.connect(broker, port) mqttc.subscribe(f"application/{applicationId}/device/{deviceEUI}/uplink") mqttc.on_connect = on_connect mqttc.on_publish = on_publish mqttc.on_subscribe = on_subscribe mqttc.on_message = on_message I am trying to subscribe to the downlink send by my client but the issue , I don't understand how do I send the access token also after the running the code I am getting the below-mentioned error I have already specified onconnect and onmessage callbacks Loading... failed to receive on socket: [WinError 10053] An established connection was aborted by the software in your host machine Loading... -
Can't pickle weakref objects Keras mdoel
I am going to build my project and data is fetched from my database with specific Project_id. and then train my model using LSTM. Epochs are clearly running but after that, It shows an Internal Server Error admin.py def build(self, request, queryset): count = 0 for p in queryset: if build_id(p.project_management.id): count += 1 else: messages.warning(request, f"Could not build model for {p}") messages.success( request, f"Successfully built models for {count} projects") build.short_description = "Build models for selected Projects" bild.py here the model is built via a specific Project_id. Model store only model.pkl data but not completed. And other files scalar_in and scalar_out do not save in a specific folder. def build_id(project_id): # get directory path to store models in path = fetch_model_path(project_id, True) # train model model, scaler_in, scaler_out = train_project_models(project_id) # ensure model was trained if model is None: return False # store models store_model(f'{path}/model.pkl', model) store_model(f'{path}/scaler_in.pkl', scaler_in) store_model(f'{path}/scaler_out.pkl', scaler_out) # clear current loaded model from memory keras_clear() return True utils.py with open(path, 'wb') as f: model_file = File(f) pickle.dump(model, model_file) when I Comment on the pickle.dump(model,model_file) then model.pkl, scalar_in.pkl, and scalar_out.pkl save files with 0 kb data. If pkl files exist already with data then it removes and builds … -
Heroku not recognizing migrations
I finally got my Heroku app to work locally at least! However, when I try to open it online it crashes with the following error: > 2021-10-29T13:16:54.435118+00:00 heroku[web.1]: Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of > launch > 2021-10-29T13:16:56.287092+00:00 heroku[web.1]: Stopping process with SIGKILL > 2021-10-29T13:16:56.458881+00:00 heroku[web.1]: Process exited with status 137 > 2021-10-29T13:16:56.499621+00:00 heroku[web.1]: State changed from starting to crashed > 2021-10-29T13:17:13.107001+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" > host=shrouded-bastion-04661.herokuapp.com > request_id=81455b66-dab8-4b20-9c69-91b73739a09a fwd="71.231.14.146" > dyno= connect= service= status=503 bytes= protocol=https > 2021-10-29T13:17:13.558163+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" > host=shrouded-bastion-04661.herokuapp.com > request_id=c6b25451-528e-4bed-a415-f35b0bcb739f fwd="71.231.14.146" > dyno= connect= service= status=503 bytes= protocol=https I'm not really sure what to make of it but when I ran the app locally it said: 2021-10-29T13:15:49.232426+00:00 heroku[web.1]: State changed from crashed to starting 2021-10-29T13:15:54.128556+00:00 heroku[web.1]: Starting process with command `python manage.py runserver 0.0.0.0:5000` 2021-10-29T13:15:55.975995+00:00 app[web.1]: Watching for file changes with StatReloader 2021-10-29T13:15:55.976241+00:00 app[web.1]: Performing system checks... 2021-10-29T13:15:55.976241+00:00 app[web.1]: 2021-10-29T13:15:56.168039+00:00 app[web.1]: System check identified no issues (0 silenced). 2021-10-29T13:15:56.434599+00:00 app[web.1]: 2021-10-29T13:15:56.434616+00:00 app[web.1]: You have 20 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, boutique, contenttypes, sessions. 2021-10-29T13:15:56.434619+00:00 … -
Problem with django-jet and Google Analytics widgets
I followed the entire documentation (https://github.com/assem-ch/django-jet-reboot) for installing the dashboard. Everything works as it should except for the Google Analytics widgets. After the command "pip install google-api-python-client==1.4.1" the Google Analytics widgets are not there inside the panel: Can anyone help me? -
Django celery redis, recieved task, but not success not fail message, how to fix?
When i run celery task i got this. Windows 10, redis celery 5. video try [2021-10-29 19:08:18,216: INFO/MainProcess] Task update_orders[55790152-41c0-4d83-8874-4bd02754cb77] received [2021-10-29 19:08:19,674: INFO/SpawnPoolWorker-8] child process 7196 calling self.run() / My celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery from celery.schedules import crontab os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'src.settings.local') BASE_REDIS_URL = os.environ.get('REDIS_URL', 'redis://localhost:6379') app = Celery('src') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() app.conf.broker_url = BASE_REDIS_URL @app.task(bind=True) def debug_task(self): print("Request: {0!r}".format(self.request)) app.conf.beat_scheduler = 'django_celery_beat.schedulers.DatabaseScheduler' app.conf.worker_cancel_long_running_tasks_on_connection_loss = True my tasks.py import random from celery import shared_task from django.shortcuts import get_object_or_404 import datetime from config.models import Config @shared_task(name="update_orders") def update_orders(): print('Delayed') obj = Config.objects.all().order_by("-id").last() obj.orders_last_time_updated = datetime.datetime.now() obj.save() return True My settings # CELERY STUFF CELERY_BROKER_URL = 'redis://127.0.0.1:6379' CELERY_RESULT_BACKEND = 'redis://127.0.0.1:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = TIME_ZONE DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' CELERY_RESULT_BACKEND = "django-db" It looks like your post is mostly code; please add some more details. It looks like your post is mostly code; please add some more details.It looks like your post is mostly code; please add some more details. -
ModuleNotFoundError: No module named 'rest_framework' python3 django
I copied code from blog and i got this error. Actually i am newbie in django and stackoverflow too. i copied code from github blog so easly i can reach to my aim. line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'rest_framework' Copied code is from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, UserManager from phonenumber_field.modelfields import PhoneNumberField ) class Address(models.Model): address_line = models.CharField( _("Address"), max_length=255, blank=True, null=True ) street = models.CharField( _("Street"), max_length=55, blank=True, null=True) city = models.CharField(_("City"), max_length=255, blank=True, null=True) state = models.CharField(_("State"), max_length=255, blank=True, null=True) postcode = models.CharField( _("Post/Zip-code"), max_length=64, blank=True, null=True ) country = models.CharField( max_length=3, choices=COUNTRIES, blank=True, null=True) return address -
How to have a Seperate REST API that only handles authentication for multiple app
I have developed multiple Django REST APIs, each with their own user authentication system, using tokens for authentication. I want to have all the APIs only use a single authentication database such that I can have a single front end where a user can log in, and then access multiple apps, each using their own API. Is there a way whereby an API can make an API call to a central API with a user database for authentication? Or What would be industry/best practice to achieve this? -
Is there any solution for the {"detail":"Method \"POST\" not allowed."}
views.py code: @api_view(['POST']) @permission_classes([IsAdminUser]) def createProduct(request): user = request.user product = Product.objects.create( user = user, name = 'sample name', price =4, countInStock = 12, category = 'Sample category', brand = 'Sample Brand', description = 'Sample Description', ) serializer = ProductSerializer(product, many=False) return Response( serializer.data ) urls.py path('products/create/',views.createProduct , name='product-create' ), Error that i got : {"detail":"Method "POST" not allowed."} -
Django - create a file for FileField inside media
I want to store log files (that change over time) that users can explore. As I want to serve these files but also change them programmatically whenever I need, I want to use FileField and store the files inside the media folder. First, when the object is created, I want to create an empty file <UUID>.log so I can access/update it then. How to create a default empty log file? class MyModel(..): log_file = FileField(upload_to='user_logs') def _create_log_file(self): content = '' filename = str(uuid4())+'.log' ... # what to do here? -
(Django) Admin datatable does not show data in the select field
below is the issue I'm having: The drug type column, which is a select field with specified options drug_types_list = ( ('pills','PILLS'), ('pellets','PELLETS'), ('lozenges','LOZENGES'), ) somehow did not show any data. Even though inside my Jquery Datatable everything displayed. So I went to my drugs/admin.py and modified the code as followed: from django.contrib import admin from import_export.admin import ImportExportModelAdmin # local from .models import Drug from .forms import DrugForm class DrugAdmin(ImportExportModelAdmin): fields = ('drug_type',) # added list_display = ['drug_id', 'name', 'drug_type', 'amount'] form = DrugForm # added list_per_page = 20 search_fields = ['drug_id', 'name', 'drug_type', 'brand', 'description'] admin.site.register(Drug, DrugAdmin) I aslo changed the drug_type line inside my drugs/forms.py as followed: from django import forms # local from drugs.models import Drug from .drug_types import drug_types_list class DrugForm(forms.ModelForm): class Meta: model = Drug fields = [ 'drug_id', 'name', 'drug_type', 'amount', ] widgets = { 'drug_id': forms.TextInput(attrs={ 'class': 'form-control', 'data-val': 'true', 'data-val-required': 'Please enter drug id', }), 'name': forms.TextInput(attrs={ 'class': 'form-control' }), 'drug_type': forms.Select(attrs={'class': 'form-control'}, choices=drug_types_list), # modified 'amount': forms.TextInput(attrs={ 'class': 'form-control' }), } but nothing worked so far. drugs/models.py Below is my drug model: from django.db import models from .drug_types import drug_types_list class Drug(models.Model): drug_id = models.CharField(max_length=20, unique=True, error_messages={'unique':"This drug id has … -
Django Redis Connection reset
Iam trying to use django_redis for redis cache backend for Django. The app is working fine in development stage on the localhost. But after deployment on Heroku and using django_redis for redis cache The connection is getting reset and the page crashes with 500 internal server error 2021-10-29T12:10:20.450924+00:00 heroku[router]: at=info method=GET path="/" host=www.humaurtum-matrimony.com request_id=37a90921- 9d8d-46c6-9d6a-888d34fb1d01 fwd="42.106.161.10" dyno=web.1 connect=0ms service=2701ms status=500 bytes=5280 protocol=https 2021-10-29T12:10:20.447599+00:00 app[web.1]: 2021-10-29 17:40:18,010 ERROR Internal Server Error: / 2021-10-29T12:10:20.447606+00:00 app[web.1]: Traceback (most recent call last): 2021-10-29T12:10:20.447607+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/django_redis/cache.py", line 27 , in _decorator 2021-10-29T12:10:20.447608+00:00 app[web.1]: return method(self, *args, **kwargs) 2021-10-29T12:10:20.447608+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/django_redis/cache.py", line 94 , in _get 2021-10-29T12:10:20.447609+00:00 app[web.1]: return self.client.get(key, default=default, version=version, client=client) 2021-10-29T12:10:20.447609+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/django_redis/client/default.py" , line 222, in get 2021-10-29T12:10:20.447609+00:00 app[web.1]: raise ConnectionInterrupted(connection=client) from e 2021-10-29T12:10:20.447610+00:00 app[web.1]: django_redis.exceptions.ConnectionInterrupted: Redis ConnectionError: Error while rea ding from socket: (104, 'Connection reset by peer') 2021-10-29T12:10:20.447610+00:00 app[web.1]: 2021-10-29T12:10:20.447611+00:00 app[web.1]: During handling of the above exception, another exception occurred: 2021-10-29T12:10:20.447611+00:00 app[web.1]: 2021-10-29T12:10:20.447612+00:00 app[web.1]: Traceback (most recent call last): 2021-10-29T12:10:20.447612+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/django/core/handlers/exception. py", line 34, in inner 2021-10-29T12:10:20.447613+00:00 app[web.1]: response = get_response(request) 2021-10-29T12:10:20.447614+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response 2021-10-29T12:10:20.447614+00:00 app[web.1]: response = self.process_exception_by_middleware(e, request) 2021-10-29T12:10:20.447614+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response 2021-10-29T12:10:20.447615+00:00 app[web.1]: … -
Django broken pipe occurs with CORS setting
I want to connect flutter app with my Django API, but broken pipe keeps occuring. settings.py """ Django settings for crawler project. Generated by 'django-admin startproject' using Django 3.2.6. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ 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/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-)4%#q5&d3^5=0!bauz62wxmc9csk*_c09k!jl2g1a-0rxsa--j' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'crawling_data', 'rest_framework', 'corsheaders', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', '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 = 'crawler.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], '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 = 'crawler.wsgi.application' # Database # https://docs.djangoproject.com/en/3.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { … -
Write the o/p into a new text file with table format below for each iteration appends in python
Write the o/p into a new text file with table format below for each iteration appends. ( i,e in for loop, 5th iteration coms number 5 which is divisible by 5 so this one should write into file) ----------------------------------------------------------- Iteration | Value 5 5 10 10 15 15 -
Unable to configure formatter 'json': Cannot resolve 'app_name.utils.logging.JSONFormatter': cannot import name 'Celery'
I am trying to include celery into our Django app and am struggling with the setup. So far all my searching of stackoverflow/google tells me I have a circular dependency, but I can't see it. The docs, https://docs.celeryproject.org/en/stable/getting-started/first-steps-with-celery.html, clearly use from celery import Celery I have defined: app_name/app_name_celery.py with from celery import signals, Celery import os from django.conf import settings # disable celery logging so that it inherits from the configured root logger @signals.setup_logging.connect def setup_celery_logging(**kwargs): pass os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.local") # Create default Celery app app = Celery('app_name') # namespace='CELERY' means all celery-related configuration keys # should be uppercased and have a `CELERY_` prefix in Django settings. # https://docs.celeryproject.org/en/stable/userguide/configuration.html app.config_from_object("django.conf:settings", namespace="CELERY") # When we use the following in Django, it loads all the <appname>.tasks # files and registers any tasks it finds in them. We can import the # tasks files some other way if we prefer. app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) Additionally, I have defined app_name/my_app_config.py with from django.apps import AppConfig class MyAppConfig(AppConfig): # ... def ready(self): # Import celery app now that Django is mostly ready. # This initializes Celery and autodiscovers tasks import app_name.app_name_celery Lastly, I have added to my __init__.py: # This will make sure the app is always imported … -
Python package: should I transform my code?
3 things you need to know for context: I have never done this before, so try to keep everything low level, or in simple steps. I have pretty good knowledge of Python and HTML (and JS) but I don't have ton of experience. I am doing this on a Chromebook, without access to Linux. (I do have access to JSLinux though) I have a Python project that is organized something like this / -- QaikeAI_1.py # This is what is actually run to use the program -- QHelper.py # Has helper functions, imported into QaikeAI_1.py -- Qepicenter.py # "The meat of the AI" imported into QHelper.py -- Qlog.py # A logfile -- Various other files (.gitignore, .replit, .gitpod.yml) Should I transform my code into a package? I want to use a Python web framework on gh-pages. Remember, I am on a Chromebook. The actual code is hosted on Github.com -
DRF post to a flask server using pytest
I am writing a test suite in Django wherein post requires flask server to be running in order to successfully return a 201 response. How can I mock that in my test? Here's a snippet of what I've tried: def test_something(self, data): response = self.client.post(reverse('myurl'), data) assert response.status_code == 201 The error here is that the flask server is not running that's why the status code is not as expected.