Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Query Annotation Does Not Support math.tan() Calculation
I have a django 3.2/mysql website. One of the tables, Flights, has two columns, angle and baseline. These two columns are combined in a view to display the value altitude using the formula altitude = baseline * tan(angle). I am building a search form for this table, and the user wants to search for flights using a minimum altitude and a maximum altitude. My normal approach to the problem is to gather the inputs from the search form, create appropriate Q statements, and use query the table with filters based on the Q statements. However, since there is no altitude field, I have to annotate the query with the altitude value for the altitude Q statement to work. It seems that a query annotation cannot use an expression like math.tan(field_name). For example, Flights.objects.annotate(altitude_m=ExpressionWrapper(expression=(F('baseline') * math.tan(F("angle"))), output_field = models.FloatField(),),) generates the error builtins.TypeError: must be real number, not F whereas the expression Flights.objects.annotate(altitude_m=ExpressionWrapper(expression=(F('baseline') * F("angle")), output_field = models.FloatField(),),) does not generate an error, but also does not provide the correct value. Is there a way to annotate a query on the Flights table with the altitude value so I can add a filter like Q(altitude__gte= min_altitude) to the query? Or, is … -
How to customize AdminPanel of django rest such as admin can see full details of Model having one to many relationship?
I want to allow the admin to see the full detail of BusinessAccountModel and can edit the is_approve field as Approved, pending, Not Selected. But the problem is that BusinessAccountModel has one to many relationships with WorkSamplesModel. WorkSamplesModel has images. How to display BusinessAccountModel and its WorkSamplesModel details in AdminPanel together on single page. class BusinessAccountModel(models.Model): business_title = models.CharField(max_length=70) business_description = models.CharField(max_length=500) status = models.CharField(max_length=100) note = models.CharField(max_length=200) is_approved = models.CharField(max_length=15, choices=IS_APPROVE_CHOICES,default='Pending') user = models.OneToOneField(UserModel,on_delete=models.CASCADE) class Meta: db_table = 'wp_business_acc' class WorkSamplesModel(models.Model): work_sample_image = models.ImageField(blank=True,null=True,upload_to="work_samples") work_sample_description = models.CharField(max_length=1000) is_business_card_image = models.BooleanField(default=False) business_account = models.ForeignKey(BusinessAccountModel,on_delete=models.CASCADE) class Meta: db_table = 'work_samples' I try the following code from django.contrib import admin from .models import BusinessAccountModel class BusinessAccountAdmin(admin.ModelAdmin): list_display = ['id','business_title','business_description','status','note','is_approved'] list_editable = ('is_approved',) list_per_page = 4 search_fields = ('business_title',) list_filter = ('is_approved',) admin.site.register(BusinessAccountModel,BusinessAccountAdmin) How to customize AdminPanel as admin can see BusinessAccountModel full details and its WorkSampleModel can change is_approve field of BisinessAccountModel? -
How to let <input type='date'>, display as yyyy.mm.dd? [duplicate]
For example: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/date with value={% now 'Y-m-d' %}, it displays as 04/06/2022 would it be possible for the date-picker to display as 2022.06.04? Thanks! -
Reciveing an error while downloading a package gunicorn
ERROR: Could not install packages due to an OSError: [WinError 2] The system cannot find the file specified: 'C:\Python310\Scripts\gunicorn.exe' -> 'C:\Python310\Scripts\gunicorn.exe.deletem -
how do make a query for this issue ? in django
I'm having a 2 models Zone and DailyTask So I want to make a table in the front end(HTML) that like image is shown below. U is used_tasks UN is unused_tasks T total_tasks I want list this data for each zones for the currusponding timeslots this is my current code model one Zone class DailyTask(models.Model): date = models.DateField() zone = models.ForeignKey(Zone, on_delete=models.SET_NULL, null=True) slot = models.ForeignKey(GeneralTimeSlot,related_name='daily_task', on_delete=models.CASCADE) total_tasks = models.IntegerField(default=0) used_tasks = models.IntegerField(default=0) unused_tasks = models.IntegerField(default=0) available_driver_slots = models.ManyToManyField(DriverTimeSlot) model two Zone class Zone(models.Model): name = models.CharField(max_length=200) coordinates = models.TextField(null=True, blank=True) time slot view.py def get(self, request, *args, **kwargs): zones = Zone.objects.all() today = datetime.date.today() daily_task = DailyTask.objects.filter(date="2022-06-04") return render(request, self.template_name, {'zones': zones, 'daily_tasks': daily_task}) template timeslotreport.html {% extends 'macro-admin/base.html' %} {% load crispy_forms_tags %} {% block title %} <title>Time Slot Report</title> {% endblock %} {% block content %} <style type="text/css"> table { border-collapse: collapse; width: 100%; } td, th { text-align: left; padding: 8px; } tr:nth-child(even) { background-color: #dddddd; } .button1 button{ border: 2px solid #3783b5; border-radius: 5px; padding: 5px 15px; margin: 2px 0; background-color: white; width: 80px; } .under{ text-decoration:underline; } .order2 .card-title{ font-size: 25px!important; } .order2 button{ float: right; padding: 10px 80px!important; } .marg{ padding-top: 50px; } … -
How to rank query results when using Q objects in Django
I am building an jobs database using Django. The user should be able to search for an jobs using its title,and its company, etc. I am currently using Q Objects to construct the query: if keyword: q=Q() qs = stemming(keyword) for key in qs: q &= Q(title__iregex = r'\b{}.*\b'.format(key))|Q(company__iregex=r'\b{}.*\b'.format(key)) jobs_list = jobs_list.filter(q).distinct() jobs_count = jobs_list.count() jobs_list = jobs_list.order_by('-title') I would like to order the results by relevance. As far as I understand this is usually accomplished by using annotate(): A ranking number is set and then used by order_by(). However, I am not sure how to do this when using Q objects. Is it possible to "annotate" Q objects? Or am I barking up the wrong tree here? Maybe someone can help, Thank you.. -
Django filter tasks done in project ListView
I have ListView of projects that has tasks i want to calculate progress % of each project i have made it like this code bellow but the progress calculate all tasks even that is not related to project haw can i do it for the tasks that is related to the project Preview image class ClientProjectView(LoginRequiredMixin, SuccessMessageMixin, ListView): model = Project template_name = 'project/list.html' def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) context['tasks'] = Task.objects.all() if Task.objects.exists(): task_done = Task.objects.filter(is_done='3', project_id__in=self.object_list).count()* 100 / Task.objects.filter(project_id__in=self.object_list).count() context['percentage_done'] = task_done else: context['percentage_done'] = '0' return context -
Two foreign key's : how to select one foreign key data that has relation to another foreign key
I've two tables User and Shop.Then I've create third table which has username_id(from table User) and shopname_id(from table shop) as foreign keys.When I search a shopname_id it should display a table in front-end that has username_id that(that is the username_id has access to that particular shop)relates with searched shopname_id( data fetch from third user-shop-mapping table) How to write it's queryset in view. -
View and CSS are not updated on mobile after I modify an element classlist with javascript
So for some context, I have a portfolio page with some projects which I can filter by tags. The CSS (color) of the tags change when it's selected/deselected, by adding/removing a selected class to the element. But somehow a selected tag doesn't go back to it's initial state when it's clicked a second time, even though the class list is correctly updated. This happens only on mobile (I could test on Android and iOS), the behavior is the one expected on desktop. The page is rendered with Django, and the HTML and JavaScript look like this: {% extends './base.html' %} {% load static %} {% block title %}Pierre Bonneau - Portfolio{% endblock title %} {% block content %} <main class="container flex-shrink-0"> <!-- TAGS --> <div class="tag-list text-center"> <ul> <li class="project-tag selected" data-filter="All">All</li> {% for tag in tags %} <li class="project-tag" data-filter="{{tag.name}}">{{tag.name}}</li> {%endfor%} </ul> </div> <!-- GALERY --> <div class="project-grid"> {% for project in project_list %} <div class="project-card" data-tags="{%for tag in project.tags.all%}{{tag.name}}, {%endfor%}"> <img src="{{ project.thumbnail.url }}" class="img-fluid w-100 h-100" alt="{{ project.project_name }} thumbnail"> <div class="project-text"> <a href="{{project.gitlab_link}}"> <h4>{{project.project_name}}</h5> <p>{{project.description}}</p> </a> </div> </div> {%endfor%} </div> <div id="no-project" class="hidden">There is no project of this type.</div> </main> {% endblock content %} {%block scripts%} … -
Using Django to add and modify an existing table in mssql
Im trying to use django to create a webpage that allows people to register themselves my django is connected to a local ms sql server and the login is correct my users table that is from BooksDataBase has the following columns with these coditions: the login column is the primary key with auto increment option and the value always start above 1000 and it will filled whenever a user is created(we dont need to fill that manuall) my 1st problem is when i order django to return the value of this table it returns with only login table with a different name: Users.objects.all() <QuerySet [<Users: Users object (1000)>, <Users: Users object (1001)>, <Users: Users object (1002)>]> my Models.py : class Admins(models.Model): adminid = models.IntegerField(db_column='AdminID', primary_key=True) # Field name made lowercase. adminlogin = models.CharField(db_column='AdminLogin', max_length=254, db_collation='SQL_Latin1_General_CP1_CI_AS', blank=True, null=True) # Field name made lowercase. usersecret = models.CharField(max_length=254, db_collation='SQL_Latin1_General_CP1_CI_AS', blank=True, null=True) class Meta: db_table = 'Admins' class Books(models.Model): uid = models.AutoField(db_column='UID', primary_key=True) # Field name made lowercase. bookname = models.CharField(db_column='BookName', max_length=255, db_collation='SQL_Latin1_General_CP1_CI_AS', blank=True, null=True) # Field name made lowercase. author = models.CharField(db_column='Author', max_length=255, db_collation='SQL_Latin1_General_CP1_CI_AS', blank=True, null=True) # Field name made lowercase. category = models.CharField(db_column='Category', max_length=255, db_collation='SQL_Latin1_General_CP1_CI_AS', blank=True, null=True) # Field name made lowercase. … -
django Pagination dosent show up
am trying to get Pagination to work on my django blog. I got pagination to work on my home.html but when i want it on my categories.html the code dosent work. Any ideas why it works on home.html but not on categories.html? I think this is the only files that you need to look at if am wrong ask me and i post more. Would be really glad with some help on this one. APP location views.py from django.shortcuts import render, get_object_or_404 from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView from .models import Post, Category, Comment from .forms import PostForm, EditForm, CommentForm from django.urls import reverse_lazy, reverse from django.http import HttpResponseRedirect def LikeView(request, pk): post = get_object_or_404(Post, id=request.POST.get('post_id')) liked = False if post.likes.filter(id=request.user.id).exists(): post.likes.remove(request.user) liked = False else: post.likes.add(request.user) liked = True return HttpResponseRedirect(reverse('article-detail', args=[str(pk)])) class HomeView(ListView): model = Post template_name = 'home.html' cats = Category.objects.all() ordering = ['-post_date'] paginate_by = 5 def get_context_data(self, *args, **kwargs): cat_menu = Category.objects.all() context = super(HomeView, self).get_context_data(*args, **kwargs) context["cat_menu"] = cat_menu return context def CategoryListView(request): cat_menu_list = Category.objects.all() return render(request, 'category_list.html', {'cat_menu_list':cat_menu_list}) def CategoryView(request, cats): category_posts = Post.objects.filter(category=cats.replace('-', ' ')) return render(request, 'categories.html', {'cats':cats.replace('-', ' ').title(), 'category_posts':category_posts}) class ArticleDetailView(DetailView): model = Post template_name = … -
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.