Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why is Django is not loading my template view but it once was
My view was running fine until Ill tried to override an admin view. Which i eventually got to work. However in the process I broke the path to my view that was working. The admin view had nothing to do with my originally working view. Now I copied my view into every possible level of my project structure. Yet the django template loader fails to find my order_input.html The error shows the correct path to my order_input.html. I made copies of order_input.html at every single possible level of my project... but django still cant find it. APP - URLS.PY from django.conf.urls import url from . import views urlpatterns = [ url(r'^hw/$', views.helloworld, name='helloworld'), url(r'^order_input/$', views.order_input, name='order_input'), url(r'^time/$', views.today_is, name='time'), url(r'^$', views.index, name='index'), ] SETTINGS.PY # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', # 'django.contrib.staticfiles', 'import_export', 'hw_app', ] PROJECT URLS.PY urlpatterns = [ url('r', include('hw_app.urls')), url('admin/', admin.site.urls), path('clearfile', views.clearfile), path('readfile', views.readfile), path('writefile', views.writefile), path('helloworld', views.helloworld), path('order_input', views.order_input), path('ajax_view', views.ajax_view), ] -
How do I use start-app template context in a template file?
I have the current setup for a Django app template which I pass to start-app like so: python3 manage.py start-app --template template/ myapp With a directory structure like this: template/ templates/app_name/ page.html ... app.py app.py uses the template context passed when start-app is run, and works fine! # app.py from django.apps import AppConfig class {{ camel_case_app_name }}Config(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = '{{ app_name }}' However, I'm trying to get similar behaviour out of page.html, to no avail. {% extends "{{ app_name }}/otherpage.html" %} {% block content %} <p>Hello from {{ camel_case_app_name }}!</p> {% endblock %} If I run start-app like normal, the template is copied over and the app name is not inserted. If I try to run start-app with --extension py,html I don't get the expected behaviour either, because the template is rendered. Is there a way to convert the {{ app_name }} calls in page.html without attempting to render the entire template? -
Django Admin filter_horizontal using wrong primary key and causing constraint violation
Here is the related models: Service order Item: class ServiceOrderItem(models.Model): id = models.AutoField(primary_key=True, verbose_name="ServiceOrderItem ID") service_order = models.ForeignKey(ServiceOrder, on_delete=models.RESTRICT) service = models.IntegerField(choices=settings.SERVICE_TYPE_CHOICES) notes = models.TextField(blank=True) in_service_date = models.DateTimeField(null=True, blank=True, default=None) cost = models.FloatField() term = models.IntegerField() active = models.BooleanField(default=True) leases = models.ManyToManyField( to="Location", symmetrical=True, null=True, blank=True, default=None, ) def __str__(self): return f"Item {self.pk} in Service Order {self.service_order.pk}" Location: class Location(models.Model): uuid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) common_name = models.CharField(max_length=200, verbose_name="Location") parent_location = models.ForeignKey("self", blank=True, on_delete=models.RESTRICT, null=True, default=None) used_slots = models.IntegerField(default=1) slot_index = models.IntegerField(default=1) company = models.ForeignKey(Company, on_delete=models.RESTRICT) location_type = models.IntegerField(choices=settings.LOCATION_CHOICES) city = models.ForeignKey(City, on_delete=models.RESTRICT, null=True, blank=True) county = models.ForeignKey(County, on_delete=models.RESTRICT, null=True, blank=True) address_line = models.CharField(max_length=200, blank=True) location_point = models.PointField(default=None, null=True, blank=True) zipcode = models.CharField(max_length=30, blank=True) def __str__(self): return f"{self.get_full_location()}" def get_description_for_admin(self): if self.county is not None: return f"{self.city.name}, {self.county.state.name}" elif self.parent_location is not None: return self.parent_location.get_description_for_admin() else: return None def get_description_for_device(self): result = "" if self.location_type in (8, 6, 5): result = f"{self.parent_location.get_description_for_device()}{self.common_name}" elif self.location_type in (1, 9) or (self.location_type == 2 and self.city is not None): result = f"{self.county.state.abbreviation}-{self.city.name}-" else: if self.parent_location is not None: result = self.parent_location.get_description_for_device() return result def get_full_location(self): result = f"{self.common_name}" if self.parent_location is not None: result = f"{self.parent_location.get_full_location()}-{result}" return result admin item: class ServiceOrderItemAdmin(admin.ModelAdmin): list_display … -
Django synchronous function: wait for one session to finishing using function
In my django server, I have a function that handles a request from a user. When multiple users are sending requests from within their respective sessions at the same time, the function processes the requests within their own sessions so it happens in parallel. But I want to ensure that when I have multiple requests from multiple users, they are handled one by one rather than simultaneously. Basically, I don't want this function to be a session instance but a global function that only one user can use at a time. How can I solve this problem? This is an open-ended question so as long as we are using Django in the implementation I don't have any more constraints. -
settings.DATABASES is improperly configured. Please supply the NAME or OPTIONS['service'] value
i develop an app on heroku server when i finishing setting up my AWS RDS POSTGRESQL and run my migrations and migrate successeful without any error. its throws me an error. the error settings.DATABASES is improperly configured. Please supply the NAME or OPTIONS['service'] value. i did'nt run heroku run python manage.py migrate which i think is not the problem. I'm using heroku server and i setup everything its needs for aws rds for postgresql. i get this error in production server not on localhost, because its working perfect on localhost. Database configurations in settings.py file DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': '', 'USER': '', 'PASSWORD': '', 'HOST': '', 'PORT': '5432', } } is anybody who face the same problem before me please. Thanks -
Error: the following arguments are required: new (How to Build an E-commerce Website with Django and Python)
I am trying to start this tutorial... I had to pip install a few packages and adjust requirements.txt a bit. Now, I'm trying to rename the project and I am getting an error "manage.py rename: error: the following arguments are required: new". Any help will be much appreciated. https://www.youtube.com/watch?v=YZvRrldjf1Y&t=1485s&ab_channel=freeCodeCamp.org import os from django.core.management.base import BaseCommand class Command(BaseCommand): help = 'Renames a Django project' def add_arguments(self, parser): parser.add_argument('current', type=str, nargs='+', help='The current Django project folder name') parser.add_argument('new', type=str, nargs='+', help='The new Django project name') def handle(self, *args, **kwargs): current_project_name = kwargs['current'][0] new_project_name = kwargs['new'][0] # logic for renaming the files files_to_rename = [f'{current_project_name}/settings/base.py', f'{current_project_name}/wsgi.py', 'manage.py'] for f in files_to_rename: with open(f, 'r') as file: filedata = file.read() filedata = filedata.replace(current_project_name, new_project_name) with open(f, 'w') as file: file.write(filedata) os.rename(current_project_name, new_project_name) self.stdout.write(self.style.SUCCESS( 'Project has been renamed to %s' % new_project_name)) -
use pytesseract with Django
i want to do text recon from image with Django and Pytesseract what i want is that, a user should upload a picture from the browser and press on a button so that the choosen image should be turned into text.. i have tried this function in a single file: import pytesseract pytesseract.pytesseract.tesseract.cmd = r"C:Program files\Tesseract-OCR\tesseract.exe" def ocr_core(filename) text = pytesseract.image_to_string(filename) return text #test the function on an image in images folder print(ocr_core('images/test4.jpeg')) this work fine in the terminal. but now i want to use this function in My django view file by calling the file where the function is written or by doing it directly in the view.. pls i don't know if my explanation is good..if yes, pls i need help -
Django-cart object always empty
I am developing ecommerce web application using Django. After I have implemented a footer, pagination and a search bar, "Add to cart" button stopped working. My only guess was that there was a cache issue, therefore I have added @never_cache decorator above the cart/checkout views however, the button still did not work and while inspecting, the cart object is empty even after pressing the button. I am not sure what is the reason behind it. main.html In this template I have written JS logic for cart, nav bar and a search bar. <!DOCTYPE html> {% load static %} <html lang="en"> <head> <title>Eshop</title> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1" /> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <link rel="stylesheet" type="text/css" href="{% static 'css/main.css' %}"> <script type="text/javascript"> var user = '{{request.user}}' function getToken(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } var csrftoken = getToken('csrftoken'); function getCookie(name) { // … -
Django Rest custom serialize field
My models.py is as follows: class ExampleClass(models.Model): TYPES = ( (0, "Amount"), (1, "Value"), ) type = models.IntegerField(choices=TYPES, default=0) type_value = models.FloatField() and I want to serialize it to looks like that: "example": { "Amount": 10.0 # "type": type_value } How can I get this custom serialisation? -
TemplateSyntaxError at / 'for' statements should use the format 'for x in y'
I am trying to run a concurrent loop in my index.html file, however i am getting this error: TemplateSyntaxError at / 'for' statements should use the format 'for x in y': for i, n in zip(images, toi_news) Here's my html code : <div class="col-6"> <center><i><u><h3 class="text-centre">Live News from The Toronto Star</h3></u></i></center> {% for i, n in zip(images, toi_news) %} <strong><h5>{{n}}</h5></strong> <img src="{{i}}"> <hr> {% endfor %} <br> </div> Anyone know how to correct this issue? -
How to change display value for one to one field in django admin?
I'm looking to change the display value for a one to one field in the django admin dashboard. I want to prefix the user's name to the one to one field. I'm able to successfully do it for a foreign key like this: def formfield_for_foreignkey(self, db_field, request, **kwargs): if db_field.name == 'audio_module': return AudioModuleChoiceField( queryset=AudioModule.objects.filter(is_deleted=False).order_by('user__last_name') ) return super().formfield_for_foreignkey(db_field, request, **kwargs) However, I don't see any options in the docs to override a formfield_for_onetoone. Currently, my form field looks like this: audio_module has a FK to my user table. Like I said above, I'd like to prefix the user's name in front of the audio module in the dropdown so it'll be easier to identify audio modules for specific users. i.e. John Doe - audio module 2 How do I achieve this? -
Django Crontab keeps stating module not found
Every time I try to run python manage.py crontab add or run my testing script I get this: File "/usr/local/lib/python3.10/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 1004, in _find_and_load_unlocked ModuleNotFoundError: No module named 'django_crontab' Settings: INSTALLED_APPS = [ 'django_crontab', 'rest_framework', 'prices.apps.PricesConfig', 'meters.apps.MetersConfig', 'devices.apps.DevicesConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'website', 'accounts', ] . . . CRONJOBS = [ ('0 22 * * *', 'website.cron.delete_old_registration') ] . . . cron.py: import datetime from .models import Register def delete_old_registration(): today = datetime.date.today() filter_old_date = today - datetime.timedelta(days=14) registrations_old = Register.objects.filter(date__lte=filter_old_date) registrations_old.delete() Banging my head here cause I've reinstall django-crontab and followed the instructions multiple times. -
eb deploy error - chown /var/app/staging/venv/bin/python: no such file or directory
Following AWS instructions for (https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html) Currently trying to run "eb deploy" with the following output: Creating application version archive "app-220413_141345835306". Uploading: [##################################################] 100% Done... 2022-04-13 20:14:00 INFO Environment update is starting. 2022-04-13 20:14:05 INFO Deploying new version to instance(s). 2022-04-13 20:14:09 ERROR Instance deployment failed. For details, see 'eb-engine.log'. 2022-04-13 20:14:11 ERROR [Instance: i-0fb1ab203cc59f0d1] Command failed on instance. Return code: 1 Output: Engine execution has encountered an error.. 2022-04-13 20:14:11 INFO Command execution completed on all instances. Summary: [Successful: 0, Failed: 1]. 2022-04-13 20:14:11 ERROR Unsuccessful command execution on instance id(s) 'i-0fb1ab203cc59f0d1'. Aborting the operation. 2022-04-13 20:14:11 ERROR Failed to deploy application. ERROR: ServiceError - Failed to deploy application. In the logs I see: 2022/04/13 20:00:19.230141 [INFO] finished extracting /opt/elasticbeanstalk/deployment/app_source_bundle to /var/app/staging/ successfully 2022/04/13 20:00:19.231105 [ERROR] An error occurred during execution of command [app-deploy] - [StageApplication]. Stop running the command. Erro r: chown /var/app/staging/venv/bin/python: no such file or directory Any ideas what to do? I have no idea where that path is coming from -
Exclude many to many results from Queryset in Django
I have 3 models and I'm trying to exclude certain things in a query, but am struggling to do so because the many-to-many is returning None and it's breaking the exclude portion of the query. My models: class Camp(models.Model): name = models.CharField(max_length=100) description = models.CharField(max_length=200, blank=True, null=True) class RelatedCamps(models.Model): name = models.CharField(max_length=50, null=True, blank=True) camps = models.ManyToManyField(Camp, related_name="related_camps") class CourseDetail(models.Model): camp = models.ForeignKey(Camp, on_delete=models.PROTECT) ...other attributes... I am trying to limit the CourseDetails that I'm getting back like so: # Get CourseDetails (this is well tested and works to return appropriate models) initial_course_details = get_available_course_details(student_id) # Get the camp_ids to check for 'related camps' course_detail_camp_ids = initial_course_details.values_list( "camp__id", flat=True ) # Get the related_camp ids, so we can remove all of those from the total list related_camp_ids = initial_course_details.values_list( "camp__related_camps__camps", flat=True ) # get the course_details, but remove the 'related_camp_ids' course_detail_camp_ids = course_detail_camp_ids.exclude(camp__in=related_camp_ids) This works if there are related_camps. But in some cases it doesn't work because the 'related_camp_ids' returns a list like this: [1, 2, None] When a list with None in it comes back - the .exclude() does not work properly and the course_detail_camp_ids list becomes empty. Is doing something like this the most 'django' way? related_camp_ids = … -
How to fetch specific item first in template and then fetch other?
In django template I am looping model on following way: {% for image in image%} {{image.image.url}} {% endfor %} Here I want to get the image where, image model has featured_image Boolean option. Here while looping, I want to loop the image which has featured_image=True first and then rest of the images. How can I do this with single for loop? -
How can I get user input for Image and save it in database using Django
I am trying To get the user to input the image And I want to save this image in the database and use it later in the HTML template Note I am a beginner and please be specific with details I tried to search online but I found it hard -
how to adjust the bootstrap 5 carousel component at the top of the view and not overlap the navbar?
I'm having issues positioning my carousel component at the top the page and to the right of the navbar in large view and under the navbar in small view. I created a template navbar.html file that I allow my other templates to inherit from using django. There seems to be an issue with the content being displayed getting either pushed to the bottom of the navbar or behind it? {% extends "all_pro_painting/navbar.html" %} {% load static %} {% block navbar %} {# <img class="img-thumbnail rounded-end" src="{% static 'all_pro_painting/img/background.jpg'%}" alt="" width="1000" height="300">#} <div id="carousel_slides" class="carousel carousel-dark slide" data-bs-ride="carousel"> <div class="carousel-indicators"> <button type="button" data-bs-target="#carousel_slides" data-bs-slide-to="0" class="active" aria-current="true" aria-label="Slide 1"></button> <button type="button" data-bs-target="#carousel_slides" data-bs-slide-to="1" aria-label="Slide 2"></button> <button type="button" data-bs-target="#carousel_slides" data-bs-slide-to="2" aria-label="Slide 3"></button> </div> <div class="carousel-inner"> <div class="carousel-item active"> <img src="{% static 'all_pro_painting/img/background.jpg'%}" class="d-block w-100" alt="..."> <div class="carousel-caption d-none d-md-block"> <h5>First slide label</h5> <p>Some representative placeholder content for the first slide.</p> </div> </div> <div class="carousel-item"> <img src="{% static 'all_pro_painting/img/slide2.jpg'%}" class="d-block w-100" alt="..."> <div class="carousel-caption d-none d-md-block"> <h5>Second slide label</h5> <p>Some representative placeholder content for the second slide.</p> </div> </div> <div class="carousel-item"> <img src="{% static 'all_pro_painting/img/slide3.jpg'%}" class="d-block w-100" alt="..."> <div class="carousel-caption d-none d-md-block"> <h5>Third slide label</h5> <p>Some representative placeholder content for the third slide.</p> </div> … -
Django model foreign key, filtering?
Let's say I have models like that: class Assignment(models.Model): name = [...] is_attendable = models.BooleanField([...]) class AttendanceList(models.Model): what_to_attend = models.ForeignKey(Assignment, on_delete=models.CASCADE) who_attends_it = [...] So if I set is_attendable to False, it shouldn't be listed on the attendance list. It's like filtering the foreign key's query... How could I do that? -
django custom Registration Form which inherits from "UserCreationForm"
I have a small question about Django so I have a custom Registration Form which inherits from "UserCreationForm" and therefore I use "fields" to define the fields I want to display. For this test just ("username", "email",). But when I go to see my form which is displayed "Password" and "Password confirmation" are also present. Wanting to understand, I therefore went to see the UserCreationForm class of django but this one has a Meta class which has fields = ("username"), so I don't really see why I have the passwords which are also present. I'm sorry the explanation is a bit laborious but I would like to understand so if anyone has a little explanation thank you very much. My custom class: class CustomSignupForm(UserCreationForm): class Meta: model = CustomUser fields = ("username", "email",) The UserCreationForm of django: class UserCreationForm(forms.ModelForm): """ A form that creates a user, with no privileges, from the given username and password. """ error_messages = { "password_mismatch": _("The two password fields didn’t match."), } password1 = forms.CharField( label=_("Password"), strip=False, widget=forms.PasswordInput(attrs={"autocomplete": "new-password"}), help_text=password_validation.password_validators_help_text_html(), ) password2 = forms.CharField( label=_("Password confirmation"), widget=forms.PasswordInput(attrs={"autocomplete": "new-password"}), strip=False, help_text=_("Enter the same password as before, for verification."), ) class Meta: model = User fields = … -
Facing difficulty in implementing crud functionality in django rest framework
I am trying to build an api using django rest framework but I am facing difficulty in crud functionality where I am not able to post the data coming from front end to the database as well as cannot display it on the api in json format my models.py from django.db import models class freelancerJob(models.Model): Job_duration = ( ('1','Less than 1 month'), ('3','1 to 3 months'), ('6','3 to 6 month'), ('12','More than 6 months') ) Job_type=(("Individual",'Individual freelancer'), ('Team','Team') ) title = models.CharField(max_length=250,null=False,blank=False) description = models.CharField(max_length=2000,blank=False) skill= models.CharField(max_length=250) duration = models.CharField(max_length=50 ,blank=False,choices=Job_duration) budget = models.IntegerField(blank=False) types = models.CharField(max_length=50,blank=False,choices=Job_type) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title serializer.py file from rest_framework import serializers from .models import freelancerJob class jobPostSerializer(serializers.HyperlinkedModelSerializer): def create(self,validated_data): instance = self.Meta.model(**validated_data) instance.is_valid(raise_exception=True) instance.save() return instance def update(self, instance,validated_data): for attr,value in validated_data.items(): setattr(instance,attr,value) class Meta: model= freelancerJob fields =('title','description','skill','duration','budget','types') views.py rom django.http import JsonResponse from . models import freelancerJob from . serializers import jobPostSerializer from rest_framework import viewsets from django.views.decorators.csrf import csrf_exempt from rest_framework.views import APIView from django.contrib.auth import get_user_model from rest_framework import status from rest_framework.response import Response from rest_framework.parsers import JSONParser @csrf_exempt def jobPostView(request): if request.method == "POST": data = JSONParser().parse(request) serializer = jobPostSerializer(data= data) if serializer.is_valid(): serializer.save() return … -
How to share a list object with custom form
Am trying to share posted objects on list view but each time that I click on the share button which redirect me to share_form.html after typing into the shared textarea and submit the form it doesn't submit the shared object form, unless I use context variable {{ form }} before the object could be shared, why is it that when I use my custom form it doesn't submit the shared post? but rather when i do say {{ form }} then it's able share the post? Here is my view to share post def share_post(request, pk): original_post = Post.objects.prefetch_related('postimage_set').get(pk=pk) form = ShareForm(request.POST, request.FILES) if form.is_valid(): new_post1 = Post( shared_body = request.POST.get('description'), description = original_post.description, username = original_post.username, date_posted = original_post.date_posted, video = original_post.video, shared_on = datetime.now(), shared_user = request.user) new_post1.save() for image in original_post.postimage_set.all(): new_post = PostImage(post=new_post1, username=original_post.username, image=image.image) new_post.save() return redirect('feed:feed') ctx = {'form':form,'original_post':original_post} return render(request,'feed/share_form.html', ctx) My django form model to share post! class ShareForm(forms.Form): body = forms.CharField(label='',widget=forms.Textarea(attrs={ 'rows': '3', 'placeholder': 'Say Something...' })) My html form to share post <div class="main_content"> <div class="mcontainer"> <div class="md:flex md:space-x-6 lg:mx-16"> <div class="space-y-5 flex-shrink-0 md:w-7/12"> <div class="card lg:mx-0 uk-animation-slide-bottom-small"> <form method="POST" action="" enctype="multipart/form-data"> <div class="flex space-x-4 mb-5 relative"> <img src="{{ request.user.profile_image.url … -
Implementing Stripe with React-native and Django
I am working on a project where I am using React-native for mobile app and Django as Server. Now I want to implement stripe payment gateway. Can anyone suggest me how to do that?..How I can make a payment and send the response to the backend so that in backend I can handle which user is now subscribed?... In web we can do that using stripe-session url. We can hit the url and after successful payment it's return an id, I have to just post the id to the server. Now How can I do that with react-native because by doing so I am kicked out from my app and the session url opens in the browser, i can make the payment successfully but cannot redirect to the app. How to successfully I can implement this with react-native and django? -
allow users in a specific group to change posts UserPassesTestMixin
I have a user and a group called Manager. How do I allow a user in the Manager group to change a post that's not theirs? Here's my code so far class UserAccessMixin(UserPassesTestMixin): def test_func(self, user): issue = self.get_object() mod = user.get_object() if self.request.user == issue.author: return True elif user.object.user == mod.groups.filter(name='Manager').exists(): return True return False And my models class Issue(models.Model): MARK_AS = ((True, 'Open'), (False, 'Closed')) title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) assignee = models.ForeignKey(Profile, on_delete=models.SET_NULL, null=True, blank=True) mark_as = models.BooleanField(choices=MARK_AS, default=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('issue-detail', kwargs={'pk': self.pk}) I get the error UserAccessMixin.test_func() missing 1 required positional argument: 'user' Where do I go from here? -
Websocket connection with django channels to heroku failed
I have tried so many different things but I just cant make the websocket connection on my website. The error i get from the console is: WebSocket connection to 'wss://myapp.herokuapp.com/wss/chat' failed: I'm using django channels with the following configurations: asgi.py os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proj.settings') django.setup() application = ProtocolTypeRouter({ "https": get_asgi_application(), "websocket": AuthMiddlewareStack( URLRouter( api.routing.websocket_urlpatterns ) ), }) settings.py ALLOWED_HOSTS = ["*"] CSRF_TRUSTED_ORIGINS = ['https://myapp.herokuapp.com', 'wss://myapp.herokuapp.com/wss/chat'] routing.py websocket_urlpatterns = [ re_path(r'wss/chat', consumers.VideoConsumer.as_asgi()) ] main.js (websocket + endpoint) var endPoint = 'wss://myapp.herokuapp.com/wss/chat' webSocket = new WebSocket(endPoint); Procfile web: daphne proj.asgi:application --port $PORT --bind 0.0.0.0 -v2 -
the error ('QuerySetManager' object is not callable) pops up? dont understand why?
def connectFunctionToNonFunction(functionID, nfID): connect_toMongoDB() print("In side connect function and function id is: ", functionID, "nonfunction id is: ", nfID) find=model_mongo.mapFunctionToNonfunction() find=find.objects(funID=functionID).get() print("find is ==========", find.funID, find.non_function_lst) if find is not None: find.update(push__non_function_lst= str(nfID)) find.save() else: print("object does not exist.. adding is in process") ds = model_mongo.mapFunctionToNonfunction() ds.funID=functionID ds.non_function_lst.append(str(nfID)) ds.save() print("index is sucessfully added")