Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django-tenant public tenant in URL explicitly
I watched Thomas's videos (he is the author of django-tenants). He sets the the Show public if no tenants flag true. Can you not set that flag to true and use the "public" key word explicitly in the url. Such as http://public.localhost:8000/admin or http://public.localhost:8000/. Thanks in advanced. -
Get filtered data after clicking a slice of pie chart and displaying it on the same Django HTML page
Within Script tag :- google.charts.load('current', { 'packages': ['corechart'] }); google.charts.setOnLoadCallback(drawChart); function drawChart() { var data = google.visualization.arrayToDataTable([ ['Status', 'Number'], ['Success',{{suc}}], ['Errors', {{fail}}] ]); var options = { title: 'Status Report', is3D: true, }; var chart = new google.visualization.PieChart(document.getElementById('piechart')); chart.draw(data, options); google.visualization.events.addListener(chart, 'select', selectHandler); function selectHandler(e) { var selectitem = chart.getSelection()[0] var samp10 = data.getValue(selectitem.row,0) } </script> In views:- checkdate = Report.objects.latest("NEW_DATE").NEW_DATE suc = Report.objects.filter(Q(NEW_DATE__month = checkdate.month) & Q(NEW_DATE__day = checkdate.day) & Q(NEW_DATE__year = checkdate.year) & (Q(MSG = "SUCCESS") | Q(MSG ="SUCCESSFUL"))).count fail = Report.objects.filter((Q(NEW_DATE__month = checkdate.month) & Q(NEW_DATE__day = checkdate.day) & Q(NEW_DATE__year = checkdate.year)) & (~Q(MSG = "SUCCESS") & ~Q(MSG ="SUCCESSFUL"))).count context = { 'suc':suc , 'fail':fail , 'checkdate':checkdate} return render(request, 'trialform.html', context) What i know:- 1.I can filter data acc to my needs in views if i get value of samp10 there What i dont know:- 1.how to send value of samp10 to my views. 2.Display the filtered data on the SAME PAGE. -
How can I insert DOCX type content created from a Ckeditor by HtmlToDocx, in to a table's cell created by Python DOCX?
Function that converts CKeditor HTML content into DOCX using HtmlToDocx def html_to_docs(html): new_parser.table_style = 'Table Grid' return new_parser.add_html_to_document(html, document) Table created by Python DOCX table # reportdetails is a django model table = document.add_table(rows=reportdetails.count()-1, cols=5, style='Table Grid') table.allow_autofit = True table.columns[0].width = Cm(2) table.columns[1].width = Cm(16) table.columns[2].width = Cm(2) table.columns[3].width = Cm(2) table.columns[4].width = Cm(2) hdr_cells = table.rows[0].cells hdr_cells[0].text = 'Research Area' hdr_cells[1].text = 'Findings' hdr_cells[2].text = 'Impact' hdr_cells[3].text = 'Recommendations' hdr_cells[4].text = 'Response' for reportdetail in reportdetails: row_cells = table.add_row().cells row_cells[0].text = reportdetail.scope.scope_name finding = row_cells[1].add_paragraph() finding.add_run(str(html_to_docs(reportdetail.findings)))#inserting CKeditor content row_cells[2].text = reportdetail.impact row_cells[3].text = reportdetail.recommendations row_cells[4].text = reportdetail.response Output I am getting on word document genetated No trees planted should be the first finding and in the findings cell of row Climate, the table with those alphabets and the line after it should be in the second findings. I have no idea why the findings cells contains None -
/media/mp3 folder not found - DJANGO
so my audio player can play music from local storage, but in strange way. if i was already upload file, when i opened again the audio file can be played. but when i uploaded again in the same time, the file cannot be played and there's message at terminal : [04/Jun/2022 15:00:17] "GET /favicon.ico HTTP/1.1" 404 2538 Honey Jet Coaster by Nasuo [Lirik Terjemahan] _ Kawaii dake ja Nai Shikimori-san Opening Full (64 kbps) (https___youtube-to-mp3.id_).mp3 [04/Jun/2022 15:00:33] "POST / HTTP/1.1" 200 7841 Not Found: /media/mp3/ [04/Jun/2022 15:00:33] "GET /media/mp3/ HTTP/1.1" 404 1741 here's my html: <audio controls="controls"> <source src="/media/mp3/{{last_audio.audio}}" type="audio/mpeg"> </audio> views.py: def homepage(request): form = AudioForm() last_audio = Audio_store.objects.last() if request.method == "POST": form = AudioForm(request.POST, request.FILES) if form.is_valid(): form.save() audio = form.cleaned_data.get("audio") print(audio) context={'form':form, 'last_audio':audio} return render(request, 'homepage.html', context) context={'form':form, 'last_audio':last_audio} return render(request, "homepage.html", context=context) i was already delete database and create again, but it's still strange. please help me, i don't know what's wrong. i was using chrome, incognito and microfost edge, and the result its same. -
Fetch details of vimeo video with url like Pytube
I want to get the thumbnail, duration etc of public Vimeo videos from a URL like PyTube in python. -
How to add custom fields in a serializer.py file inheriting from User Model Python Django
I'm developing my backend on Python Django, while its frontend is on React-Native (yet to be integrated). I was basically following a tutorial, and the guy didn't use models.py to initialize a database. Instead, he did everything through serializers.py by inheriting the built-in User model from Django. Problem is, I realized later that I had 4 other fields (dob, gender, address, contact_no) in my frontend registration page. These are not a part of the default fields in the User model. I've seen a bunch of solutions, but they all require me revamping my code too much and I'm too far ahead to do that. I've implemented registration, email verification and login. Does anyone have a solution that will allow me to use my current code AND include custom fields? Adding my code below for reference: models.py file: from django.db import models from django.contrib.auth.models import User class VerificatonToken(models.Model): user = models.ForeignKey( User, on_delete=models.CASCADE, related_name='token') verification_token = models.CharField( max_length=256, blank=True, null=True) serializers.py file: from rest_framework import serializers from django.contrib.auth.models import User from rest_framework.validators import UniqueValidator from rest_framework_jwt.settings import api_settings from .models import VerificatonToken class TokenSerializer(serializers.ModelSerializer): class Meta: model = VerificatonToken fields = ('user', 'verification_token',) class PatientSerializer(serializers.ModelSerializer): token = serializers.SerializerMethodField() email = serializers.EmailField( … -
audio control not appear - DJANGO
so i want play music from local storage, but my audio control not appear. i was use backend django to get file from local storage. there's no error message. so please help me. #html <audio controls="controls"> <source src="/media/mp3/{{last_audio.audio}}" type="audio/mpeg"> </audio> #view def homepage(request): form = AudioForm() last_audio = Audio_store.objects.last() if request.method == "POST": form = AudioForm(request.POST, request.FILES) if form.is_valid(): form.save() audio = form.cleaned_data.get("audio") print(audio) context={'form':form, 'last_audio':audio} return render(request, 'homepage.html', context) context={'form':form, 'last_audio':last_audio} return render(request, "homepage.html", context=context) -
Reduce the redundandant code in django model form
I have lot of code repeated here how can i modify such that there is only there is less redundant code in my model forms.the only difference here is the user_type in save method.which is admin user and the customer user.How can i reduce an modify my code can anyone please suggest on this class AdminUserCreateModelForm(UserCreationForm): first_name = forms.CharField(required=True) last_name = forms.CharField(required=True) email = forms.EmailField(required=True) class Meta(UserCreationForm.Meta): model = User def clean_email(self): email = self.cleaned_data.get("email") if User.objects.filter(email__iexact=email).exists(): self.add_error("email", "A user with this email already exists.") return email def clean_username(self): username = self.cleaned_data.get('username') if User.objects.filter(username__iexact=username).exists(): raise forms.ValidationError('Username Already Exists') return username def save(self): user = super().save(commit=False) user.is_admin = True user.first_name = self.cleaned_data.get('first_name') user.last_name = self.cleaned_data.get('last_name') user.email = self.cleaned_data.get('email') user.save() admin = User.objects.create(user=user) admin.phone_number = self.cleaned_data.get('phone') admin.save() return user class CustomerUserCreateModelForm(UserCreationForm): first_name = forms.CharField(required=True) last_name = forms.CharField(required=True) class Meta(UserCreationForm.Meta): model = User def clean_email(self): email = self.cleaned_data.get("email") if User.objects.filter(email__iexact=email).exists(): self.add_error("email", "A user with this email already exists.") return email def clean_username(self): username = self.cleaned_data.get('username') if User.objects.filter(username__iexact=username).exists(): raise forms.ValidationError('Username Already Exists') return username def save(self): user = super().save(commit=False) user.is_customer = True user.first_name = self.cleaned_data.get('first_name') user.last_name = self.cleaned_data.get('last_name') user.email = self.cleaned_data.get('email') user.save() customer = User.objects.create(user=user) customer.phone_number = self.cleaned_data.get('phone') customer.save() return user -
Django many to many filter
I have many to many field in user model where one user can have multiple roles for example admin, patient, doctor and others. now I want to query data to get users with admin and all other roles and not doctor and patient role. I am using this User.objects.exclude(roles__code_name__in=['pt', 'doc']) now my one user signs up as patient too so he has admin and patient role both now i am unable to get him by using above query. so concluding... if user has two roles if one of it is patient and he has any other role too i want to get him too. what should i do? Thanks in advance -
Generating new files Everytime with respect to rollnumber from body in django Logging
{ "Name": "Hardik Hussain", "DOB": "29-Nov-1998", "Class": "CSE-BAtch2", "RollNumber": "12345", } How to generate log file every time with new RollNumber passing through body (Ex.Summary_12345.log)from DJango logging . -
Django Prefetch and prefetch_related not working for reverse foreign key
I have the following models for which despite using Prefetch and prefetch_related, a sql is fired. I am trying to get the address of any of the ClientBranchDetails corresponding to the despatch_branch of the Folio model. from django.db import models class Client(models.Model): name = models.CharField(max_length=50) class ClientBranch(models.Model): client = models.ForeignKey('Client', on_delete=models.CASCADE) class ClientBranchDetails(models.Model): client_branch = models.ForeignKey('ClientBranch', on_delete=models.CASCADE, related_name='all_client_branch_details') sap_code = models.CharField(max_length=20, unique=True) address = models.CharField(max_length=100) class Folio(models.Model): folio_nbr = models.PositiveIntegerField(unique=True) client_branch = models.ForeignKey('ClientBranch', on_delete=models.CASCADE, related_name='client_branch') despatch_branch = models.ForeignKey('ClientBranch', on_delete=models.CASCADE, related_name='despatch_branch') The code is as follows client_branch_and_details=ClientBranch.objects.prefetch_related('all_client_branch_details') folios=Folio.objects.all().prefetch_related(Prefetch('despatch_branch', queryset=client_branch_and_details, to_attr='branch_details')) f=folios[0] f.despatch_branch.id f.branch_details The 3rd line above fires a SQL query as expected but so does the 4th and 5th line and this is not what I was expecting. -
Chat application in Django with Kafka
I had to build a group model where I have many users . my question is can I use ManyToManyField here like ManyToManyField(Users,related_name="users").so I can add may users and remove them . Is there any other library for making ManyToManyField for Intersting. Is there any alternative way of implementing group and group chats. -
React app not loading in IOS Facebook in-app browser
I have a full stack web application. The backend is built in Django and the front end is built in React. Everything works fine. But the only problem is when I send that website's link to someone on Facebook/Messenger and when they click on that link, it opens in the Facebook in-app browser but it shows blank page. But If I copy that same link and paste in Safari or any other browser, it loads without any issue. What might be the issue? Why doesn't it work on IOS Facebook in-app browser? -
Django Rest Framework CRUD
I´m building an API with Django Rest Framework, and I’m wondering if it's enough to use only the ModelViewSet class to implement the CRUD. My worries is that it’s not enough for the frontend to consume and use the create, read, update and delete functionalities. -
Direct assignment to the forward side of a many-to-many set is prohibited. Use creator.set() instead
I'm getting this error: Direct assignment to the forward side of a many-to-many set is prohibited. Use creator.set() instead. New to django I believe there is an error with the assignment of my create method. Here are my files: Any advice helps // Views.py def createTrip(request): trip_creator = User.objects.get(id = request.session['loggedInID']) newTrip = Trip.objects.create( creator = trip_creator, description = request.POST['description'], city = request.POST['city'], country = request.POST['country'], photo = request.POST['photo'] ) print(newTrip) return redirect('/home') //models.py class Trip(models.Model): creator = models.ManyToManyField(User, related_name= "trips") description = models.CharField(max_length= 255) city = models.CharField(max_length= 255) country = models.CharField(max_length= 255) photo = models.ImageField(upload_to='static/img/trips') // html <div class="form-container"> <h4>Add a Trip</h4> <form action="/createTrip" method="post" class="reg-form"> {% csrf_token %} <p><input class="field" type="text" name="city" placeholder="City" id=""></p> <p><input class="field" type="text" name="country" placeholder="Country" id=""></p> <p><textarea name="description" id="" cols="30" rows="10"></textarea></p> <p><input class="field" type="file" name="photo" placeholder="Photo" id=""></p> <input class="form-btn" type="submit" value="submit"> </form> </div> //settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) MEDIA_ROOT = 'static/img/trips/' MEDIA_URL = os.path.join(BASE_DIR, 'static/img/trips/') -
How to get multiple image files data in django
The simple portfolio page uploading multiple image fields and prints all images on the page also, save in DB -
Dynamically Loading Data Into Django Modal
I've been trying to implement a way to dynamically load information into a modal in order to do a quick preview for my ecommerce site. Any help would be appreciated, I'm not sure which direction I should head in. I tried to play with Javascript and creating an onclick function to refresh the div, but I have had no success so far. Please comment if any part of my question is unclear. attached is a screenshot as to what is rendering on my end to get an idea of what I am trying to do. https://gyazo.com/e0168c6d41a19071a95e8cecf84e37a9 store.html {% extends 'main.html' %} {% load static %} <!DOCTYPE html> <head> <link rel="stylesheet" href="{% static 'css/store.css' %}"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script> </head> <body> {% block content %} <div class="p-5 text-center bg-image mt-4 mb-4" style=" background-image: url('{% static 'images/ship.jpg' %}'); background-size: auto; height: 400px; box-shadow: 1px 2px 2px; "> <div class="mask" style="background-color: rgba(0, 0, 0, 0.6);"> <div class="d-flex justify-content-center align-items-center h-100"> <div class="text-white"> <h1 class="font-weight-bold mb-3" style="color: white;">Store</h1> <h2 class="font-weight-bold mb-3" style="color: white;"> Welcome to our online shop, where our shipping quotes are listed below</h1> <h3 class="mb-3" style="color: white;"> We ship a variety of items to fit your needs including cars, car parts, heavy … -
How do I filter querysets by a field chosen from template form in Django?
I'm learning Django. I have a listview and detailview for a queryset, all working properly. In the listview, I want the user to be able to search the model database choosing to look for given string in one, many, or all the model's fields. Since the filter() method gets field name as .filter(name__icontains='string') I don't know how to pass this name parameter from the form checkboxes. -
What is causing my django authentication backed to be so slow?
I have a custom authentication backend. def authenticate(self, request): start = time.time() auth_header = request.META.get("HTTP_AUTHORIZATION") if not auth_header: raise NoAuthToken("No auth token provided") id_token = auth_header.split(" ").pop() try: decoded_token = decode_verify_firebase(id_token) except Exception: raise InvalidAuthToken("Invalid auth token") if not id_token or not decoded_token: return None try: uid = decoded_token.get("user_id") email = decoded_token.get("email") except Exception: raise FirebaseError() q_start = time.time() user, created = User.objects.get_or_create(username=uid, email=email, firebase_user=True) logger.info(f'getting the user --- {time.time() - q_start}') logger.info(f'Total auth time --- {time.time() - start}') return user, None Note: I am custom decoding the firebase token, there is no outgoing request here. I put some time stamps in this function for profiling: getting the user --- 0.5818960666656494(s) Total auth time --- 0.5826520919799805(s) You can see that user query is taking the bulk of the time. This is also causing my authenticated endpoints to perform very poorly. However, when I log the queries it reports the query being very quick. Execution time: 0.089754s [Database: default] Any ideas what I could do to fix or improve this? -
ModuleNotFoundError received when using tinymce with Django
Problem I'm trying to add a 3rd party app to my project so that I can add it to an app called 'Plants' however when I follow the installation instructions I receive an error message. instructions followed: https://django-tinymce.readthedocs.io/en/latest/installation.html Troubleshooting I've tried Uninstalling and reinstalling tinymce with pip install django-tinymce and pip uninstall django-tinymce. Confirmed that I was in a virtualenv for installation and while running my server with python manage.py runserver. Fully installed the tinymce module then reset my terminal. Confirmed my requirements were created correctly with pip freeze > requirements.txt Reviewed all of my spelling in base.py, plants > models.py, and config > urls.py Confirmed my DJANGO_SETTINGS_MODULE was set correctly in config.wsgi.py and manage.py Read through every stackoverflow issue with the same traceback error. Adding path('tinymce/', include('tinymce.urls')), to plants > urls.py, that didn't make since so I removed it Traceback Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/opt/homebrew/Cellar/python@3.9/3.9.10/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 973, in _bootstrap_inner self.run() File "/opt/homebrew/Cellar/python@3.9/3.9.10/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 910, in run self._target(*self._args, **self._kwargs) File "/Users/mary/Projects/opensprouts-web/opensprouts/lib/python3.9/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/Users/mary/Projects/opensprouts-web/opensprouts/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "/Users/mary/Projects/opensprouts-web/opensprouts/lib/python3.9/site-packages/django/utils/autoreload.py", line 76, in raise_last_exception raise _exception[1] File "/Users/mary/Projects/opensprouts-web/opensprouts/lib/python3.9/site-packages/django/core/management/__init__.py", line 357, in execute … -
The Cross Origin Opener Policy header has been ignored - DJANGO
Im making a Chatapp project in Django. I implemented channels and websockets to send and receive message and this worked when i tested using two differents windows in the same browser (one of them in incognito mode), but when i try to test it using another browser i get the following error: enter image description here I tried to solve implementing django corsheaders with the following configuration: enter image description here enter image description here enter image description here (I know that setting all origins to true its not recommendable but it's just for testing purpouses) -
Django Error: Profile matching query does not exist
I am working with an Open-Source Social Media Website. I have a normal Feed.html where Users can see the Post of their Followings. When I open the feed page it shows this error message. It never showed an Error Message before. I tried insted of p = Profile.objects.get(user=u) = p = Profile.objects.get(Profile, id=1) But then it just showed the first Account on the Website. Error Message Views.py from blog.models import Post from notification.models import Notification from django.core.checks import messages from django.shortcuts import render, get_object_or_404, redirect from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from django.contrib.auth.models import User from django.urls import reverse_lazy, reverse from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView from .models import Comment, Post from .forms import CommentForm from django.http import HttpResponseRedirect, JsonResponse from users.models import Profile from itertools import chain from django.contrib.auth.decorators import login_required from django.contrib import messages from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.template.loader import render_to_string import random """ Home page with all posts """ def first(request): context = { 'posts':Post.objects.all() } return render(request, 'blog/first.html', context) """ Posts of following user profiles """ @login_required def posts_of_following_profiles(request): profile = Profile.objects.get(user = request.user) users = [user for user in profile.following.all()] posts = [] qs = None for u in users: p … -
Trying to pass traffic through NGINX container to Django with Kubernetes
I'm stuck on something that I feel is rather simple for someone who may know kubernetes. I a django app I'm trying to deploy to production. Part of that will be adding an SSL cert so I believe to do that I need something like an nginx container for public traffic to hit first. I have this working in docker-compose but our production environment is a kubernetes cluster. I was able to get the kubernetes file to spin up the containers but traffic just goes straight to the django app. How would I configure this to pass traffic through nginx instead? apiVersion: apps/v1 kind: Deployment metadata: name: networkapp-deploy labels: name: networkapp spec: replicas: 1 selector: matchLabels: name: networkapp_pod template: metadata: labels: name: networkapp_pod spec: containers: - name: nginx image: nginx:alpine ports: - containerPort: 8000 - name: redis image: redis:alpine ports: - containerPort: 6379 - name: webapp image: localhost:5000/newweb/webapp:latest ports: - containerPort: 8001 --- kind: Service apiVersion: v1 metadata: name: networkapp-svc spec: selector: name: networkapp_pod ports: - protocol: TCP port: 80 targetPort: 8000 type: LoadBalancer Here is the docker compose file which seems to work if I run it locally off of that, I just need this to work in kubernetes … -
Django: Why im getting NameError in shall if I have correct import in admin.py
I don't really understand why i get NameError when i try run Post.objects.all() in shell.(by using django_extensions) I made migrations and i see posts_post table on db(work fine) and i can do CRUD operations in running applicationon local server. Below is my code and error message. posts app admin.py from django.contrib import admin from .models import Post admin.site.register(Post) settings.py INSTALLED_APPS = [ ... 'django_extensions', 'posts.apps.PostsConfig' ] shell Traceback (most recent call last) Input In [1], in <cell line: 1>() ----> 1 Post.objects.all() NameError: name 'Post' is not defined -
Django comparar mi dato con todos los datos de la base de datos
Estoy tratando de realizar un trabajo en django obtengo mis datos de mi formulario y quiero validar que mi usuario este en la base de datos pero a la hora de hacer la comprobacion solo me compara la primera fila esta es mi funcion enter code here...def Agregausuario(request): t = 'AgregarUsuarios.html' s = 'index.html' if request.method == 'GET': return render(request, t) elif request.method == 'POST': Usu = request.POST.get('user').strip() password = request.POST.get('pass').strip() DatosUsuarios = models.Usuariosss.objects.all() for i in DatosUsuarios: while i.usuario == Usu: messages.success(request, 'Usuario no agregado') return render(request, t) else: conn = pymysql.connect(host='localhost',user='Telefonia',password='170195',db='monitoreodb',) cursor = conn.cursor() sql = "INSERT INTO app_usuariosss(Usuario, password) VALUES('{}', '{}')".format(Usu, password) cursor.execute(sql) conn.commit() conn.close() messages.success(request, 'Usuario agregado') return render(request, t)