Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Google Login Redirect Url Integrity Error
I have done proper configurations and google login is working correctly. When Google authenticates and redirect user to website it shows this error IntegrityError at /auth/social/google/ null value in column "appointments_enabled" violates not-null constraint DETAIL: Failing row contains (166, 2021-12-23 10:11:01.370877+00, 2021-12-23 10:11:01.370907+00, f, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 166, null, null, null, null, null). Request Method: POST Request URL: http://cozmo.gvmtechnologies.com:8000/auth/social/google/ Django Version: 2.0.9 Python Executable: /root/.local/share/virtualenvs/cozmo-FEPF8JuT/bin/python Python Version: 3.6.15 Python Path: ['/root/cozmo-server-develop/cozmo', '/usr/lib/python36.zip', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', '/root/.local/share/virtualenvs/cozmo-FEPF8JuT/lib/python3.6/site-packages', '/root/cozmo-server-develop/cozmo'] Server time: Thu, 23 Dec 2021 10:11:01 +0000 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.messages', 'django.contrib.sessions', 'django.contrib.staticfiles', 'django.contrib.sites', 'django.contrib.postgres', 'guardian', 'storages', 'rest_framework', 'rest_framework_swagger', 'rest_framework_tracking', 'rest_framework_jwt', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', 'rest_auth', 'rest_auth.registration', 'cozmo_common.apps.CozmoCommonConfig', 'accounts.apps.AccountsConfig', 'automation.apps.AutomationConfig', 'accounts.profile.apps.ProfileConfig', 'app_marketplace.apps.AppMarketplaceConfig', 'crm.apps.CrmConfig', 'listings.apps.ListingsConfig', 'events.apps.EventsConfig', 'listings.calendars.apps.CalendarsConfig', 'notifications.apps.NotificationsConfig', 'owners.apps.OwnersConfig', 'pois.apps.PoisConfig', 'payments.apps.PaymentsConfig', 'public_api.apps.PublicApiConfig', 'message_templates.apps.MessageTemplatesConfig', 'rental_connections.apps.RentalConnectionsConfig', 'rental_integrations.apps.RentalIntegrationsConfig', 'rental_integrations.airbnb.apps.AirbnbConfig', 'rental_integrations.booking.apps.BookingConfig', 'rental_integrations.expedia.apps.ExpediaConfig', 'rental_integrations.homeaway.apps.HomeawayConfig', 'rental_integrations.trip_advisor.apps.TripAdvisorConfig', 'send_mail.apps.SendMailConfig', 'search.apps.SearchConfig', 'vendors.apps.VendorsConfig', 'send_mail.phone.apps.PhoneConfig', 'services.apps.ServicesConfig', 'chat.apps.ChatConfig', 'settings.apps.SettingsConfig', 'rental_network.apps.RentalNetworkConfig', 'dashboard.apps.DashboardConfig', 'pricing.apps.PricingConfig', 'behave_django', 'corsheaders', 'internal.apps.InternalConfig'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.contrib.messages.middleware.MessageMiddleware'] Exception Type: IntegrityError at /auth/social/google/ Exception Value: null value in column "appointments_enabled" violates not-null constraint DETAIL: Failing row contains (166, 2021-12-23 10:11:01.370877+00, 2021-12-23 10:11:01.370907+00, f, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, … -
ModuleNotFoundError: No module named 'django.utils'
Hi am getting these error ...do we know how to fix Traceback (most recent call last): File "manage.py", line 11, in main from django.core.management import execute_from_command_line File "/mnt/c/Users/krammurti/counselcareer/venv/lib/python3.8/site-packages/django/init.py", line 1, in from django.utils.version import get_version ModuleNotFoundError: No module named 'django.utils' -
How to display files by only its name
[![enter image description here][1]][1] [1]: https://i.stack.imgur.com/sjO7r.jpg Here i want to display only the file name i.e sample.pdf. I use postgresql as database ,django rest for backend and angular as frontend. If you want other code ask me i will share -
KeyError: 'password'
There's frontend on react and backend on Django, on registering user, got an issue with password field,like ** KeyError 'password'**, the code is below. serializer.py ... class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = '__all__' ... views.py ... from.django.contrib.auth.hashers import make_password ... @api_view(['POST']) def userRegister(request): data = request.user user = User.objects.create( email = data['email'] password = make_password(data['password']) serializer = UserSerializer (user, many=False) return Response (serializer.data) ... -
User form foreignkeyfield form not valid
I was creating a post based website i want to show the author's name to show up in the post it works in the admin site when adding posts but when i try uploading a post from the site the form is not getting validated therefore it is not getting saved please help model : from django.conf import settings class MemeImg(models.Model): Title = models.CharField(max_length=500) op = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default=None, blank=True, null=True) date_created = models.DateTimeField(auto_now_add=True) Post_Img = CloudinaryField('Post') forms : class PostImg(forms.ModelForm): class Meta: model = MemeImg fields = ['Title', 'op', 'Post_Img'] view : @login_required(login_url='/login') def post(request): func = data(request) if request.method == 'POST': form = PostImg(request.POST, request.FILES, instance=request.user) form.op = request.user if form.is_valid(): print('success') posts = form.save(commit=False) posts.op = request.user form.save() return HttpResponseRedirect('https://youtu.be/dQw4w9WgXcQ') else: print("fail") form = PostImg(request) ctx = { 'form': form, 'url': func[0], 'name': func[1], 'date': func[2], } return render(request, 'Post.html', ctx) and finally the post page template : <form method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="container"> {{ form.Title|materializecss }} <div class="file-field input-field"> <div class="btn"> <span>File</span> <input type="file"> </div> <div class="file-path-wrapper"> {{ form.Post_Img }} <input class="file-path validate" type="text"> </div> </div> <button class="btn waves-effect waves-light" type="submit" name="action">Submit <i class="material-icons right">send</i> </button> </div> </form> If anymore code is required please … -
How to retrieve data from MySQL database in Django and display it in html page?
I am trying to add data from MySQL database and display it in a html page using python. Here is my view.py: def show(request): data = Persons.objects.all() person = { "Persons": data } return render(request, "home.html", person) models.py: class Persons(models.Model): PersonID = models.IntegerField() LastName = models.CharField(max_length=100) FirstName = models.CharField(max_length=100) Address = models.CharField(max_length=100) City = models.CharField(max_length=100) class Meta: db_table = "persons" html: <div> <div class="numbers">Graph</div> {% for item in Person %} {{ item.LastName }} {% endfor %} </div> But I didnot retrieve anything. Any help will be highly appreciated. -
Google Cloud App Engine (Django) and Google Cloud Storage working on a Single Domain with Custom URLs
I have a Django application working on supereye.co.uk. Django handles all URL routing such as supereye.co.uk/signin supereye.co.uk/watch etc. I am also using Google Cloud Storage that is working with Google Cloud App Engine on gs://production2.supereye.co.uk How shall I handle the routing so both App Engine and Storage can be accessible through the supereye.co.uk domain. For instance : supereye.co.uk -> Django App, Google Cloud App Engine data.supereye.co.uk -> Google Cloud Storage bucket, gs://production2.supereye.co.uk Is there any way to achieve this without relating Django App to bucket at all ? Can the bucket be accessible by its own resources? Is there any internal Google Cloud tool that will let me achieve this ? -
Best way to handle articles with Django
I'm looking for the best possible way to manage articles in Django. My idea was to load the articles as static files (there's no upload from users, so no form necessary, I guess), then create the model, but which field type to use here ? Textfield or FilePathField (in the static ?) or something else ? Then create the view and render it. The articles will be showned as cards with a summary on the index page, and each card will point to the full article page. If someone would point me in the right direction, I would appreciate. I'm checking the docs since yesterday, I might have missed the relevant part. -
Add custom admin actions to django irrelevant to objects
I want to add admin actions (for example with buttons) to django admin site that are irrelevant to particular model, for example doing administrative tasks such as optimizing database or clearing cache or log files or deleting records from multiple tables... I have seen django admin action without selecting objects, but the answers seems tricky and the solutions was selecting objects of particular model, in other ways. Is there a better to add this functionality to admin site anyway? -
How Django works with Mongodb
I need to make a Django restful api. I have a volume of data that is distributed in a tree structure with 3 attachments. I want to implement this nesting in Mongo: base->collection->object. The objects are generally the same so I don't really want to prescribe millions of models. I can draw an analogy with library: hall->stack->book. Each shelf has different books on it, but all of them are made of paper and covers. I found how to work with different databases and how to send the model to a certain database: 'default': { 'ENGINE': 'djongo', 'NAME': 'some_name', 'CLIENT': { { "host": "mongodb://.........../", } }, { "user": { 'ENGINE': 'djongo', 'NAME': 'some_name2', 'CLIENT': { { "host": "mongodb://......../", } } And accessing different databases Author.objects.using('other').all(). How to relate one model to one collection I found too: class MongoMeta: db_table = "some_collection_name" But how to combine all this I can't find. That one model can belong to different databases to different collections while being one single. -
Cannot connect to websocket by unicorn and uwsgi
I have tried the following 6 methods to start my django project. 1. command=python3 manage.py 2. command=daphne myproject.asgi:application -b 0.0.0.0 -p 778 3. command=uwsgi --ini /root/uwsgi.ini 4. command=uvicorn myproject.asgi:application --workers 4 --host 0.0.0.0 --port 778 5. command=gunicorn myproject.wsgi --workers 2 --bind 0.0.0.0:778 6. command=gunicorn myproject.asgi:application -k uvicorn.workers.UvicornWorker -b 0.0.0.0:778 However, only the first two methods are able to connect to websocket. Unfortunately, there is not two much error details left in my client(Only know the error code is 1006). Anyone knows why I cannot connect? -
Django - getting user input from HTML file (jQuery post, get) printed in console
I'm trying to get the user input printed in terminal by using jQuery, but for some reason I'm not getting it. On /aktoriai/ there's a form that requires a movie title to be entered and when I enter it, nothing get printed. When loading up the page, "get" is being printed and after clicking the button, "post" is being printed. HTML snippet: <script src="https://code.jquery.com/jquery-3.5.0.js"></script> <script> // Attach a submit handler to the form $( "#searchForm" ).submit(function( event ) { // Get some values from elements on the page: var $form = $( this ), term = $form.find( "input[name='movie_title']" ).val(), url = $form.attr( "aktoriai" ); // Send the data using post var posting = $.post( url, { s: term } ); }); </script> <form method="post"> <label for="movie_title">Filmo pavadinimas: </label> <input type="text" name="movie_title"> <input type="submit" value="OK"> </form> views: @csrf_exempt def aktoriai(request): # print(request.GET) if request.method == "GET": print("get") print(request.get['movie_title']) objects = Filmlist.objects.none() # # return render(request, "aktoriai.html", context={'objects': objects}) return render(request, "aktoriai.html", context={'objects': objects}) if request.method == "POST": print("post") objects = Filmlist.objects.none() # return render(request, "aktoriai.html", context={'objects': objects}) return render(request, "aktoriai.html", context={'objects': objects}) -
How to post foreign key id only once in Django
class Department(models.Model): name = models.CharField(max_length=50) class Employee(models.Model): name = models.CharField(max_length=100) age = models.IntegerField() department = models.ForeignKey(Department, on_delete=models.CASCADE) I'm really wondering how to do this. Suppose there are three departments with id 1, 2, 3. So in employee model if i posted some employee with name abc and department 1. So next time if i will try to post the same department id that is 1 for another employee. I should not be able to do that. Validating this field does not work i believe because of foreign key.So how to achieve this. Any help would be really appreciated. Thank you !! -
I/O time differing on docker containers
I am running this script to test I/O performances on my docker containers. from tempfile import NamedTemporaryFile d = 500 n = 100000 with NamedTemporaryFile() as f: for i in range(n): nums = [] for j in range(d): nums.append(str(round(random.uniform(0, 1000), 3))) s = ' '.join(nums) f.write(s.encode()) f.write('\n'.encode()) Strange thing is execution time differs depending of containers On container 1 : 65.96740865707397 seconds On container 2 : 71.00589632987976 seconds The only thing differing between these 2 containers is the command docker executes : Container 1 command is : ./manage.py runserver 0.0.0.0:80 (this is django) Container 2 command is : python3 manage.py rqworker my_queue (this is django_rq) Do you have any idea why I have such a difference of 5 seconds ? Or do you know where could I investigate ? -
HOW DO I AVOID DUPLICATE ENTRIES WHILE TAKING DATA FROM AN API IN DJANGO MODELS
from home.models import suppotors for i in items: if i['status'] != "failed": ins = suppotors(name=i['notes']['name'] , amount = i['amount']) ins.save() return True "SUPPOTORS" is a model that im using and "ITEMS" is the data im getting from the api , when ever i reload the page django saves the of items in the suppotors model HOW DO I AVOID DUPLICATE ENTRIES? -
Different upload and download urls for Django Models's Image Field
I need a way to have different upload and download URLs for ImageField. I want to upload the image to AWS S3 and while accessing the image I want the image to route through CDN (in my case Fastly). def get_avatar_upload_path(identity, filename): file_ext = filename.split('.')[-1] file_name = f'{uuid.uuid4()}.{file_ext}' return f'{settings.AWS_MEDIA_PREFIX}{identity.uuid}/{file_name}' class Identity(identity_revision_base): """ Identity model. Ties a user to a chat identity. """ badges = models.ManyToManyField(Badge, blank=True) key = models.UUIDField(_("key"), unique=True, default=uuid.uuid4) uuid = models.UUIDField(_("UUID"), unique=True, default=uuid.uuid4) avatar = models.ImageField(upload_to=get_avatar_upload_path, blank=True) user = models.ForeignKey( to=settings.AUTH_USER_MODEL, blank=True, null=True, on_delete=models.SET_NULL, related_name="+", ) Just like I am specifying upload path in ImageField, I would like a way to do something similar for accessing Image. It also seems that I cannot modify avatar.url once it is created. Is there any way around? -
TypeError while testing answer checker
I'm writing a test for my "answer checker", so I made a test question and I want to test if the result checker works by giving the right answer (so the test should pass). I'm in some trouble with the error that I got back. I know the code it's not that good, but I'm new in this field. I think I've misunderstood something in the logic. Can anybody help? :) Error is: correct = QuestionMultipleChoice.correct_answer() TypeError: 'property' object is not callable Test (the last lines are wrong I know): @when(u'I give an answer to a Multiple choice question') def save_object(context): lab1 = Lab.objects.create(lab_name="testlab", pub_date=datetime.now(), lab_theory="test theory") question1 = QuestionMultipleChoice.objects.create(lab=lab1, question='This is a test question', option1='1', option2='2', option3='3', option4='4', answer=1) @then(u'I should get true if answer is correct') def should_have_only_one_object(self): given = 1 correct = QuestionMultipleChoice.correct_answer() QuestionMultipleChoice.check_answer(correct, given) assert 1 == Lab.objects.count() Models.py class QuestionMultipleChoice(models.Model): lab = models.ForeignKey(Lab, on_delete=models.CASCADE) type = QuestionType.multiplechoice question = models.CharField(max_length=200,null=True) option1 = models.CharField(max_length=200,null=True) option2 = models.CharField(max_length=200,null=True) option3 = models.CharField(max_length=200,null=True) option4 = models.CharField(max_length=200,null=True) answer = models.IntegerField(max_length=200,null=True) def __str__(self): return self.question @property def html_name(self): return "q_mc_{}".format(self.pk) @property def correct_answer(self): correct_answer_number = int(self.answer) correct_answer = getattr(self, "option{}".format(correct_answer_number)) return correct_answer def check_answer(self, given): return self.correct_answer == given -
Convert a timestamp to a DateTime field?
I've got a DateTimeField(auto_now_add=True) in my model. However, I wish to update this field, and the format I'm receiving from my API is a UNIX timestamp. Can I somehow convert the format I receive from my API to the correct one? (eg 1640206232 to 2021-12-22 20:50:32). Using postgres as my db if that matters.. -
I have extended a AbstractUser model. But I'm not able to login with username & password
I am creating an API for signup. Based on signup username & password I need to perform login. But it say user not found. Model.py class User(AbstractUser): """This Class is used to extend the in-build user model """ ROLE_CHOICES = (('CREATOR','CREATOR'),('MODERATOR','MODERATOR'),('USERS','USERS')) GENDER_CHOICES = (('MALE','MALE'),('FEMALE',"FEMALE"),('OTHER','OTHER')) date_of_birth = models.DateField(max_length=10, verbose_name='Date of Birth', null=True) profile_image = models.ImageField(upload_to='profile_images', verbose_name='Profile Image', default='images/default.webp', blank=True) bio = models.TextField(verbose_name='Bio') role = models.CharField(max_length=10, verbose_name='Role', choices=ROLE_CHOICES) gender = models.CharField(max_length=6, verbose_name='Gender', choices=GENDER_CHOICES) serializers.py class LoginSerializer(serializers.ModelSerializer): username = serializers.CharField(max_length=25) password = serializers.CharField(max_length=25) class Meta: model = User fields = ('username','password') def validate(self, **kwargs): username = self.validated_data.get("username", None) password = self.validated_data.get("password", None) print(username) print(password) user = authenticate(username=username, password=password) print(user) if user is None: raise serializers.ValidationError('User Not Found') else: return Response({'username':'ronaldo'}) views.py class UserLoginAPI(viewsets.ModelViewSet): serializer_class = LoginSerializer queryset = User.objects.all() def post(self, request): serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) response = { 'success':'True', 'status_code':status.HTTP_200_OK, 'message':'Login Successfully', } status_code = status.HTTP_200_OK return Response(response, status=status_code) I think i'm doing it in wrong way. As i'm using OAuth2 toolkit to generate token. So please help AttributeError: 'NoneType' object has no attribute '_meta' -
How to execute function as a json in python?
I'm a beginner and now I'm trying to do something with django and data science. My project is to rate salesmen for their service and I want to do some magic with data science.)) (showing average ratings of salesmen and etc.) For now, I have this function: def average_values(): average_values_in_json = [] data = json_maker() df = pd.read_json(data) df = df.set_index('id') salesman_group = df.groupby(['salesperson']) for person in df['salesperson'].unique(): salesperson = salesman_group.get_group(f"{person}").mean() data = { "salesperson": person, "average": salesperson['rating'] } average_values_in_json.append(data) average_values_in_json = json.dumps(average_values_in_json) return average_values_in_json It works nice, I rendered it properly and now I want to represent graph with matplotlib. In my views.py, I have: def graph_show(request): new_data = average_values() x = [new_data[i]['salesperson'] for i in range(len(new_data))] y = [new_data[i]['average'] for i in range(len(new_data))] chart = get_plot(x,y) return render(request, 'report/graph.html', {'x': x, 'y': y}) The problem is that new_data takes string type of the return of function. But I need a json object in order to my further codes work properly. What kind of advice would you give? -
AttributeError: module 'django.db.migrations' has no attribute 'RunPython'
I get this error whenever I try running my server, migrating, or running any Django commands. All my previous Django projects also show the same error, but they were working fine before. I tried updating Django, but it's still showing the same error. This is the error I am getting. Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Python310\lib\threading.py", line 1010, in _bootstrap_inner self.run() File "C:\Python310\lib\threading.py", line 947, in run self._target(*self._args, **self._kwargs) File "C:\Python310\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Python310\lib\site-packages\django\core\management\commands\runserver.py", line 115, in inner_run autoreload.raise_last_exception() File "C:\Python310\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\Python310\lib\site-packages\django\core\management\__init__.py", line 381, in execute autoreload.check_errors(django.setup)() File "C:\Python310\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Python310\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Python310\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Python310\lib\site-packages\django\apps\config.py", line 123, in create mod = import_module(mod_path) File "C:\Python310\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "C:\Python310\lib\site-packages\django\contrib\auth\apps.py", line 8, in … -
django-q task manager is not working correctly if there is no request in system
Anyone using django-q task scheduler: https://github.com/Koed00/django-q (Not the database related Q library) I'm scheduling cron task which will trigger some jobs. But my main problem is, tasks starts working 30-60 mins later than i scheduled if there is no new request in server. After lots time when i refresh page , it's starts running immediately. Even i set timeout low to try if it's gonna work but it didn't. Is there any conf that i can set for this issue ? Q_CLUSTER = { "name": "Cluster", "orm": "default", # Use Django's ORM + database for broker 'workers': 2, 'timeout': 240, 'retry': 300, } -
Getting "IntegrityError FOREIGN KEY constraint failed" when i am trying to generate the invoice from booking table
I am trying to generate an invoice from the booking table. I have created a separate table for invoices and declared a foreign key for the booking table and package too. But whenever I try to generate an invoice it gives a Foreign key constraint. Here is my models file models.py class Invoice(models.Model): photographer = models.ForeignKey(Photographer,on_delete=models.CASCADE) package = models.ForeignKey(Package,on_delete=models.CASCADE) booking = models.ForeignKey(Booking,on_delete=models.CASCADE) extra_amt = models.IntegerField(null=True,blank=True) total_amt = models.IntegerField(null=True,blank=True) payment_status = models.CharField(max_length=100) created_at = models.DateField(auto_now_add=True) updated_at = models.DateField(auto_now=True) Here is the view that I created to generate invoice views.py def generate_invoice(request,id): photographer = Photographer.objects.get(user=request.user) booking = Booking.objects.get(id=id) packages = Package.objects.filter(photographer=photographer) if request.method == "POST": package_get = request.POST.get('package') extra_amt = request.POST.get('extra_amt') payment_status = request.POST.get('payment_status') invoice = Invoice( photographer = photographer, booking = booking, package_id = package_get, extra_amt = extra_amt, payment_status = payment_status, ) invoice.save() messages.success(request,'Invoice generated Successfully') return redirect('view_booking') context = { 'package':packages, } return render(request,'customadmin/photographer/generate_invoice.html',context) When I click on submit button to generate url it shows below error on this url http://localhost:8000/customadmin/bookings/generate-invoice/5/ IntegrityError at /customadmin/bookings/generate-invoice/5/ FOREIGN KEY constraint failed Request Method: POST Request URL: http://localhost:8000/customadmin/bookings/generate-invoice/5/ Django Version: 4.0 Exception Type: IntegrityError Exception Value: FOREIGN KEY constraint failed Exception Location: /home/shreyas/project/mainPhotographer/venv/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py, line 416, in execute Python Executable: /home/shreyas/project/mainPhotographer/venv/bin/python Python Version: 3.8.10 Python … -
Collectstatic fails with Django 4.0 [duplicate]
I am unable to run python manage.py collectstatic with Django 4.0. Error is ....min.js references a file which could not be found .....min.js.map I believe this is due to Django 4.0 collectstatic having added manifest_storage: https://docs.djangoproject.com/en/4.0/ref/contrib/staticfiles/ This leads to error. I try to disable this by WHITENOISE_MANIFEST_STRICT = False but this does not have any affect. I run site on Heroku so I have django_heroku.settings(locals()) at end of settings.py file. Tried to fix this by adding an empty file with touch to location indicated in error message. Error is gone, but next .map-file is missing. No sense to manually fix. The question - how to disable finding .map -files in manage.py collectstatic in Heroku-setup? -
How to close a socket and open it again in tornado
I have a tornado websocket class WSHandler(tornado.websocket.WebSocketHandler): def open(self): print ('new connection') global hr_values_list hr_values_list=[] def on_message(self, message): value=getvalue(message) if value: self.write_message(json_encode(int(value))) hr_values_list.append(value) def on_close(self): avg=int(np.mean(hr_values_list)) print ('connection closed',len(hr_values_list),avg) def check_origin(self, origin): return True application = tornado.web.Application([ (r'/websocket', WSHandler), ]) First i want to write value to browser console or page, when on_close action is taken . Like is there a way write_message as in on_message function. Second, i want to open the connection again after connection is closed function defsocket(){ var socket = new WebSocket('ws://localhost:8888/websocket'); return socket; }; socket= defsocket(); $(document).ready(function () { let video = document.getElementById('video'); let canvas = document.getElementById('canvas'); let context = canvas.getContext('2d'); let draw_canvas = document.getElementById('detect-data'); let draw_context = draw_canvas.getContext('2d'); let image = new Image(); if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) { navigator.mediaDevices.getUserMedia({video: true}).then(function (stream) { video.srcObject = stream; video.play(); }); } function drawCanvas() { context.drawImage(video, 0, 0, 500, 350); sendMessage(canvas.toDataURL('image/png')); } document.getElementById("start-stream").addEventListener("click", function () { drawCanvas(); }); document.getElementById("stop-stream").addEventListener("click", function () { socketClose(); }); function sendMessage(message) { socket.send(message); } function socketClose() { socket.close(); } socket.onmessage = function (e) { console.log(e) document.getElementById("pid").innerHTML = e.data; drawCanvas(); }; }) So what i want is that when i click on start-stream, connection start and value start displaying in html page. This is …