Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to send every specific time interval in django websocket?
When a user requests a post, the sever sends the progress of the work to the websocket When the process is finished, send a message that it is finished. Then javascript receives the message and requests to get to a specific url. The server does the filer response. The question here is how the actual service checks progress asynchronously... First of all, the code is as below. class GifConsumer(WebsocketConsumer): .... def receive(self, text_data): ... t = downloand_video.delay(data) # celery while not t.ready(): # async_to_sync(asyncio.sleep)(1) self.send(text_data=json.dumps({ 'message': "Doing" })) self.send(text_data=json.dumps({ 'message': "Done" })) The code keeps checking the status with while statements, so it seems to waste resources too much. How can I modify this? If use sleep, the web server will sleep. so, I don't think I can even request get, post. -
pass an image from views to html template without saving
in this code I tried to write on an image that is in the computer and i take a name from the user to write on the image and display it but i want to pass it to an html template without save in the database or in the disk here i use a FileResponse How could I pass it through render to an Html template this is the method in my Views.py def app(request): if request.method == "POST": res = resultImages() name = request.POST.get('name') reshaped_text = arabic_reshaper.reshape(name) bidi_text = get_display(reshaped_text) my_image = Image.open("static/images/firstTest.jpeg") #title_font = ImageFont.load_default() font = ImageFont.truetype("arial.ttf", size=32) title_text = bidi_text image_editable = ImageDraw.Draw(my_image) res.img=image_editable.text((248, 537), title_text, fill="red" ,font = font) timeNow = datetime.datetime.now().strftime('%Y%m%d%H%M%S') filename = "%s%s.jpg" % (timeNow, name) res.name = name my_image.save(filename) res.save() im = open(filename,'rb') return FileResponse(im) return render(request,'img.html') -
django restframwork Put and DELETE doesn't work
Get and post work pretty well for me . but put and delete i use "U_repo_name" to look in table i got the error message : Page not found (404) Request Method: PUT Request URL: http://localhost:8000/gitapi/repo/authoo/ Using the URLconf defined in gitit.urls, Django tried these URL patterns, in this order: admin/ gitapi/ [name='gitapi'] gitapi/ repo/ gitapi/ repo/str:U_repo_name this is my model : class UserRepos(models.Model): U_repo_name =models.CharField( max_length=50) this is my url : urlpatterns = [ path('repo/',view=userreposapi), path('repo/<str:U_repo_name>',view=userreposapi), ] this is my serializer : class UserReposSerializer(serializers.ModelSerializer): class Meta: model = UserRepos fields ='__all__' and this is my views : @csrf_exempt def userreposapi(request,id=0): if request.method=='GET': userrepos = UserRepos.objects.all() userreposserializer = UserReposSerializer(userrepos , many=True) return JsonResponse(userreposserializer.data , safe=False) elif request.method=='POST': userrepos_data=JSONParser().parse(request) userreposerializer = UserReposSerializer(data=userrepos_data) if userreposerializer.is_valid(): userreposerializer.save() return JsonResponse("added successfully!!",safe=False) return JsonResponse("failed to add",safe=False) elif request.method=='Put': userrepos_data=JSONParser().parse(request) userrepos = UserRepos.objects.get(U_repo_name=userrepos_data['U_repo_name']) userreposserializer=UserReposSerializer(userrepos,data=userrepos_data) if userreposserializer.is_valid(): userreposserializer.save() return JsonResponse("updated successfully", safe=False) return JsonResponse("failed to update",safe=False) elif request.method=='DELETE': userrepos = UserRepos.objects.all() userrepos.delete() return JsonResponse("deleted",safe=False) -
How to set up a elegant custom DB logger in Django?
How can we customize logging in Django in an elegant way? Please help . -
Getting errors when django app deploying to heroku
My code works on the local server. After deploying in Heroku, it raises some errorsimage. image -
Flutter error even when the backend (django-rest_auth) send status code 200
when I try to sign in with backend (django), the status code showed by the back end is correct : "POST /auth/login/ HTTP/1.1" 200 50 but the flutter side have an error: code Future login(String email, String password) async { final url = Uri.parse('http://localhost:8000/auth/login/'); try { print('number 1'); final response = await http.post(url, body: (<String, String>{ 'email': email, 'password': password, })); print('number 2'); print(response.statusCode); final responseData = json.decode(response.body); print(responseData.toString()); _token = responseData['key']; notifyListeners(); final userData = json.encode({ 'token': _token, }); // prefs.setString('userData', userData); } catch (error) { print("error2"); throw error; } } code can someone help me please. Thank you -
Django updates view based on database
My issue seems pretty simple but I found it difficult since I'm extremely new to HTML / CSS / Django. I have a postgresql database that is being updated continuously by another microservice. What I want to do is simply display the table in a HTML page (with https://datatables.net/ for example) and keep on updating it. I've found that we can create websocket connection when we reach the html page via channels but all the tutorial online are about chatbot. I've managed to do it via a websocket/consumer: class WSConsumer(WebsocketConsumer): def connect(self): self.accept() while True: #get the entire info from my db table info = list(infoDB.objects.value()) self.send(json...(info..)) I keep on receiving the information in my HTML page (which is what I wanted), the only problem is I'm getting EVERYTHING from the table + I'm having hard time replacing correctly the initial table with the new one. Here is my HTML page: {% load static %} <!DOCTYPE html> <html lang="En"> <head> <link rel="stylesheet" href="https://cdn.datatables.net/1.12.1/css/jquery.dataTables.min.css"> <script src="https://code.jquery.com/jquery-3.5.1.js"></script> <script src="https://cdn.datatables.net/1.12.1/js/jquery.dataTables.min.js"></script> <title>Test</title> </head> <body> <table id="table_id" class="table table-bordered" style="width:100%"> </table> <!--script> const socket = new WebSocket('ws://127.0.0.1:8000/ws/info_co/') socket.onmessage = function(e){ const data = JSON.parse(e.data); const table = document.getElementById("table_id"); for (var i = 0; i < … -
How do you read and open a file uploaded through Django FileField
I want to open files uploaded through the Django FileField. I also want to read the contents of the file and output it. I keep getting errors and don't know what to do. This is my Models.py from django.db import models from django.contrib.auth.models import User from django.core.validators import FileExtensionValidator import os class ChatModel(models.Model): sender = models.CharField(max_length=100, default=None) message = models.TextField(null=True, blank=True) thread_name = models.CharField(null=True, blank=True, max_length=50) timestamp = models.DateTimeField(auto_now_add=True) def __str__(self) -> str: return self.message class File(models.Model): title = models.CharField(max_length=100) author = models.CharField(max_length=100) doc = models.FileField(upload_to='files/docs/', validators=[FileExtensionValidator(allowed_extensions=['pdf','docx'])]) def doc_pdf(self): name, extension = os.path.splitext(self.doc.name) if 'pdf' in extension: return self.doc def doc_docx(self): name, extension = os.path.splitext(self.doc.name) if 'docx' in extension: return self.doc def __str__(self): return self.title ` -
Why won't my signal-triggered function for saving a model instance actually save?
I'm trying to get into DJango, and I'm building a simple blog website. There is a model called BlogPost: class BlogPost(models.Model): slug = None title = models.CharField(max_length = 100) content = models.TextField('Page Content') upload_date = models.DateField(auto_now = True) Usually, when there are blog posts, the posts have links that do not end in None, but I have my model this way because I want my website to automatically generate the slug based on the post's title using the following signal-triggered function: @receiver(signals.post_save,sender = BlogPost) def set_slug(sender,instance,**kwargs): if instance.slug: return instance.slug = parse.quote(instance.title) instance.save() The if-statement should change .slug to a URL-encoded version of the post's title when I save the new instance of the model in the admin site, but when I check the value of .slug, it's always None. Why is that? -
Django - media files - security
I created a Django app with Video files. I'm using Gunicorn & Nginx. A user (not root) that runs the django server. I restricted the views so only the users with correct permissions can view these. This works fine. But when watching a video, I can get the url. (../media/videos/video.mp4) And now everyone with this file-location can see the video. I'm a little lost now. Do I need to use a package like django-sendfile2’s ? Or do I need to change my server settings and limit access to the media folders ? -
django render not updating context
I am using FullCallendar (a node package) to display a calendar, I want to display data of an event in this calendar upon clicking it, which is handled by the following function: eventClick: function(info) { $.ajax({ type: 'GET', url: 'get_lesson_by_id/', beforeSend: function (xhr) { xhr.setRequestHeader("XSRF-TOKEN", $('input:hidden[name="__RequestVerificationToken"]').val()); }, data: { current_id: info.event.id }, success: function (res) { $("#signupModal").modal('show'); } }) } This sends a request to my view where I want to update the context: def get_lesson_by_id(request): lesson_id = request.GET['current_id'] lesson = get_object_or_404(Lesson, pk=lesson_id) print(lesson.to_dict()) return render(request, 'agenda/agenda.html', lesson.to_dict()) This works fine, the print in this view prints for example this when I click on an event: {'lesson_id': 2, 'lesson_title': 'Vioolbouwweek', 'lesson_begin_date': datetime.date(2022, 6, 3), 'lesson_end_date': datetime.date(2022, 6, 9), 'lesson_begin_time': datetime.time(9, 0), 'lesson_end_time': datetime.time(19, 0), 'lesson_description': 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi lobortis neque vitae tempus ullamcorper. Ut ac dolor euismod, congue tortor eu, suscipit nunc. Fusce vulputate diam condimentum sem interdum fringilla. Suspendisse vitae justo vulputate, laoreet lacus quis, mattis lectus. Mauris tincidunt sit amet velit vel ultrices. Quisque tincidunt enim eu viverra dictum. Duis malesuada hendrerit ante nec commodo. Mauris condimentum, mi id gravida pretium, ante ex mollis leo, eu elementum orci lorem molestie neque.', 'lesson_type_name': … -
Seperate login for custom user and django admin in Django
I'm currently working on a django project and I have a custom user model in my django app. Custom user authentication is working perfectly, but the issue I'm facing is whenever I'm logging into admin account in the django admin site, it logs out the previous user(let say, user2) and admin being logged in. How Can I separate their login, so that admin site logins don't interfere with my website login? Here is my code attached: Custom User model and its manager: from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class CustomerManager(BaseUserManager): def create_user(self, email, username, name, password=None): if not email: raise ValueError('Users must have an email address to register') if not username: raise ValueError('Users must have an username address to register') if not name: raise ValueError('Users must enter their name to register') user = self.model( email = self.normalize_email(email), username = username, name=name, ) user.set_password(password) user.save(using = self._db) return user def create_superuser(self, email, username, name, password=None): user = self.create_user( email = self.normalize_email(email), username = username, name=name, password=password, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class Customer(AbstractBaseUser): # user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) email = models.EmailField(max_length=254, null=True, unique=True) username = models.CharField(max_length=40, unique=True) name … -
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?