Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can't hear voice and sound while sharing screen in Agora.io
I have some issues with screen sharing. I can't hear any sounds from viewer site. What can i do this for? I am new to this. Source from dennis ivy:https://www.youtube.com/watch?v=QvNzL_FmzLQ&t=33273s let toggleScreenShare = async() => { if (sharingScreen){ sharingScreen = false await rtcClient.publish([localScreenTracks]) toggleVideoShare() document.getElementById('screen-btn').innerText ='Share screen' }else{ sharingScreen = true document.getElementById('screen-btn').innerText ='Share camera' localScreenTracks = await AgoraRTC.createScreenVideoTrack() document.getElementById('video__stream').innerHTML ='' let player = document.getElementById(`user-container-${rtcUid}`) if(player != null){ player.remove() } player = `<div class="video-container" id="user-container-${rtcUid}"> <div class="video-player" id="user-${rtcUid}"></div> <div class="live-location"> <span class="live-tag">LIVE</span></div> </div> </div> ` document.getElementById('video__stream').insertAdjacentHTML('beforeend', player) localScreenTracks.play(`user-${rtcUid}`) await rtcClient.unpublish([localTracks[0], localTracks[1]]) await rtcClient.publish([localScreenTracks]) } -
contenttype field in serializer without model
Here is the class that only takes object_id and content_type as post request and for that I want to create contenttype field in serializerclass which must show all contenttype object of project while passing data from browsable api. Can somebody know how to do that And my code look like: in views.py from rest_framework.views import APIView class Snippetviews(APIView): serializer_class=SnippetSerializer def post(self,request): data = request.data object_id = data.get("object_id",None) content_type = data.get("content_type") ctype = ContentType.objects.get(model=content_type) obj_model = ctype.get_object_for_this_type(id=object_id) in serializers.py class SnippetSerializer(serializers.Serializer): object_id=serializers.IntegerField() #for this field i don't know what to do.. content_type = -
How to Login with Gmail account in Django
I am having a Login button with Gmail account in Django....Here when I am login with Gmail account means I want extra add information from the user and I want to Store that Information in the auth_user table. Please Help me If I login with Gmail means I will Redirect to that Register Page With Some More Extra Informations. It will Successfully Login but I don't Know How to Save the Extra Information in the auth_user table.Here I am having Extra Register Form with Extra Information to add User but I don't Know how to save that Information in auth_user table in Postgresql.Please Help me I am stuck here Please Help me someone -
Django: How to embede a video in <iframe> using the URL sourced from the database in Django?
I have a Django app that displays a list of videos (ListView). On clicking each item in the ListView, I get directed to DetailView where that specific video is displayed. I am trying to accomplish this by: I can see that the URL as a text is modeled properly. This is how it's supposed to look. The image below shows the embedded video by hard passing the URL in the . But I want to pass the URL dynamically to the src="<URL sourced to database>" from the database. Please help me. Thank you in advance. -
In djangorestframewokr how to apply group by in django serializer using queryset?
models.py Sharing two mapping table where in CategoryLessonMapping, category is mapped with lesson and in UserLessonMapping, user is mapped with lesson ------- category mapped with lesson -------------------- class CategoryLessonMapping(models.Model): category = models.ForeignKey(MasterCategory, on_delete=models.CASCADE, blank=True, null=True) lesson = models.ForeignKey(Lesson, on_delete=models.CASCADE, blank=True, null=True) class Meta: db_table = 'category_lesson_mapping' ------- user mapped with lesson -------------------- class UserLessonMapping(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True) lesson = models.ForeignKey(Lesson, on_delete=models.CASCADE, blank=True, null=True) class Meta: db_table = 'user_lesson_mapping' views.py ------- getting lesson and category related to lesson in json format -------------------- class PatientLessonListView(ListAPIView): serializer_class = PatientLessonSerializer queryset = UserLessonMapping.objects.all() permission_class = (permissions.IsAuthenticated,) def get_queryset(self): user_lesson = self.queryset.filter(user=self.request.user) user_lesson_id = user_lesson.values_list("lesson_id", flat=True) return CategoryLessonMapping.objects.filter(lesson_id__in=user_lesson_id) serializers.py --------- get lesson serialized data ------------- class LessonSerializer(serializers.ModelSerializer): class Meta: model = Lesson fields = ('id', 'lesson_type', 'content', 'description') depth = 1 --------- get category serialized data ------------- class CategorySerializer(serializers.ModelSerializer): class Meta: model = MasterCategory fields = ('id', 'name', 'code') --------------- getting lesson and category related to user ----------used in views.py------------ class PatientLessonSerializer(serializers.ModelSerializer): lesson = LessonSerializer() category = CategorySerializer() class Meta: model = CategoryLessonMapping fields = ['lesson','category'] then json format in which i'm getting it is [ { "lesson": { "id": 1, "lesson_type": { "id": 1, "lesson_type": "Video", "lesson_code": "VIDEO", "is_active": 1, "created_at": … -
How at get user profile details from Django using React?
I have created an Api using django rest framework (localhost/users/profile) that gets the user's details if they are logged in. It works perfectly when I call the API in the backend when user is logged in the backend. enter image description here But when I try to access the same API from my React front end, it doesnt work. import React, { useEffect, useState } from "react" import AuthContext from '../context/AuthContext' import {Link} from 'react-router-dom' const ProfilePage = () => { const [profiles, setProfiles] = useState([]) const fetchData = async () => { const response = await fetch("http://127.0.0.1:8000/users/profile") const data = await response.json() setProfiles(data) console.log(data) } useEffect(() => { fetchData() }, []) return ( <div> {profiles.length > 0 && ( <ul> {profiles.map(profile => ( <li key={profile.id}>{profile.name}</li> ))} </ul> )} </div> ) } export default ProfilePage error from console enter image description here error from Backend server enter image description here -
Django Admin Page not found (404), urls.py + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Going to http://127.0.0.1:8000/admin returns this error: Using the URLconf defined in the_food_blog.urls, Django tried these URL patterns, in this order: admin/ [name='home'] <slug:slug>/ [name='post_detail'] ^(?P<path>.*)$ The current path, admin, matched the last one. urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', include('blog.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urls.py urlpatterns = [ path('', views.PostList.as_view(), name='home'), path('<slug:slug>/', views.PostDetail.as_view(), name='post_detail'), ] Removing + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) fixes this but why? -
How can I prevent one USER from writing multiple reviews for the same movie in djnago?
What you want to achieve I want to prevent one USER from writing multiple reviews for the same movie. I got the movie information from TMDB, so I didn't know how to change it and asked. Current code def view_movie_detail (request, movie_id): if not (Movie.objects.filter (id = movie_id)): Movie (id = movie_id) .save () movie = Movie.objects.get (id = movie_id) if request.method == "POST": form = Comment_movie_CreateForm (request.POST) if form.is_valid (): Comment_movie ( comment = form.cleaned_data ['comment'], user = request.user, stars = form.cleaned_data ['stars'], movie = movie ). Save () return redirect ('view_movie_detail', movie_id = movie_id) else: else: form = Comment_movie_CreateForm () data = requests.get (f "https://api.themoviedb.org/3/movie/{movie_id}?api_key={TMDB_API_KEY}&language=en-US") recommendations = requests.get (f "https://api.themoviedb.org/3/movie/{movie_id}/recommendations?api_key={TMDB_API_KEY}&language=en-US") comments = reversed (Comment_movie.objects.filter (movie_id = movie_id)) average = movie.average_stars () context = { "data": data.json (), "recommendations": recommendations.json (), "type": "movie", "comments": comments, "average": average, "form": form, } return render (request, "Movie / movie_detail.html", context) class Movie (models.Model): id = models.CharField (primary_key = True, editable = False, validators = [alphanumeric], max_length = 9999) def get_comments (self): return Comment_movie.objects.filter (movie_id = self.id) def average_stars (self): comments = self.get_comments () n_comments = comments.count () if n_comments: return sum ([comment.stars for comment in comments]) / n_comments else: else: return 0 … -
Django Admin CSRF issue on Cloud Sutdio
I am learning Django through Django official documentation on Cloud Studio,which can let people develop website online.However,a CSRF issue occurred when I tried to log in the Admin page Django carried originally.I didn't change anything in admin.py enter image description here enter image description here -
How to use d3-cloud in django?
I want to use d3 cloud (https://github.com/jasondavies/d3-cloud) in my django project. but the library source is compiled by Node JS.. so that is like var dispatch = require("d3-dispatch").dispatch; module.exports = function() { var size = [256, 256], text = cloudText, But I can't use Node JS in my django project..how can i use that library in my project? T_T -
Cannot find Django admin static file (404 not found)
My Django project deployed on EC2 instance. Everything is fine except static files. Here is my project directory path tree my_project └─admin ├── admin │ ├── admin │ ├── keywords │ ├── manage.py │ └── static ├── README.md And this is my settings.py setting code about staticfiles # settings.py debug=False BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) ROOT_DIR = os.path.dirname(BASE_DIR) STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR,'my_project/static') STATICFILES_DIRS = [ STATIC_ROOT ] And this is my nginx.conf files root /usr/share/nginx/html; location = /favicon.ico { access_log off; log_not_found off; } location /static { alias /static/; } 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://unix:/home/devel/run/gunicorn.sock; } error_page 404 /404.html; location = /40x.html { } error_page 500 502 503 504 /50x.html; location = /50x.html { } } And also my machine's environments: Centos 7.9 python 3.6.8 Django 4.0.6 I already did python manage.py collectstatic command. When I enter into this project's Admin page, Every UI have loaded without CSS and JS though. Is somewhere of my setting is wrong? I wonder why django cannot find any static files. -
How do I call model function in groupBy queryset inside View? Django
So this is get_project function I have made in this model which return project details based on billingId class ReportLog(models.Model): billing_id = ... caller_id = ... ... @property def get_project(self): return Project.objects.get(billing_id=self.billing_id) My question is how do I call or integrate this get_project method in this below groupby query I have written in the View so later on in the template page I can access the fields of Project model. bounce_log = ReportLog.objects.all().values('billing_id', 'caller_identity', 'from_addr').annotate(total=Count('billing_id')).order_by('-total') context = { "report_list": bounce_log, } In the template page, where I am iterating report_list I tried accessing with post.get_project.title however, it's returning empty. How do I access it? -
pythonanywhere: Something went wrong :-(
When I'm uploading my DRF app to pythonanywhere, the server shows the following log error: 2022-07-15 01:06:14,933: ModuleNotFoundError: No module named 'Rest_API_Framework.settings'. However, I don't understand why, since if we look at /var/www/art1x_pythonanywhere_com_wsgi.py folder, everything looks fine to me: import os import sys path = 'home/art1x/Rest_API_Framework' if path not in sys.path: sys.path.insert(0, path) os.environ['DJANGO_SETTINGS_MODULE'] = 'Rest_API_Framework.settings' from django.core.wsgi import get_wsgi_application application = get_wsgi_application() In addition, the settings.py folder in my django app: os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Rest_API_Framework.settings') Please point out any mistakes -
How can API request be "routed" through Django Backend when I want to call it from the frontend?
I am trying to make an API request to a 3rd-party server from my NextJS frontend project which requires a secret API key to be stored as an environmental variable. I used NEXT_PUBLIC_API_KEY in this case, but realized that this exposes the variable to the browser. The documentation of a 3rd-party API says " Production requests must be routed through your own backend server where your API key can be securely loaded from an environment variable or key management service." I am using Django REST as my backend; How do I "route the API through backend" when calling the API from the frontend? I see a lot of resources for node.js, but I am struggling to figure it out for Django. This is how I understood it so far, but I am not sure if it's correct and how to implement. API_KEY is stored in .env of Django server User event in frontend -> sends the data for API request to backend Backend makes the actual 3rd party API request Backend returns the API result back to frontend -
IntegrityError at /tickets/1/comments/new/ NOT NULL constraint failed: comments_comment.ticket_id
Getting an integrity error when creating a separate comments app for my ticket project. Not sure why, I have already assigned the logged in user as author in the get_absolute_url method on my Comment object and so now I'm not sure on how to proceed. Any help is much appreciated Here is my comment model models.py class Comment(models.Model): ticket = models.ForeignKey(Ticket, related_name='comments', on_delete=models.CASCADE) title = models.CharField(max_length=20) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('tickets: ticket-detail', kwargs={'pk': self.ticket_id}) Here is my views.py class CommentCreateView(LoginRequiredMixin, CreateView): redirect_field_name = 'tickets/ticket_detail.html' model = Comment fields = ['title', 'content'] def form_valid(self, form): form.instance.post_id = self.kwargs['pk'] form.instance.author = self.request.user return super().form_valid(form) -
ModuleNotFoundError: No module named 'django'
enter image description here enter image description here enter image description here enter image description here So i just tried to install django 4.0.6 and the terminal says it was successfully installed. However, when I tried to import, it says "ModuleNotFoundError: No module named 'django'" (as provided in the picture). Anyone knows what's going on there? -
CORS issue with HTTP requests when sendign http get request to host IP
I have a development environment with python's django web server running locally. I had setup django to respond to API requests and whenever I send http GET requests to http://localhost:8000/api/service/ the server responds as expected. The issue happens whenever I send the same request using the host IP, i.e, http://192.168.15.66:8000/api/service/ (I realized the issue when trying to get the api data from another host in the LAN) I'm using postman to send the requests in order to validate whether it's working or not, though, I'm developing a javascript react application that already consumes the api data. Through the web javascript application, there's a bit more information. The browser's console presents the error message: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://192.168.15.66:8000/api/service/. (Reason: CORS request did not succeed). Status code: (null). I've been searching around and tried a few suggestions, such as: setting server/setting.py ALLOWED_HOSTS to: ['192.168.15.66'] , to [] and to ['*'] whitelisting with CORS_ORIGIN_WHITELIST to: ['192.168.15.66'] and to ['*'] Here's my setting.py MIDDLEWARE varible value: 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.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", ] Any clues what I could be missing? -
How do I find all descendant models in a child/parent relationship?
Consider the following model: from django.db import models class Person(models.Model): name = models.CharField(primary_key=True, max_length=50) parent = models.ForeignKey('self', null=True, default=None, on_delete=models.SET_NULL) a = Person.objects.create(name='A') b = Person.objects.create(name='B') c = Person.objects.create(name='C', parent=a) d = Person.objects.create(name='D', parent=b) e = Person.objects.create(name='E', parent=c) Is there an easy way to find all descendants of an instance? Example of desired output: a.descendants >>> [a, c, e] -
How do I query for "greater than" on a textfield in Django?
I have a certain field in my database which is a textfield. However, for a certain use I have a set of records that only include numbers (saved as a string of course) and I want to query them using "gte" (greater than). Normally I would do: MyTable.objects.filter(text_field__gte=100) However, this does not return any results. It seems that I need to cast this field as an integer. Can I do that within this same query? The actual query is more cumbersome and involves external tables (something like MyTable.objects.filter(associated_table__other_table__text_field__gte=100)), but I am simplifying above for clarity. -
How would i go about displaying more information of objects in a ModelForm?
I've tried googling this for hours and i just can't seem to understand it. So i have a model (called Vare) that has 8 different fields with information and containes a str function. I have another model called (Rett) where you store 3 different fields and a field where you store Vare objects. I've managed to make a form for this that displayes the 3 fields + the Vare objects field, but the Vare objects field only shows the name of Vare in a dropdownbox (presumebly from the str function). Now i want to display these with more information from the 7 other fields of vare and put the into a nice looking list element instead of just a drop-down showing the name. But i can't seem to find out how you are supposed to do it. What i want is kinda like looking at amazone where you can see lots of information about the different Vare (like date crated, who is selling, price) in a nice orderly list instead of a dropdown with just the name. Currently i am just using the basic ModelForm with a meta class and i accsess it in my template as {{ rett_form.as_p }}. … -
DRF + SimpleJWT
We use DRF + SimpleJWT and we're finding that when our servers get overloaded or timed out, we're passing a 401 on the token refresh endpoint and causing users to be thrown back to the login screen (because a 401 indicates that the user is no longer authorized to view anything). Does anyone know why this might be? It only happens under really bad network conditions – we've ruled out the client and do believe it's the server returning a 401 somewhere now. When the user kills the app after being thrown back home, they are authenticated on next launch again, so it seems like we're issuing a 401 on timeout or something like that. -
How to temporatily store many user inputs somewhere in the backend within 60s?
I've been searching for solutions to this problem for weeks. My underlying struggle is that I am having trouble storing user inputs temporarily (like 60 seconds for a game. It's not like storing user IDs for each account in the backend). I want to develop a website game where it takes user input(one word as input) and counts how many words a user can give in 60 seconds. This requires the website to go back to the same website after submitting the input (but recorded each user input in the backend and count on it). I guess that I should use session in django but I'm still not sure about how should I approach this problem. -
How to Aggregate By with django-tables2 and keep linkify?
With django-tables2, I found I can either have an aggregate by querying model.objects.values('foo_bar').annotate(...) but only the values themselves are passed. If I try to linkify a column, I get an error that for linkify=True, 'FOOCOLUMN' must have a method get_absolute_url. If I pass model.objects.all(), I can linkify columns, however, it seems that you cannot aggregate. Is there a way to aggregate/annotate in django-tables2 while keeping linkify? -
Serving Vue.js static files and Django app running on gunicorn over Nginx
I have a web backend implemented in Django and running on Gunicorn. Plus, I also have a Vue.js app that uses this backend. I want to run both of them on nginx and also do HTTPS configs. This is how my "/etc/nginx/nginx.conf" file looks like: ... server { server_name .website.com; listen 80; return 307 https://$host$request_uri; } server { location / { proxy_set_header Host $host; proxy_pass http://localhost:8080; # where the Django app over gunicorn is running } location /static { root /code/frontend/dist/; # static frontend code created with vite on vue.js autoindex on; index index.html; try_files $uri $uri/ /index.html; } # ssl configs listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/website.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/website.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } Both of them, Django and Vue.js part, are hosted in a single Docker container. 80 and 8080 ports of this container is mapped to 80 and 8080 ports of the host PC. 443, 8080 and 80 ports are open on the machine for inbound connections. Sending a post request to http://website.com:8080/bla do returns correct values, meaning that backend seems to be working but on http only … -
How do i make a list from Django queryset and format the annotate field?
I'm trying to make my django query json serializable queryset= list(Products.objects.filter(status=True, salelog__created__range=(start,today)).values("name").annotate(individual_sales=Count("salelog__quantity")).annotate(combined_quantity=Sum("salelog__quantity"))) so i return json_response(queryset) and i get the following for combined_quantity: null but when i print(queryset) in terminal i get the following: [{'name': 'STEAK', 'individual_sales': 21, 'total_quantity': Decimal('300.00')}, {'name': 'RIBEYE', 'individual_sales': 18, 'total_quantity': Decimal('500.00')}, {'name': 'T-BONE', 'individual_sales': 8, 'total_quantity': Decimal('450.00')}] i guess the Decimal(xxx) doesnt play well with my front end. how do i fix this? btw im using vue and django and pretty new at this