Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Connecting flutter with Django API in localhost, but CORS issue keeps blocking connection
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': … -
Is there a way to annotate a related field in django?
Is something like this possible? m = Message.objects.annotate(room__something=Value('DOH', output_field=CharField())).select_related('room') m.room.something == 'DOH' # is true -
Request help for webscraping issues
I have been trying to webscrape two websites for data but facing issues. I will be extremely glad if anyone can help in resolving the problem 1.https://online.capitalcube.com/ The website requires one to login. I came up with the following code after watching tutorials on youtube for the last 2 days. from bs4 import BeautifulSoup import pandas as pd import requests URL = 'https://online.capitalcube.com/' LOGIN_ROUTE = '/login' import requests headers = { 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:93.0) Gecko/20100101 Firefox/93.0', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8', 'Accept-Language': 'en-US,en;q=0.5', 'Connection': 'keep-alive', 'Upgrade-Insecure-Requests': '1', 'Sec-Fetch-Dest': 'document', 'Sec-Fetch-Mode': 'navigate', 'Sec-Fetch-Site': 'none', 'Sec-Fetch-User': '?1', 'TE': 'trailers', } s = requests.session() login_payload = { 'email': '<intentionally removed it>', 'password': '<intentionally removed it>' } login_req = s.post(URL + LOGIN_ROUTE, headers = headers, data = login_payload) print(login_req.status_code) The error i am getting is as follows *Traceback (most recent call last): File "/Users/rafatsiddiqui/opt/anaconda3/envs/scientificProject/lib/python3.9/site-packages/urllib3/connectionpool.py", line 699, in urlopen httplib_response = self._make_request( File "/Users/rafatsiddiqui/opt/anaconda3/envs/scientificProject/lib/python3.9/site-packages/urllib3/connectionpool.py", line 382, in _make_request self._validate_conn(conn) File "/Users/rafatsiddiqui/opt/anaconda3/envs/scientificProject/lib/python3.9/site-packages/urllib3/connectionpool.py", line 1010, in validate_conn conn.connect() File "/Users/rafatsiddiqui/opt/anaconda3/envs/scientificProject/lib/python3.9/site-packages/urllib3/connection.py", line 416, in connect self.sock = ssl_wrap_socket( File "/Users/rafatsiddiqui/opt/anaconda3/envs/scientificProject/lib/python3.9/site-packages/urllib3/util/ssl.py", line 449, in ssl_wrap_socket ssl_sock = ssl_wrap_socket_impl( File "/Users/rafatsiddiqui/opt/anaconda3/envs/scientificProject/lib/python3.9/site-packages/urllib3/util/ssl.py", line 493, in _ssl_wrap_socket_impl return ssl_context.wrap_socket(sock, server_hostname=server_hostname) File "/Users/rafatsiddiqui/opt/anaconda3/envs/scientificProject/lib/python3.9/ssl.py", line 500, in wrap_socket return self.sslsocket_class._create( File … -
Django models.DateTimeField, how to store the value without seconds?
I have this model class Appointments(models.Model): options = ( ('waiting', 'In Attesa'), ('confirmed', 'Confermato'), ('closed', 'Chiuso'), ) duration = ( ('15', '15 minuti'), ('20', '20 minuti'), ('30', '30 minuti'), ('40', '40 minuti'), ) date = models.DateTimeField(default=timezone.now) patient_first_name = models.CharField(max_length=250) patient_last_name = models.CharField(max_length=250) patient_email = models.EmailField(_('email address')) patient_phone = models.CharField(max_length=250) doctor = models.ForeignKey(Doctor, on_delete=models.PROTECT) room = models.ForeignKey(Room, on_delete=models.PROTECT, default=1) status = models.CharField(max_length=10, choices=options, default='waiting') message = models.TextField(null=True, blank=True) notes = models.TextField(null=True, blank=True) appointment_date = models.DateTimeField(null=True, blank=True) duration = models.CharField(max_length=10, choices=duration, default='15') class Meta: ordering = ('-date', ) unique_together = ('appointment_date', 'room', ) How can I store appointment_date value without seconds in the DB? Right now the value is like this 2021-11-05 17:30:43 I'd like to store it as 2021-11-05 17:30 That's because otherwise unique_together is basically useless for what I need. -
Displaying rating star in Django
I am writing a small Django website and I want display rating stars but am a bit stuck. In my html file, I am doing something like below <div class="rating-star"> <span> <i class="fas fa-star{% if review.rating == 0.5 %}-half-alt {% endif %}" aria-hidden="true"></i> <i class="fas fa-star{% if review.rating == 1.5 %}-half-alt {% endif %}" aria-hidden="true"></i> <i class="fas fa-star{% if review.rating == 2.5 %}-half-alt {% endif %}" aria-hidden="true"></i> <i class="fas fa-star{% if review.rating == 3.5 %}-half-alt {% endif %}" aria-hidden="true"></i> <i class="fas fa-star{% if review.rating == 4.5 %}-half-alt {% endif %}" aria-hidden="true"></i> </span> </div> In each <i> tag, I also want use elif to display far fa-star. Let me show an example using fontawesome v4.7. In fontawesome v4.7, it looks like below and I want to achieve the same thing with fontawesome v5.13 but I don't know to <span> <i class="fa fa-star{% if review.rating == 0.5 %}-half-o{% elif review.rating < 1 %}-o {% endif %}" aria-hidden="true"></i> <i class="fa fa-star{% if review.rating == 1.5 %}-half-o{% elif review.rating < 2 %}-o {% endif %}" aria-hidden="true"></i> <i class="fa fa-star{% if review.rating == 2.5 %}-half-o{% elif review.rating < 3 %}-o {% endif %}" aria-hidden="true"></i> <i class="fa fa-star{% if review.rating == 3.5 %}-half-o{% elif review.rating < … -
Update a string in database using django? [closed]
Lets say I have an table named, Class Food: item = models.CharField(max_length=32, blank=True) And for example there is a record as follows, egg carrot Now i need to update "egg" with "egg1239812", How to update this ? For int fields we can use "F" expression to add and update. How to update a string using django without removing it ? -
Django bulk create with self reference foreign key
I have a question about Django objects creation using bulk_create() Here is a part of my model : class Group(models.Model): uid = models.IntegerField(unique=True) persons = models.ManyToManyField(User, blank=True) label = models.CharField(max_length=128) parent_group = models.ForeignKey('self', on_delete=models.SET_NULL, null=True, blank=True) And then I want to create like this : df_records = df.to_dict('records') model_instances = [Group( uid = record["uid"], label = record["label"], group_parent = Group(uid=record["parent_uid"]), ) for record in df_records] Group.objects.bulk_create(model_instances) Is it possile to self reference parent in a bulk create (of course the parent is in the same bulk) ? Or I have to set parent to null and iterrate throught all objects to find the parent django object id ? -
Django can't compare offset-naive and offset-aware datetimes
If the time has not exceeded three minutes, I want to proceed to the next actions django models: class ActivationCode(models.Model): blablabla activate_code_expiry = models.DateTimeField(default=datetime.now, blank=True,null=True) views.py: activation = ActivationCode.objects.get(user_id=request.user.id) if activation.activate_code_expiry < (datetime.now()-timedelta(minutes=3)): blablablabla -
i am unable to execute the sudo python3 manage.py setup i have .env and settings.py file in same location so please help to resolve the issue
strong text below error i am getting while executing the sudo python3 manage.py setup enter image description here django.core.exceptions.ImproperlyConfigured: Set the MEDIA_ROOT environment variable enter image description here please find the exact error which im getting -
django admin form does not work in inline
This is my form class LoginForm(ModelForm): class Meta: model = Login fields = '__all__' widgets = { 'password': PasswordInput(), } This is my inline class LoginInline(admin.StackedInline): model = Login This is my admin class AppAdmin(admin.ModelAdmin): list_display = ('name', 'link_href') inlines = [LoginInline] class LoginAdmin(admin.ModelAdmin): form = LoginForm When I try to add login from login page, the password is correctly applied But not from the app page using inline How can I fix this ? -
Replacing template with another with Django
I am trying to find a way to replace only a section of a web page with another template based on the change of a drop down. Also I don't want the rest of the page to reload. I'm using jquery to call the function when the drop down is changed so that's not an issue. The closest way I have is to use ajax replace the contents of a div with something else but when I try to pass a django tag that would refer to another html template, the string "{% include 'upgrading_template.html' %}" prints on the page rather than reading it as an include statement. I have also tried methods like replaceWith() but I get the same result. $.ajax({ type: 'GET', url: {% url 'sw_upgrade' %}, data: parameters, success: function (response) { document.getElementById('upgrade_template').innerHTML = "{% include 'upgrading_template.html' %}"; } }) -
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.