Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django.db.utils.ProgrammingError: relation does not exist
I developed a Django application deployed on DigitalOcean's Ubuntu server with Postgres db. Everything worked fine, without any problems, but today after adding new model, I'm getting this error: relation "documents_app_document" does not exist although I have this model, where some of my models inherits from Document model. But somehow it was deleted from database, and now I can't add it back to database after migration. How can I add that model as a table again to database ? -
why the form is invalid on post
I have records in my model. I want to list the existing records and edit and add more records. I successfully got the records to my template and edit. I can add new records also. it is working fine in template. But when I post the form is invalid and print invalid message as per my code http response. I can not figure out what is the mistake. Please advise. forms.py: class NewTransForm(forms.ModelForm): th_no = forms.DecimalField(max_digits=5,error_messages={"max_digits":"Transaction number should be less than 6 digits.","unique":"Transaction number already exists."}) class Meta: model = TransHeader fields = ['th_no','th_dt','th_type', 'th_code','th_cust_code','th_sm_code','th_ref'] ... urls.py: path('edit_sales_transaction_details/<int:trans_id>/',views.EditSalesTransaction, name="edit_sales_transaction"), views.py: def EditSalesTransaction(request,trans_id): # template_name= "wstore/edit_sales_transheader_input.html.html" # trans_id =kwargs['trans_id'] if request.method == "POST": print(request.POST) form = NewTransForm(request.POST) if form.is_valid(): # trans_id =kwargs['trans_id'] exist_trans_header = TransHeader.objects.get(id=int(trans_id)) TransBody.objects.filter(trans_header=exist_trans_header).delete() exist_trans_header.delete() obj = form.save() books = request.POST.getlist('book_code') quantities = request.POST.getlist('quantity') prices = request.POST.getlist('price') for book_code,quantity,price in zip(books,quantities,prices): try: book = TextBook.objects.get(code=book_code) TransBody.objects.create(trans_header_id=obj.id,quantity=quantity,price=price,book=book) except Exception as e: print(e) if request.POST.get('save_home'): return redirect('saltransactions') else: print(NewTransForm.errors) # return redirect(reverse('view_sales_transaction', kwargs=kwargs['trans_id'])) return HttpResponse("form is invalid.. this is just an HttpResponse object") else: form = NewTransForm() context = {} # trans_id =kwargs['trans_id'] context['trans_header'] = TransHeader.objects.get(id=int(trans_id)) trans_body = TransBody.objects.filter(trans_header=context['trans_header']) context['trans_body'] = trans_body context['total_quantity'] = trans_body.aggregate(Sum('quantity')) context['total_price'] = trans_body.aggregate(Sum('price')) context['current_date'] = datetime.datetime.strftime(datetime.datetime.now(),"%Y-%m-%d") … -
How to implement carousel in django with col-md?
I would like to load django model instance in a js carousel with col-md. How should i do that? -
Django pre-save
I'm working on my first project with Django ,it's a personal blog the story model has 'beginning' filed that is first 100 characters of the story itself I want to create beginning with pre_save but I got error always : in admin section when I add a story and leave the beginning blank ,Django say 'this field is required'!! this works very good in another file here is the code : from django.db import models from django.db.models.signals import pre_save from my_blog_tags.models import Tag # Create your models here. class Story(models.Model): title = models.CharField(max_length=75) story = models.TextField() beginning = models.CharField(max_length=100) tags = models.ManyToManyField(Tag, blank=True) active = models.BooleanField(default=True) views = models.IntegerField(default=0) def __str__(self): return self.title class Meta: verbose_name = "story" verbose_name_plural = "stories" def story_pre_save(sender, instance: Story, *args, **kwargs): if not instance.beginning: story = str(instance.story) instance.beginning = story[:100] pre_save.connect(story_pre_save, sender=Story) -
I am getting LocalUnboundError
This is my views.py file: url = "https://covid-193.p.rapidapi.com/statistics" headers = { 'x-rapidapi-key': "c5e4f10fa8msh519e24367741e55p1dcabajsn27df4eda14e0", 'x-rapidapi-host': "covid-193.p.rapidapi.com" } response = requests.request("GET", url, headers=headers).json() def home(request): noofresults = int(response['results']) mylist = [] for x in range(0,noofresults): mylist.append(response['response'][x]['country']) if request.method=='POST': selectedcountry= request.POST['selectedcountry'] # noofresults = int(response['results']) for x in range(0,noofresults): if selectedcountry==response['response'][x]['country']: new = response['response'][x]['cases']['new'] active = response['response'][x]['cases']['active'] critical = response['response'][x]['cases']['critical'] recoverd = response['response'][x]['cases']['recovered'] total = response['response'][x]['cases']['total'] deaths = int(total)-int(active) - int(recoverd) context = {'selectedcountry':selectedcountry,'mylist':mylist, 'new':new, 'active':active, 'critical':critical, 'recoverd':recoverd, 'total':total, 'deaths':deaths} return render(request,'home.html',context) context = {'mylist': mylist} return render(request, 'home.html',context) The error i am getting after selecting a country is: UnboundLocalError at / local variable 'new' referenced before assignment -
How to Fix no reverse match with argument in django
I have the following error in Django, I'm new to Django and i Cant seem to figure where the error is coming from. no tutorial seems to help either. I have a feeling the error might be coming from urls.py but cant seem to navigate it where do you think the error is? NoReverseMatch at / Reverse for 'subcategory_detail' with arguments '('DEFAULT VALUE',)' not found. 2 pattern(s) tried: ['category/(?P<category_slug>[\\w-]+)/$', '$'] Here is my models.py from django.db import models from django.urls import reverse from django.utils.text import slugify from datetime import datetime class Category(models.Model): title = models.CharField(max_length=30, default="Random") slug = models.SlugField(max_length=100, unique=True, blank=True, null=True) category_thumbnail = models.CharField(max_length=400, default='DEFAULT VALUE', blank=True, null=True) category_description = models.CharField(max_length=400, default='DEFAULT VALUE', blank=True, null=True) def __str__(self): return self.title class Meta: verbose_name_plural = "Categories" def get_absolute_url(self): return reverse("subcategory_detail", args=[self.slug]) class SubCategory(models.Model): title = models.CharField(max_length=30, default="Random") categories = models.ForeignKey(Category, on_delete=models.CASCADE, blank=True, null=True) slug = models.SlugField(max_length=100, unique=True, blank=True, null=True) subcategory_thumbnail = models.CharField(max_length=400, default='DEFAULT VALUE', blank=True, null=True) subcategory_description = models.CharField(max_length=400, default='DEFAULT VALUE', blank=True, null=True) def __str__(self): return self.title class Meta: verbose_name_plural = "SubCategories" class Tag(models.Model): name = models.CharField(max_length=100, unique=True, blank=True, null=True) slug = models.SlugField(max_length=100, unique=True, blank=True, null=True) def __str__(self): return self.name def get_absolute_url(self): return reverse('lesson_by_tag', args=[self.slug]) class Lessons(models.Model): title = models.CharField(max_length=200) slug … -
Adding schema name to media path for django-tenant based site
I have a Django class that I use to save my media directory to Azure. This uses Django-tenants https://github.com/django-tenants/django-tenants and I need to return the name of the schema to the media path. When I want to run this locally, if I change the DEFAULT_FILE_STORAGE = "django_tenants.files.storage.TenantFileSystemStorage" the media files are saved as media/schema_name. But if I use Azure it ommits the schema name. stroages.py from storages.backends.azure_storage import AzureStorage from django_tenants.files.storage import TenantFileSystemStorage class AzureMediaStorage(AzureStorage, TenantFileSystemStorage): account_name = settings.AZURE_ACCOUNT_NAME account_key = settings.AZURE_STORAGE_KEY azure_container = settings.AZURE_MEDIA_CONTAINER expiration_secs = 30 overwrite_files = True Settings.py: DEFAULT_FILE_STORAGE = 'saleor.core.storages.AzureMediaStorage' STATICFILES_STORAGE = "django_tenants.staticfiles.storage.TenantStaticFilesStorage" MULTITENANT_RELATIVE_MEDIA_ROOT = " -
How exactly do django serializers and views work together? And how can I return additional data with my queryset to the frontend?
I'm working with a react front end and a django rest framework backend, and I'm having trouble understanding what happens in between the view and the serializer. I want to return additional metadata that is not part of the queryset to the front end. Here is the flow of my application My frontend calls an endpoint: Server.get("api/books-filtered") This goes to a path in the backend written with django rest framework: path("books-filtered/", Books.BookList.as_view()), and then to class Books(generics.RetrieveAPIView): serializer_class = BookSerializer lookup_field = 'id' lookup_url_kwarg = 'book_id' def get_queryset(self): """Return only queries pertaining to the patient""" return FilterOutSomeBookRelatedQuerySetHere() whose serializer class is: class BookSerializer(SurveySerializer): class Meta: model = Book fields = ['Title','Author','Publisher'] I get this back on the front end: console.log(Server.get("api/books-filtered")) // prints [{Title:"book 1", Author:"author 1", Publisher:"publisher 1"},{Title:"book 2", Author:"author 2", Publisher:"publisher 2"},{Title:"book 3", Author:"author 3", Publisher:"publisher 3"}] What happens between the view and the serializer that causes the data to be formatted like that by the time its sent back to the frontend? How can I modify what gets printed by console.log(Server.get("api/books-filtered")) to include additional metadata? Like console.log(Server.get("api/books-filtered")) // prints [{Title:"book 1", Author:"author 1", Publisher:"publisher 1"},{Title:"book 2", Author:"author 1", Publisher:"publisher 2"},{Title:"book 3", Author:"author 1", Publisher:"publisher 2"}, [3 books, 2 … -
Django app custom clean up for code reload
my Django project has an app which overrides its AppConfig.ready() method. In the ready method, I'm starting a separate multiprocessing.Process to handle consuming from an external message queue, this seems to be causing problems with autoreload on code changes. def infinite_loop(): while True: time.sleep(10) class BrokerConfig(AppConfig): name = 'backend.broker' has_started = False def ready(self): if not os.environ.get("RUN_MAIN"): # Avoid running for reloader return if BrokerConfig.has_started: return BrokerConfig.has_started = True proc = Process(target=infinite_loop) proc.start() For whatever reason, this causes the automatic code reload to break. Seems the reloader is not able to clean up started processes. The reloader prints this and then gets stuck: .../backend/broker/apps.py changed, reloading. I run into exactly the same issue if I start a threading.Thread instead of a multiprocessing.Process. I am looking for some way to add some custom clean up when the reloading is happening, but I can't seem to find a way to do that. Is there some hook or signal you can subscribe to in order to find out if reloading has been triggered? Alternatively, I need to find another solution to subscribing to message queues. I was looking at Django Channels, but it did not look like they had built-in support for RabbitMQ, … -
Django - How to logging by decorator?
I want to set up logging for every single API function by using decorator for simplicity. But keep encountering the same error. Please help settings.py log_dir = './log' #create a folder for logging log_dir = os.path.abspath(log_dir) if log_dir and not os.path.exists(log_dir): os.mkdir(log_dir) LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'formatters': { 'short': { #for internal errors 'format': '%(asctime)s.%(msecs)03d|%(levelname)s|%(message)s', 'datefmt': '%Y-%m-%d %H:%M:%S', }, 'data': { #for error relate to db 'format': '%(asctime)s.%(msecs)03d|%(message)s', 'datefmt': '%Y-%m-%d %H:%M:%S', }, }, 'handlers': { 'file_fatal': { #folder for db errors 'level': 'CRITICAL', 'class': 'logging.FileHandler', 'filename': os.path.join(log_dir, 'fatal.log').replace('\\', '/'), 'formatter': 'data', }, 'file_info': { #folder for internal errors 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': os.path.join(log_dir, 'info.log').replace('\\', '/'), 'formatter': 'short', }, }, 'loggers': { 'main': { 'handlers': ['file_info'], 'level': 'DEBUG', 'propagate': True, }, } } This is my views.py def func_detail(func): #function for the decorator @wraps(func) def func_wrapper(requests,*args, **kwargs): log = logging.getLogger('main') try: response = func(requests, *args, **kwargs) except: log.debug('Exception', func.__name__) class simple_function(generics.GenericAPIView): @func_detail def get(self,requests): input_1 = requests.GET.get('input_1') input_2 = requests.GET.get('input_2') input_3 = requests.GET.get('input_3') return JsonResponse([{'aaa':111, 'bbb':222, 'ccc':333}],safe =False) Got this error when running it: TypeError at /simple_function 'NoneType' object is not callable When I comment out the decorator @func_detail, it works normally -
'Incorrect Padding' error while using google.oauth2 id_token.verify_oauth2_token() in Django
I am trying to verify a user's submitted google authentication JWT from a React frontend to my Django backend. I have my frontend POST a request to the backend with the JWT, and then my backend extracts it from the request and processes it through google's recommend token authentication found here. My problem is that each time I process a JWT received from my frontend through id_token.verify_ouath2_token(), an error about 'incorrect padding' is raised ultimately stemming from the base64 encoding of the token. When testing this manually by copy-pasting the token I have extracted from the POST request, however, it works perfectly fine and does not raise an error. So somewhere in my handling of the post request something goes wrong, but I'm not sure what. I have tried decoding the POST request in utf-8 and ascii, and simply leaving the JWT in the bytes form that I extracted it as. All of these throw the same error, and I'm left pretty confused. Here is my code: views.py def login(request): if request.method == "POST": print(request.body.decode("ascii")) # For decoding. By copy/pasting this output into id_token.verify_oauth2_token instead of the token variable, the function returns successfully try: token = request.body.decode("ascii") # Specify the … -
Assigning Value(s) to ManyToMany Field
I'm trying to assign a value onto a ManyToMany field in the Order class. def assign_order(request, user_id): order_id = request.session.get('order_id') #picking this session from a previous fxn allowing me to call the order.id order = get_object_or_404(Order, id=order_id) employee = Employee.objects.filter(user_id=user_id) #Employee is a profile model leveraging an AbstractUser order.deliverer.set(employee) #using .set() for direct assignment of user(Employee) onto ManyToMany field on "Order" order.status = 'deliverer_assigned' order.save() The problem with this schema is that the fxn will always overwrite my ManyToMany field rather than append a new User(Employee profile) onto it. 1. Is there a better way of accomplishing what I need? i.e. Updating a ManyToMany field outside the admin? 2. How do I prevent the overwrite problem in this scenario? -
unable to import rest_framework_simplejwt
I have installed djangorestframework-simplejwt package and trying to import that module in urls.py and views.py but still its not working .Please guide me to solve this issue.. pip list ''' Package Version ----------------------------- ------- asgiref 3.3.1 Django 3.1.4 djangorestframework 3.12.2 djangorestframework-simplejwt 4.6.0 pip 20.2.3 PyJWT 1.7.1 pytz 2020.4 setuptools 49.2.1 sqlparse 0.4.1 Settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'Django_MedicalApp', 'rest_framework', 'rest_framework_simplejwt',] REST_FRAMEWORK = {'DEFAULT_AUTHENTICATION_CLASSES': ['rest_framework_simplejwt.authentication.JWTAuthentication',], 'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.AllowAny','rest_framework.permissions.IsAuthenticatedOrReadOnly',)} urls.py from rest_framework_simplejwt.views import TokenObtainPairView router = routers.DefaultRouter() router.register('Company',views.CompanyViewset,basename='Company') urlpatterns = [ path('admin/', admin.site.urls), path('api/',include(router.urls), path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'))] views.py from rest_framework_simplejwt.authentication import JWTAuthentication class CompanyViewset(viewsets.ViewSet): authentication_classes = [JWTAuthentication] ''' please help me to resolve this import error -
I am having urls.py patterns errors
from django.urls import path from django.urls import include from . import views urlpatterns=[ path("",views.index,name="index") ] i have views.py as follows from django.shortcuts import render from . models import ClientServiceRepresentative # Create your views here. def index(request): return render(request,"ClientServicesManagement/index.html",{"representatives":ClientServiceRepresentative.objects.all()}) When I run the application i get following error File "C:\Users\hp\KHSystem\KHSystems\ClientServicesManagement\urls.py", line 6, in <module> path("",views.index,name="index") AttributeError: module 'ClientServicesManagement.views' has no attribute 'index' I have clearly defined index in views why i am having this problem -
Django Static files not found - Site works but not pulling through static files - 404 console message
I am receiving a 404 for my static files, pages load but when inspect the console it relays the following errors, i've been sratching my head for while on this one. Would someone be able to point me in the right direction, it would be massively appreciated!: 127.0.0.1/:10 GET http://127.0.0.1:8000/static/css/all.css net::ERR_ABORTED 404 (Not Found) 127.0.0.1/:12 GET http://127.0.0.1:8000/static/css/bootstrap.css net::ERR_ABORTED 404 (Not Found) 127.0.0.1/:14 GET http://127.0.0.1:8000/static/css/style.css net::ERR_ABORTED 404 (Not Found) 127.0.0.1/:16 GET http://127.0.0.1:8000/static/css/lightbox.min.css net::ERR_ABORTED 404 (Not Found) 127.0.0.1/:26 GET http://127.0.0.1:8000/static/js/jquery-3.3.1.min.js net::ERR_ABORTED 404 (Not Found) 127.0.0.1/:28 GET http://127.0.0.1:8000/static/js/lightbox.min.js net::ERR_ABORTED 404 (Not Found) 127.0.0.1/:27 GET http://127.0.0.1:8000/static/js/bootstrap.bundle.min.js net::ERR_ABORTED 404 (Not Found) 127.0.0.1/:29 GET http://127.0.0.1:8000/static/js/main.js net::ERR_ABORTED 404 (Not Found) 127.0.0.1/:28 GET http://127.0.0.1:8000/static/js/lightbox.min.js net::ERR_ABORTED 404 (Not Found) 127.0.0.1/:29 GET http://127.0.0.1:8000/static/js/main.js net::ERR_ABORTED 404 (Not Found) Here's some of the code from the settings.py file: DEBUG = True TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] STATIC_ROOT= os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' STATICFILES_DIR =[ os.path.join(BASE_DIR, '/btre/static/') ] Here's the base.html file: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- Font Awesome --> <link rel="stylesheet" href="{% static 'css/all.css' %}"> <!-- Bootstrap --> <link rel="stylesheet" href="{% static 'css/bootstrap.css' … -
RuntimeError: There is no current event loop in thread 'Dummy-2' - Running a Django API with mod_wsgi
I have a Django API connected with mod_wsgi (python3.8) in the Ubuntu-20.4 ec2 instance. When I'm running this using the Public DNS of the Ec2 instance, I'm getting this error. How to resolve this Error: There is no current event loop in thread 'Dummy-2'. Django Version: 3.1.4 Exception Type: RuntimeError Exception Value: There is no current event loop in thread 'Dummy-2'. Exception Location: /usr/lib/python3.8/asyncio/events.py, line 642, in get_event_loop Python Executable: /home/ubuntu/django_project/env/bin/python3 Python Version: 3.8.5 Python Path: ['/home/ubuntu/django_project', '/usr/lib/python38.zip', '/usr/lib/python3.8', '/usr/lib/python3.8/lib-dynload', '/home/ubuntu/django_project/env/lib/python3.8/site-packages'] Server time: Sun, 20 Dec 2020 14:40:28 +0000 Events.py def get_event_loop(self): """Get the event loop for the current context. Returns an instance of EventLoop or raises an exception. """ if (self._local._loop is None and not self._local._set_called and isinstance(threading.current_thread(), threading._MainThread)): self.set_event_loop(self.new_event_loop()) if self._local._loop is None: raise RuntimeError('There is no current event loop in thread %r.' % threading.current_thread().name) return self._local._loop -
django SITE_ID by query
I have a django app. I'm adding a second site. So now I need to set SITE_ID correctly. This is easy enough, except that since it is the primary key id in the Site table, this means the value is dependent on the order in which sites have been added (and, eventually, deleted). That's fragile, without even discussing how developers will sort this if they've done any scratch work in that table. Much better to set it by query. SITE_ID = Site.objects.get(name='my_site_name').id But the settings_myapp.py file, which sets WSGI_APPLICATION, is pretty much the only one that might know which app I'm running. I could try modifying settings in that site-specific settings file, but importing settings at that point leads to an error that SECRET_KEY is not yet defined. Is there a robust way to do this? -
Django Model Form is not saving data to database, but object is created
I'm using a model form and a class based view and I'm trying to save user post model to db. The problem is that UserPost object is created (I've printed it in console and it has all the data and every time when I create new it has new id, so it seems it works) but nothing is saved to database. I'm not sure where the problem might be. Do you have any idea? views.py class CompletePost(View) def get(self, request, *args, **kwargs): post_form=myForms.UploadPostForm() return render(request,'shop/create_post.html',{'post_form':post_form}) def post(self, request, *args, **kwargs): post_form=myForms.UploadPostForm(request.POST) print(request.user.id) if post_form.is_valid(): user_post_v=post_form.save() transaction.commit() models.py class UserPost(models.Model): user_id=models.ForeignKey(Account,on_delete=models.CASCADE) title=models.CharField(max_length=255) text=models.TextField(null=True) category=models.ForeignKey(Category,null=True,on_delete=models.SET_NULL) is_used=models.BooleanField(default=False) price=models.IntegerField(default=0) created_at = models.DateField(auto_now_add=True) updated_at = models.DateField(auto_now=True) is_active = models.BooleanField(default=True) def __unicode__(self): return self.id def get_absolute_url(self,**kwargs): return reverse_lazy('index') -
How to slice items generated from a forloop with conditionals in django
I have a list of products, and I filter through them to get those with a specific category name , how can I slice the resulting items to limit the number shown {% for product in products %} {% if product.category.name == 'specified category' %} <div>{{ product.name }}</div> {% endif %} {% endfor %} -
What is the easiest way to load JSON data from API to Django Template with minimum JavaScript usage
I am looking for the easiest way to load JSON data from API in Django Template without page refresh. I really like to stick with the Django style of Coding and I am new to JavaScript. I have several views in my project that read data from JSON APIs and I am reading them in my views.py and passing the results to templates. Currently, I am refreshing my pages every 10 seconds to show the latest data. But I need to do this without the complete page refresh. Is there any way to achieve this without re-writing everything in JavaScript? If not what is the closest alternative solution? I have read several answers about Ajax calls and also this detailed answer about django-channels. But all of them involve a lot of JavaScript. I would appreciate any suggestion that will make my work easier than these. Below is my example view. (Please note that this is only an example and I have several similar views in my project. That is also the reason why I want to avoid writing custom JavaScript for each view) # views.py import requests class MyView(TemplateView): def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['data'] = requests.get('https://url_to_my_json').json() return context … -
How to create a Django group and assign the group to certain models?
I would like to know how to create groups in django and assign the group to certain models. How can I do this? -
How can i use nested serializer inside the same serializer?
class UserViewSerializer(DynamicFieldsMixin,serializers.ModelSerializer): followers_set = UserViewSerializer(required=False,many=True) class Meta: model = User fields = ('id','email','username','password','followers_set') depth = 2 is there anyway i can use this function without getting this error? followers_set = UserViewSerializer(source='follows',required=False,many=True) NameError: name 'UserViewSerializer' is not defined i tried SerializerMethodField but then i can't use depth option there following_set = serializers.SerializerMethodField() def get_following_set(self, user): return UserViewSerializer(User.objects.filter(follows__author=user), many=True).data using SerializerMethodField gives me error of: RecursionError at /api/users/ maximum recursion depth exceeded Can somebody help me please? -
django channel CancelledError
I'm using the docker to run the django project on server. But, for somehow this error below found after I added new function check_docker_container_status to check the container. This is the error that come from sentry, and I have no error log on my django. But, the problem is for somehow our server also down because this CancelledError. CancelledError: null File "channels/http.py", line 192, in __call__ await self.handle(body_stream) File "asgiref/sync.py", line 304, in __call__ ret = await asyncio.wait_for(future, timeout=None) File "asyncio/tasks.py", line 414, in wait_for return await fut Trying to create the docker ssh connection. from channels.generic.websocket import WebsocketConsumer class DockerSSH(WebsocketConsumer): def connect(self): self.accept() .... try: self.client.inspect_image(full_image_name) except docker.errors.ImageNotFound: pull_docker_image(self.client, full_image_name) container_id, container_is_running = check_docker_container_status(self.client, container_name) def close(self, close_code): logger.debug("### onclose triggered") self.disconnect(1) def disconnect(self, close_code): # Close Thread self.stop_thread = True # Close Socket if self.tls: self.socket.sendall('stop\r\n'.encode('utf-8')) else: self.socket._sock.send('stop\r\n'.encode('utf-8')) logger.debug("### Closing the socket and containers") # socket close self.socket.close() # Clean up the container self.client.stop(self.container_id) self.client.wait(self.container_id) self.client.remove_container(self.container_id) logger.info("## Stopped the container: " + str(self.container_id.encode('utf-8'))) # Close the client connection self.client.close() which is the function of check_docker_container_status is: def check_docker_container_status(client, container_name): # print(dir(client)) """ ['__attrs__', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__enter__', '__eq__', '__exit__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__init__', … -
Configuring Gunicorn with nginx - nginx displaying 500 Internal Server Error when running on port 8000
I'm having issues while setting up nginx and Gunicorn on my local computer (not the server). I have a Django project and I want to be able to access it via http://localhost:8000/. Before my nginx was functional, my Gunicorn server was able to start successfully. However, once I got my nginx server configured, now my Gunicorn server won't start because nginx is already running on my localhost on port 8000. When I visit http://localhost:8000/ I get 500 - Internal Server Error. When I visit http://localhost:80/, however, I get Welcome to nginx! web page. To configure nginx and Gunicorn, I followed this guide, skipping steps 5 to 7 (inclusive). I have to note that in my /etc/nginx the sites-available and sites-enabled directories didn't exist, so I had to make them. I have only two files in my /etc/nginx/sites-available directory - default and mydjangoproject. Both have the same contents and both have their symbolic links in /etc/nginx/sites-enabled. Their contents are: server { listen 8000; server_name 127.0.0.1; location = /favicon.ico { access_log off; log_not_found off; } location /production_static/ { root /home/john/Documents/Django_projects/mydjangoproject/Version_2/mydjangoproject; } location / { proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_pass http://127.0.0.1:8000; } } Here are … -
Generate video requests to a server running at an IP and Port
I have a simple question that can I generate traffic (or not) on a (self-created and accessible) video server that is running on port 8000? I want to generate the traffic for a specific process, not on an IP (what most of the tools provide). So far, I am unable to find any tools that allow us to generate traffic on a specific port. If there is any, please inform me about the options that are available. Actually, I want to observer/analyze the traffic statistics using any monitoring tools. The video server is written in python3 created under Django Framework.