Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to start and stop stream in which uses nginx rtmp and Django
I am an absolute beginner with NGINX and RTMP module. I am working on a project which involves a live streaming app. I want to link this Nginx rtmp server to my django server which runs on port 8000. This is what I made up my nginx.conf file after going through multiple tutorials. What I understood from following the tutorials is that application is endpoint in rtmp so i put the url next to it, also I understand that hls video will be stored in the folder path that I provide along push/hls_path.I have a doubts now, do I need to define two applications(as it done) for start stream and stop stream or they can be clubbed together into one application. Please clarify my doubts and correct me. Thank You! Nginx configuration for RTMP upstream and HLS downstream worker_processes auto; events { worker_connections 1024; } # RTMP configuration rtmp { server { listen 1935; # Listen on standard RTMP port chunk_size 4000; application rtmp://localhost/api/livevideostreams/startstream { # Live status live on; # Turn on HLS hls on; hls_fragment 3; hls_playlist_length 60; # disable consuming the stream from nginx as rtmp deny play all; # Push the stream to the local HLS … -
{% for projects in profile.project_set.all %} is not displaying anything
I have been learning django through a video course and in the video course the guys has used {% for projectss in profile.project_set.all %} {{ projectss.title }} {% endfor %} To display List of projects Here is my Model.js file of project model class Project(models.Model): owner = models.ForeignKey(Profile, null=True, blank=True, on_delete=models.SET_NULL) title = models.CharField(max_length=200) id = models.UUIDField(default = uuid.uuid4 , primary_key=True, unique=True, editable=False) And Here is my Model.js of Users model class Profile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) id = models.UUIDField(default=uuid.uuid4, primary_key=True, editable=False, unique=True) The guy in video is doing the same thing its working for him but not me. -
Application Error while deploying django website please help me to get this issue resolve
2022-06-25T12:44:34.000000+00:00 app[api]: Build started by user mohammedvaraliya2661392@gmail.com 2022-06-25T12:45:01.176068+00:00 app[api]: Deploy 6cc5ee0c by user mohammedvaraliya2661392@gmail.com 2022-06-25T12:45:01.176068+00:00 app[api]: Release v13 created by user mohammedvaraliya2661392@gmail.com 2022-06-25T12:45:11.000000+00:00 app[api]: Build succeeded 2022-06-25T12:45:17.901599+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=textutilssystem.herokuapp.com request_id=a3bdba23-2b85-4c0d-91d8-0477bc1b3c2f fwd="103.56.227.229" dyno= connect= service= status=503 bytes= protocol=https 2022-06-25T12:45:18.769362+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=textutilssystem.herokuapp.com request_id=7ffe54ce-071f-4f63-9d44-7b507a47c08d fwd="103.56.227.229" dyno= connect= service= status=503 bytes= protocol=https 2022-06-25T12:48:55.291051+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=textutilssystem.herokuapp.com request_id=f18e05e7-9e02-497a-9179-a7eb94129a4d fwd="103.56.227.229" dyno= connect= service= status=503 bytes= protocol=https 2022-06-25T12:48:56.133916+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=textutilssystem.herokuapp.com request_id=5882a3a1-f662-40a4-be6e-5cfea3786bc4 fwd="103.56.227.229" dyno= connect= service= status=503 bytes= protocol=https 2022-06-25T12:49:10.243644+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=textutilssystem.herokuapp.com request_id=39f5b3c5-1811-4a32-824a-591a9faa4b0b fwd="103.56.227.229" dyno= connect= service= status=503 bytes= protocol=https 2022-06-25T12:49:11.446623+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=textutilssystem.herokuapp.com request_id=bc10901a-cdcf-470f-b7d1-3944646dc935 fwd="103.56.227.229" dyno= connect= service= status=503 bytes= protocol=https -
IntegrityError at /signup UNIQUE constraint failed: auth_user.username ---> In django
When I click on sign in button I get integrity error!! I have checked in my admin site and all users are properly visible which i had signed up . But when I click sign in button with entries already registered in admin , my code crashes and gives integrity error!! This is my views.py from django.http import HttpResponse from django.shortcuts import redirect, render , HttpResponse from django.contrib.auth.models import User from django.contrib import messages from django.contrib.auth import authenticate , login # Create your views here. def home(request): return render(request,"authentication/index.html") def signup(request): if request.method=="POST": username=request.POST.get('username') fname=request.POST.get('fname') lname=request.POST.get('lname') email=request.POST.get('email') pass1=request.POST.get('pass1') pass2=request.POST.get('pass2') myuser=User.objects.create_user(username,email,pass1) #creating user myuser.first_name=fname myuser.last_name=lname myuser.save() messages.success(request,"Your account has been successfuly created") return redirect('/signin') return render(request,"authentication/signup.html") def signin(request): if request.method=='POST': username=request.POST.get('username') pass1=request.POST.get('pass1') user=authenticate(username=username,password=pass1) if user is not None: login(request,user) return render(request,"authentication/index.html") else: messages.error(request,"Bad credentials") redirect('home') return render(request,"authentication/signin.html") def signout(request): pass -
Problem with passing kwargs in django rest
I have created simple endpoint about user detail with default_lookup = pk and, if pk == 9_999_999_999 I wish to return user that is already logged in. My problem i assume is with kwargs, am i doing something wrong? class UserDetailView(generics.RetrieveUpdateDestroyAPIView): serializer_class = UserSerializer queryset = User.objects.all() def get(self,*args,**kwargs): pk = kwargs.get('pk') print(kwargs) print(f"pk {pk}") if pk == 9999999999: kwargs['pk'] = self.request.user.id print(kwargs) return self.retrieve(self,*args,**kwargs) and output: {'pk': 9999999999} pk 9999999999 {'pk': 13} Not Found: /api/users/9999999999 -
Adding Plus minus button in form with POST and scrf_tocken
With Django I generate a list of items, with the number of them. To be more convenient, I would like to add a plus and a minus button. I found a simple solution, but when I try to put this in my form with the POST method, if click the page refresh or POST ? I don't want to refresh the page every time, I have a validate button and all the value will be treat in one time. <form class"form-inline" action="{% url 'stock:stock' %}"method="post" >{% csrf_token %} {% for stock in stocks %} <div> <button id="minusButton">-</button> <input type="number" name="stock" id="stock" value="{{stock.stock}}" > <button id="plusButton">+</button> </div> {% endfor %} </form> <script> textInput = document.querySelector('#numberInput'); plusButton = document.querySelector('#plusButton'); minusButton = document.querySelector('#minusButton'); plusButton.onclick = () => textInput.value = parseInt(textInput.value) + 1; minusButton.onclick = () => textInput.value = parseInt(textInput.value) - 1; </script> If anyone know how to manage? -
How to serve media files correctly in django subdomains (using django-hosts) in development?
I have this model Blog and using it in 'blog' subdomain created with 'django-hosts'. My subdomains in 'hosts.py': from django.conf import settings from django_hosts import patterns, host host_patterns = patterns('', host(r'blog', 'blog.urls', name='blog'), host(r'(|www)', settings.ROOT_URLCONF, name='www'), ) And Blog model - Note that 'title_image' field powered by 'sorl.thumbnail' and 'content' field is a 'django-ckeditor' uploadable field: class Blog(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name=_('author'), on_delete=models.CASCADE, related_name='blog_author') title = models.CharField(verbose_name=_('title'), max_length=200) title_image = ImageField(verbose_name=_('title image'), blank=True) content = RichTextUploadingField(verbose_name=_('content')) I've' created a simple ListView for blog that show every blog title, content and title_image to viewer: class BlogListView(ListView): """Everyone can see all blogs""" template_name = 'blog/templates/blog/blog_list_view.html' model = Blog context_object_name = 'blogs' And my blog.urls: from django.urls import path from . import views app_name = 'blog' urlpatterns = [ path('', views.BlogListView.as_view(), name='blog_list_view'), ] When I'm using my blog subdomain (eg: blog.localhost:8000/) it doesn't show any image to me whether it's the title_image or any image in django-ckeditor powered 'content' field. But when I'm not using subdomain and instead use 'blog' app as other 'URLCONF' path (eg: localhost:8000/blog/) I can see every images without any problem. Anyone knows why using subdomains, media files does not shown and how to fix it? -
Couldn't to rollback migrations: Value Error
I have tryed to roll back, cause have some migration conflicts, but it wrotes me: ValueError: The field accounts.Ninja.id_team was declared with a lazy reference to 'mission.team', but app 'mission' doesn't provide model 'team'. Trying python manage.py migrate accounts 0052. [X] 0050_goal_id_ninja [X] 0051_ninja_id_user [X] 0052_alter_ninja_id_user [ ] 0053_alter_ninja_id_user [ ] 0054_remove_ninja_id_team [ ] 0055_remove_ninja_id_user [ ] 0056_remove_goal_id_ninja [ ] 0057_ninja_id_user [ ] 0058_remove_ninja_id_user [ ] 0059_ninja_id_team_ninja_id_user [ ] 0060_remove_ninja_id_user [ ] 0061_delete_ninja [ ] 0062_ninja [ ] 0063_delete_ninja [ ] 0064_ninja [ ] 0065_ninja_id_team_ninja_id_user [ ] 0066_remove_ninja_id_team [ ] 0067_ninja_id_team [ ] 0068_remove_ninja_id_team [ ] 0069_ninja_id_team Note. I have the model Team in mission app. -
Django: User matching query does not exist in django
i wrote a function to send message using django and ajax, when i submit the message form it shows this error User matching query does not exist., i have tried getting the user in ajax like this: <input type="hidden" name="to_user" id="to_user" value="{{active_direct}}"> <script type="text/javascript"> $(document).on('submit', '#chat-form', function (e) { e.preventDefault(); let _to_user = $("#to_user").attr("name") $.ajax({ //some code here }) </script> but it keeps showing the same error when i submit the form, i have already written the server side with django but i think there is something i am not getting right. views.py @login_required def Directs(request, username): user = request.user messages = Message.get_message(user=user) active_direct = username directs = Message.objects.filter(user=user, reciepient__username=username) directs.update(is_read=True) for message in messages: if message['user'].username == username: message['unread'] = 0 context = { 'directs': directs, 'messages': messages, 'active_direct': active_direct, } return render(request, 'directs/direct.html', context) def SendDirect(request): if request.method == "POST": from_user = request.user to_user_username = request.POST['to_user'] body = request.POST['body'] to_user = User.objects.get(username=to_user_username) Message.sender_message(from_user, to_user, body) # return redirect('message') success = "Message Sent." return HttpResponse(success) directs.html <form id="chat-form"> {% csrf_token %} <div class="input-group"> <input type="hidden" name="to_user" id="to_user" value="{{active_direct}}" /> <input name="body" id="body" type="text" class="form-control" placeholder="Type your message" /> <button class="btn btn-primary" type="submit">Send</button> </div> </form> <script type="text/javascript"> $(document).on("submit", "#chat-form", function … -
Django ElasticSearch rest framework suggestion duplicate result
I am writing a API which will auto-suggest when I a type something but it is working, it is returning the results without query and even sometime duplicate value. This is is my API views: from django_elasticsearch_dsl_drf.filter_backends import ( SuggesterFilterBackend ) from django_elasticsearch_dsl_drf.viewsets import DocumentViewSet from django_elasticsearch_dsl_drf.constants import ( SUGGESTER_COMPLETION, ) from users.paginations import LotPagination class SuggestionsAPIView(DocumentViewSet): document = ProductDocument serializer_class = ProdcutTitleSerializer filter_backends = [ SuggesterFilterBackend, ] suggester_fields = { 'title': { 'field': 'title', 'suggesters': [ SUGGESTER_COMPLETION, ], 'options': { 'size': 20, 'skip_duplicates':True, }, }, } and when I make API request, I pass parameter like this: http://127.0.0.1:8000/search/product/?title=Ar In my database, there are lots of duplicate title but when it return the search results in suggestion, it should not show the duplicate title. Can anyone please help me in this case? Why is it not working? or should I do it another way? -
can not update data in Django Form
can not upload data in Profile. How to Solve the problem. can not upload data in Profile. How to Solve the problem. can not upload data in Profile. How to Solve the problem. can not upload data in Profile. How to Solve the problem. model.py class Profile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE, blank=True, null=True) name = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) created_at = models.DateField(auto_now_add=True) alamat = models.CharField(max_length=200, null=True) no_tlp = models.IntegerField(default=0) wilayah = models.CharField(max_length=200, null=True) j_kel = models.CharField(max_length=200, null=True) pic_Profile = models.ImageField(upload_to='profil/',default="person-circle.svg",null=True, blank=True) def __str__(self): return str(self.id) this form.py class Uplaoddata(ModelForm): no_tlp = forms.CharField(label='No Telpon', max_length=100) wilayah = forms.ChoiceField(label =("Wilayah"),widget=forms.Select, choices=wilayah ,help_text="<style>.errorlist{display:None} </style>") j_kel = forms.ChoiceField(label = ("Jenis Kelamin"),widget=forms.Select, choices=Jenis ,help_text="<style>.errorlist{display:None} </style>") pic_Profile = forms.ImageField(label='Foto Profil', max_length=100) class Meta: model=Profile fields=["email", "name", "alamat", "no_tlp", "wilayah", "j_kel", "pic_Profile"] this my view.py def home(request): data = cartData(request) cartItems = data['cartItems'] id_profil = request.user.profile profiles = Profile.objects.get(id__contains=id_profil) if request.method == "POST": form = Uplaoddata(request.POST ,request.FILES, instance=profiles) if form.is_valid(): form.save() else: form=Uplaoddata(instance=profiles) print("Data Tidak terupdate") context = {'profiles':profiles,'form':form, 'cartItems':cartItems} return render(request, 'home.html',context) -
Django smtp mail is having HTTP link in button but the plain text contains the correct HTTPS one
My server is sending different mail for things like password reset, email verification etc. The mail template button link gets changed to HTTP one, which gives a non-secure warning. The plain paragraph text link is the correct HTTPS one. When using 'django.core.mail.backends.smtp.EmailBackend' Let's say that the current host is localhost and port 8000. So {{ activate_url }} for confirming the mail becomes http://localhost:8000/some-path/account-confirm-email/<token>/ but the button shows a different URL http://url5948.domain/ls/click?upn=<very-long-token>. It seems to be a kind of redirect. What's the problem here? Note: I am using the same variable to generate button href and plain-text link. -
How to use Django oscar catalogue options?
I have a product where it as multiple options for the user to select. say its a food item and it has different flavours and size packs.So i need to have an option in the UI for the users to select the option they want and that product need to be added to the basket with the user provided options. -
how to show image just after uploading in django form
I have a model of image and I want that when a user uploads the image field of the model the image should be shown in the form so that user can confirm the uploaded image but I didn't find any easy solution to do this task. Please show me what is the good and easy way to implement this functionality. -
Django channels can't use redis
I am trying to do a chat app with Django channels. To do it I copied the code of a youtube video from Github. The video link is here. But when I run it I get WebSocket is already in CLOSING or CLOSED state. I use redis. CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [('127.0.0.1', 6379)], }, }, } But when I use InMemoryChannelLayer it works perfectly. Also I haven't enabled the Redis localhost. What should I do? Thanks. -
Doesn't provide model team
ValueError: The field accounts.Ninja.id_team was declared with a lazy reference to 'mission.team', but app 'mission' doesn't provide model 'team'. This is my error when I try migrate or migrate --fake. class Ninja(models.Model): id_user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="ninja", blank=True, null=True) id_team = models.ForeignKey("mission.Team", null=True, blank=True, on_delete=models.SET_NULL) def __str__(self): return '{}'.format(self.id_user) class Team(models.Model): id_mission = models.ForeignKey(Mission, null=True, blank=True, on_delete=models.SET_NULL) name = models.CharField(max_length=200, null=True) leader = models.ForeignKey("accounts.Ninja", related_name='team_leader_set', null=True, on_delete=models.SET_NULL) # member = models.ForeignKey(Ninja, null=True, on_delete=models.SET_NULL) # count_members = models.PositiveIntegerField(null=True) date_created = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return self.name I have two apps - Mission and Accounts. My accounts.showmigrations: [X] 0001_initial [X] 0002_remove_time_description [X] 0003_time_description [X] 0004_alter_time_value [X] 0005_alter_time_value [X] 0006_alter_time_value [X] 0007_remove_time_value [X] 0008_time_value [X] 0009_remove_team_leader_remove_team_member_and_more [X] 0010_alter_time_category [X] 0011_alter_goal_status_alter_time_category [X] 0012_alter_goal_status_alter_time_category [X] 0013_alter_goal_status_alter_time_category [X] 0014_alter_time_description [X] 0015_alter_goal_description [X] 0016_alter_time_category [X] 0017_alter_time_category [X] 0018_remove_time_category [X] 0019_time_category [X] 0020_alter_time_description [X] 0021_alter_goal_description_alter_goal_status_and_more [X] 0022_alter_goal_status_alter_time_category [X] 0023_remove_time_category [X] 0024_time_category [X] 0025_alter_time_category [X] 0026_alter_time_category [X] 0027_alter_time_category_alter_time_description [X] 0028_alter_time_category_ninja [X] 0029_remove_goal_id_user_goal_id_ninja [X] 0030_rename_id_ninja_goal_id_user [X] 0031_alter_goal_id_user [X] 0032_alter_goal_id_user_alter_ninja_id_team_and_more [X] 0033_rename_id_user_goal_id_ninja [X] 0034_remove_goal_id_ninja_goal_id_user [X] 0035_alter_ninja_id_user [X] 0036_alter_ninja_id_user [X] 0037_remove_goal_id_user [X] 0038_goal_id_user [X] 0039_remove_goal_id_user_goal_id_ninja [X] 0040_remove_ninja_id_user [X] 0041_remove_goal_id_ninja [X] 0042_ninja_id_user [X] 0043_remove_ninja_id_user [X] 0044_goal_id_user [X] 0045_goal_id_ninja [X] 0046_remove_goal_id_user [X] 0047_goal_id_user [X] 0048_alter_goal_id_ninja [X] 0049_remove_goal_id_ninja [X] 0050_goal_id_ninja [X] 0051_ninja_id_user [X] 0052_alter_ninja_id_user [ … -
Populating db with initial data in Django
I need a way to populate db with initial data(cities) for my refs. So I've tried to do it through migrations(https://docs.djangoproject.com/en/4.0/topics/migrations/#data-migrations) Not sure it's a best way, since now I've made changes in this file after migration and can't apply it again, neither can't roll it back(since operation ...populate_cities... is not reversible) and apply again. So the questions are: is there a way to roll such migration back(may be manually)? may be there is a better way to populate db with such data -
Looping through <TD> and linking to whatever is in the loop - Django
I have a loop inside HTML that goes over every user and shows whats linked to it as shown in pic How do I make the HTML link to whatever is shown in the URL? using the following snippet : <td> <a href="{{ user.speciality }}">{{ user.speciality }} </td> will link me to http://127.0.0.1:8000/['http://127.0.0.1:8000/api/speciality/1/',%20'http://127.0.0.1:8000/api/speciality/2/'] -
I need simple django rest framework microservice project
There are 3 services in project. Services are: account category product -
Django restframework filtering with multiple query
I have viewset like this with django-restframework class MixViewSet(viewsets.ModelViewSet): serializer_class = MixSerializer filter_backends = [django_filters.rest_framework.DjangoFilterBackend] filter_fields = ["id","user"] def list(self,request,*args,**kwargs): #filterset = FilterBook(request.query_params, queryset=Mix.objects.all()) queryset = self.filter_queryset(self.get_queryset()) #print(request.GET['access_token']) if ('at' in request.GET): try: user = AccessToken.objects.get(token=request.GET['at']).user except: print("access token invalid") return Response({'message':'invalid access token'}) print(user.id) queryset = queryset.filter(user=user) #http://localhost:8008/api/mixs/?access_token=128 serializer = self.get_serializer(queryset, many=True) custom_data = { 'items': serializer.data } custom_data.update({ 'meta':{"api":"Mix"} }) return Response(custom_data) def get_queryset(self): queryset = Mix.objects.all() ids = self.request.query_params.get('id') print(ids) if ids is not None: queryset = queryset.filter(id=ids) return queryset class MixSerializer(serializers.ModelSerializer): pub_date = serializers.DateTimeField(format="%m/%d/%Y,%I:%M:%S %p") class Meta: model = Mix fields = ('id','pub_date','detail','user') Now I want to get the items by multiple id such as https://example.com/mix/?id=100&id=112&id=143 however in this case only 143 works and it returns the one row. How can I make this work for multiple query?? -
How to Make use of Pagination in this API using Django
Here I am trying to create a getData API using Django Rest Framework in which i want to get data using Pagination, i had created this statically but it should be like (getting PAGE and number of ROWS on that page) in request and accordingly data get fetch from database and also show the number entries i got. please help me out to solve this, i have no idea about how pagination works logically just have basic understanding. class DeviceControlPolicyView(APIView): def get(self, request): if request.data.get('page', 'rows'): if request.data.get('page') == "1" and request.data.get('rows') == "1": print(request.data.get('rows')) print(request.data.get('page')) qry = DeviceControlPolicy.objects.all()[0:1] serializer = DeviceControlPolicySerializer(qry, many=True).data entries = 1 data = { 'details':serializer, 'entry':entries } return Response(data) elif request.data.get('page') == "1" and request.data.get('rows') == "2": print(request.data.get('rows')) print(request.data.get('page')) qry = DeviceControlPolicy.objects.all()[0:2] serializer = DeviceControlPolicySerializer(qry, many=True).data entries = 2 data = { 'details': serializer, 'entry': entries } return Response(data) -
Client sent an HTTP request to an HTTPS server Docker Django Nginx
I have recently started learning docker and I created a django app which I went ahead and dockerized. I am however experiencing an error I can't get past. The error message is Client sent an HTTP request to an HTTPS server. Here is my nginx config file server { listen 80; listen [::]:80; server_name 192.168.99.106; charset utf-8; location /static { alias /usr/src/app/static; } location / { proxy_pass http://web:8000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } } And here is my docker-compose.yml version: '3' services: web: restart: always build: ./web expose: - "8000" links: - postgres:postgres - redis:redis volumes: - web-django:/usr/src/app - web-static:/usr/src/app/static env_file: .env environment: DEBUG: 'true' command: sh -c "python manage.py makemigrations && python manage.py migrate && usr/local/bin/gunicorn inventory.wsgi:application -w 2 -b :8000" nginx: restart: always build: ./nginx/ ports: - "80:80" volumes: - web-static:/www/static - ./certbot/www:/var/www/certbot/:ro - ./certbot/conf/:/etc/nginx/ssl/:ro links: - web:web certbot: image: certbot/certbot:latest volumes: - ./certbot/www/:/var/www/certbot/:rw - ./certbot/conf/:/etc/letsencrypt/:rw command: certonly --webroot -w /var/www/certbot --force-renewal --email example@gmail.com -d 192.168.99.106 --agree-tos postgres: restart: always image: postgres:latest ports: - "5432:5432" volumes: - pgdata:/var/lib/postgresql/data/ environment: POSTGRES_DB: "db" POSTGRES_HOST_AUTH_METHOD: "trust" POSTGRES_PASSWORD: ${DB_PASS} redis: restart: always image: redis:latest ports: - "6379:6379" volumes: - redisdata:/data volumes: web-django: web-static: pgdata: redisdata: The docker … -
WebSocket connection to 'url' failed
I just deployed a django project that uses djagno channels in heroku.. when I try to create a websocket connection form http://localhost:3000/ to the url, I am getting connection to websocket failed Is this due to improper deployment or something else I am not able to understand can anyone help me.. This is how i am connecting to websocket useEffect(() => { Socket = new WebSocket(`${WEBSOCKET_URL}/room/${roomName}/${myUserName}/`); Socket.onmessage = ({ data }) => { let res = JSON.parse(data); if (!res.error && res["data-type"] === "begin-game") { const { gameId } = res; Socket.close(); navigate(`/game/${gameId}/`, { state: { gameId, data: res.data, myUserName }, }); } else if (!res.error) setUsersOnRoom({ ...res.data }); }; }, []); where WEBSOCKET_URL is export const WEBSOCKET_URL = "wss://ludo-thegameforlegends.herokuapp.com/ws"; The codes in my django project is in asgi.py import os from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter,URLRouter from channels.auth import AuthMiddlewareStack from main.routing import websocket_urlpatterns as room_urlpatters from gameManager.routing import websocket_urlpatterns as gameManager_urlpatterns from channels.security.websocket import AllowedHostsOriginValidator os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ludo.settings') websocket_urlpatterns = room_urlpatters + gameManager_urlpatterns application = ProtocolTypeRouter({ 'http':get_asgi_application(), 'websocket':AllowedHostsOriginValidator(AuthMiddlewareStack(URLRouter(websocket_urlpatterns))), }) I am configuring channel layers like this CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [(os.environ.get('REDIS_URL'), 6379)], }, }, } routing is like this.. from django.urls import … -
why does css file is not working in django project
When i shutdown my PC and reopen my project every time i have to change the css file name to see the changes on the web i have tried many ways to fix this issues. *i have researched online but i did not get any answer on it * i have tried these ways to fix this error i have tried settings up STATIC_ROOT=''. i have tried setting up STATICFILES_DIRS=[]. please guide me to solve this error. -
Can We Have Two Views For The Same Page - Django
I am working on a simple project of creating a e-commerce for having a product and orders pages for customer and admin of website. Now I wanted the same product page for both customer and admin but admin should have more options like editing that product or who ordered the product whereas customers shouldn't be able to see this. Is it possible by creating a different views but passing two different values or can we use jinja tags for this ? NB : I am beginner so please forgive me if i missed a point or while explaining please use simpler terms. Thanks For Answers