Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django calculate total hour from datatimefield
I have a model that looks something like below which has a field called datetime. This field holds the record of date and time. What I want to do is to calculate the total number of hours per month and week. I need direction on how to go about doing that. class Clockin_Transaction(models.Model): id = models.AutoField(db_column='id', primary_key=True) clockinusers = models.ForeignKey(Clockin_Users, on_delete=models.CASCADE) lid = models.IntegerField(db_column='LID', null=True, default=0) userid = models.IntegerField(db_column='UserID') temid = models.IntegerField(db_column='TemID') datetime = models.DateTimeField(db_column='DateTime', help_text='eg:2021-07-21') inout = models.IntegerField(db_column='InOut') def __unicode__(self): return self.clockinusers.name -
Django compressor is not effective
I've successfully set everything in the setting.py and when running py manage.py compress it runs without errors and I see that 2 blocks have been compressed. Here is the template: {% compress css %} <link rel="stylesheet" type="text/css" href="{%static 'project/main.css' %}"> {% endcompress %} When opening the site from the browser I see something happened (the filename changed to output.6a62b0ce8790.css and the Accept-Encoding: gzip, deflate is also shows up). However the filesize is not changing. COMPRESSION_ENABLED = True is set and I also use DEBUG = True (I don't know if it matters). -
How to see keys set by django-ratelimit in redis server?
I am using the following django==3.1.3 django-ratelimit==3.0.1 django-redis==4.12.1 djangorestframework==3.12.2 I am trying to set up a rate-limit to limit the number of times a POST request is called. I have this in my settings: CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379/1", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", }, "KEY_PREFIX": "my_app" } } I have this in views.py. (A very simplified version) @ratelimit(key='ip', rate='1/5m', method=['GET', 'POST']) def rate_limit_func(request): if request.method == 'POST': return Response(status='200') The rate limit is working as expected. But I cannot see any keys getting stored in the redis server 127.0.0.1:6379> ping PONG 127.0.0.1:6379> get ip (nil) 127.0.0.1:6379> keys * (empty list or set) I also tried searching the key using django shell >>> from django.core.cache import cache >>> 'ip' in cache False I am not sure if I have set this up correctly and it will work in production. Also, where are the cache values being set? -
Django Object gets created twice
So I have a big app and was able to find out where the "error" is located (That's why I don't need to upload more of my code) image_model = Image_model( user = user, lan = lan, lon = lon, width = width, height = height, image_name = image_name, image_name_preview = image_name_preview, image = original_image, preview_image = preview_image, whatisseen = whatisseen, timestamp_create = timestamp_create ) image_model.save() RoomChatMessage.objects.create( room = room, user = user, content = message, image = image_modal, ) payload = {"Success": "Message successfully added"} So when I call the function around the two objects the image object is created and after that the RoomChatMessage object. But now I have a problem: When I commend the image_modal out (the full object) and only create the RoomChatMessage (without the image) it works fine. But if I call the function like this I get one Image Object and two Message Objects - but why? -
How to get category id and display the product which is under the category in django
Here is my models.py. from django.db import models # Create your models here. class Category(models.Model): cateId = models.AutoField(primary_key=True) cateName = models.CharField(max_length=200) def __str__(self): return self.cateName class Product(models.Model): prodCategory = models.ForeignKey(Category, on_delete=models.CASCADE) prodId = models.AutoField(primary_key=True) prodName = models.CharField(max_length=200) def __str__(self): return self.prodName views.py from django.shortcuts import render, get_object_or_404 from product.models import Category, Product def category(request, *args, **kwargs): category = Category.objects.all() ctx = {'category': category} return render(request, 'category.html', ctx) def category_product(request, cateId, *args, **kwargs): product = Product.objects.get(prodCategory=cateId) ctx = {'product': product} return render(request, 'product.html', ctx) urls.py path('category/<int:cateId>/', views.category_product, name='category_product') this is my product which is after i click the category link product.html <body> <div class="container"> {% for product in product %} <a href="#"> <div class="product"> <h2>{{ product.prodName }}</h2> </div> </a> {% endfor %} </div> </body> here is my category page which give a clickable link to view the product which is under this category. category.html <div class="container"> {% for category in category %} <a href="#"> <div class="category"> <h2>{{ category.cateName }}</h2> </div> </a> {% endfor %} </div> -
How to access user profile in templates Django
How do you access user profile model in template. I have related name set to "profile", and I use {{user.profile.id}} and it returns nothing. -
Django Admin CSS not loading up
Iam trying to get my Django admin to have the css as it look in development, but nothing seems to work for me. I tried following things: Have following static value in settings.py # Default primary key field type # https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' STATICFILES_DIRS = [os.path.join(BASE_DIR,'staticfiles')] STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/' Add mimetypes.add_type("text/css", ".css", True). Since the console error was showing "Refused to apply style from 'https://example.org/admin/login/?next=/static/admin/css/base.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled." I ran python manange.py collectstatic. (Admin static files are available in static folder as well). I set Debug=False as well I cant figure out the problem. Any ideas are welcome. Thanks in advance -
How to display multiple images in a django template img element
I am having a challenge displaying multiple images users post to one img template element, for one reason if i try fetching images with the default related name it wouldn't show in the template and i wonder what i am doing wrong. Can anyone be of help! Here is my model for post. class Post(models.Model): page = models.ForeignKey(Page, on_delete=models.CASCADE, related_name="page") username = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE ,related_name="page_user") description = models.TextField(max_length=500, blank=True) video = models.FileField(upload_to="PageVideos", blank=True) pic = models.ImageField(blank=True) date_posted = models.DateTimeField(auto_now_add=True) tags = models.CharField(max_length=100, blank=True) class Mete: ordering = ['-date_posted'] def __str__(self): return self.description class PostImage(models.Model): #page = models.ForeignKey(Page, on_delete=models.CASCADE, related_name="pg") post = models.ForeignKey(Post, default=None, on_delete=models.CASCADE) images= models.ImageField(upload_to="postimages/") Here is my Detail view def page_detail(request,id): post = get_object_or_404(Post, id=id) photos = PostImage.objects.filter(post=post) context = { 'post':post, 'photos':photos } return render(request, 'page/detail.html',context) These my Template to display users images <div class="p-3 border-b dark:border-gray-700"> {{ post.description }} </div> <div uk-lightbox> <div class="grid grid-cols-2 gap-2 p-2"> {% for p in photos.images_set.all %} <a id="images" href="{{ p.images.url }}" class="col-span-2" > <img src="{{ p.images.url }}" alt="" class="rounded-md w-full lg:h-76 object-cover"> </a> <a href=""> <img src="" alt="" class="rounded-md w-full h-full"> </a> <a href="" class="relative"> <img src="" alt="" class="rounded-md w-full h-full"> <div class="absolute bg-gray-900 bg-opacity-30 flex justify-center items-center text-white rounded-md … -
How to see the logs of django-docker deployed on digitalocean via github
I deployed my django docker via GitHub actions to Digital Ocean. How can I see the logs since I am not able to see my django live on the link? -
How to fetch clients id and clients secret key in models using django for social media login
Hey how to fetch user credentials from database models for Facebook login in django. And how to get token_access of Facebook graph API for each user -
How to deploy flutter web with Django?
when I build flutter web app : flutter build web I want to deploy this with dango server, what should i do? thanks !! -
Django FileResponse through nginx error ERR_RESPONSE_HEADERS_MULTIPLE_CONTENT_DISPOSITION
django use FileResponse and runserver in 8000 port. # this add Content-Disposition header in response response = FileResponse(file, filename="file.txt", as_attachment=True) nginx proxy_pass to django: location /api/v1/download { proxy_pass http://127.0.0.1:8000; proxy_set_header X-Forwarded-Proto $scheme; 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; } when I access django directly, I download file successfully, but when I access django through nginx, chrome throw error ERR_RESPONSE_HEADERS_MULTIPLE_CONTENT_DISPOSITION. Use curl to send request to django directly: curl -v http://django:8000 < HTTP/1.1 200 OK < Server: WSGIServer/0.2 CPython/3.9.2 < Content-Type: application/octet-stream < Content-Disposition: attachment; filename="filename.txt" # django add < Vary: Accept, Cookie < Allow: GET, HEAD, OPTIONS < X-Content-Type-Options: nosniff < Referrer-Policy: same-origin < Connection: close Use curl to send request to nginx, it shows duplicate Content-Disposition response header: curl -v https://nginx < HTTP/1.1 200 OK < Server: nginx/1.20.1 < Date: Mon, 04 Oct 2021 16:39:01 GMT < Content-Type: application/octet-stream < Transfer-Encoding: chunked < Connection: keep-alive < Content-Disposition: attachment; filename="filename.txt" # django add < Vary: Accept, Cookie < Allow: GET, HEAD, OPTIONS < X-Content-Type-Options: nosniff < Referrer-Policy: same-origin < Content-Disposition: “attachment” # nginx add Why nginx auto Content-Disposition: "attachment" In response header? Is there some way to avoid this? -
How to do nested Group By with django orm?
I have the following data: publisher title -------------------------- ----------------------------------- New Age Books Life Without Fear New Age Books Life Without Fear New Age Books Sushi, Anyone? Binnet & Hardley Life Without Fear Binnet & Hardley The Gourmet Microwave Binnet & Hardley Silicon Valley Algodata Infosystems But Is It User Friendly? Algodata Infosystems But Is It User Friendly? Algodata Infosystems But Is It User Friendly? Here is what I want to do: I want to count the number of books published by each author in a single object. I want to get the following result: {publisher: New Age Books, titles: {Life Without Fear: 2, Sushi Anyone?: 1}}, {publisher: Binnet & Hardley, titles: {The Gourmet Microwave: 1, Silicon Valley: 1, Life Without Fear: 1}}, {publisher: Algodata Infosystems, titles: {But Is It User Friendly?: 3}} My solution goes something along the lines of: query_set.values('publisher', 'title').annotate(count=Count('title')) But it is not producing the desired result. -
multiple websocket instances for chat application
I'm building a Django-Vue chat applicaton, I already builded the core functionallity of the app. When the SideBar component is mounted a HTTP request is maded to get all rooms that the user is a participant, when some room is clicked a WebSocket instance is created on the Chat component. My doubt is, if I send a message to that room but the others users are not connected in the same room (suposse that they are connected in other room) they will not receive the message right? So how I send him a notification about the new message? like Whatsapp sidebar notifications. I was thinking in create two WebSocket connections, one on the SideBar that will be the user endpoint (ws:127.0.0.1:8000/chat/$Username) and other for the actually chat room (ws:127.0.0.1:8000/chat/$ChatId), is that a good approach? My django models => from django.db import models from account.models import CustomUser class Message(models.Model): sender = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='messages') message = models.TextField() created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return f'message from {self.sender.username}' class Chat(models.Model): name = models.CharField(max_length=24) participants = models.ManyToManyField(CustomUser, blank=True) messages = models.ManyToManyField(Message, blank=True) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name -
Can you break a for loop in django?r
{% if user.is_authenticated %} {% for robot in object_list %} {% if user.id == robot.username.id %} <div style="color: #3b2063; outline: 3px solid #3b2063;"> <ul> <li><a href="{% url 'robot-detail' robot.pk %}"><h1>{{ robot.name }} - Current Status: {{ robot.current_status }} - Current Path: {{ robot.path_options }}</a></li> </ul> </ul> <hr> </div> {% else %} <h1>You have no robots.</h1> {% endif %} {% endfor %} {% else %} <div style="color: #3b2063; outline: 3px solid #3b2063;"> <ul> <li><H1><a href="{% url 'login' %}"> Log in </a> to get started.</h1></li> </ul> <hr> </div> {% endif %} where it says you have no robots. it runs the the amount of robots there are in object_list, i was thinking that i could break the for loop right after the any suggestions? -
How to retrieve the ids from the array of objects using python and django?
Hi i have an array of objects like below, const arr_obj = [ { 'id': 1, 'items': [ { 'id':'1', 'data': { 'id': 3, } }, { 'id': '2', 'data': { 'id': 4, } } ] }, { 'id': 2, 'items': [ { 'id':'3', 'data': { 'id': 5, } }, ] }, ] I want to retrieve the id property of items array and put it an array so the expected output is ['1','2','3'] below code works in javascript arr_obj.map(obj=>obj.items.map(item=>item.id)).flat() how can i do the above in python and django. could someone help me with this. I am new to python and django thanks. -
django "Field 'id' expected a number but got 'yoavlv'."
I want to create a page where the user can see the details he posted on the site. The problem I get "Field 'id' expected a number but got 'yoavlv'." I already searched for solution and try to solve it with "slug" but it didn't work.. def my_items(request, user): user_items = get_object_or_404(Add_Item, user=user) items = Add_Item.objects.filter(user =user_items) return render(request, 'my_items.html',{"items":items,}) model : class Add_Item(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE, default=None, null=True) title = models.CharField(max_length=255) categories = models.CharField(max_length=255 , choices=all_categories) description = RichTextField(blank=True,null=True) condition = models.CharField(max_length=100, choices=cond) city = models.CharField(max_length=50, choices=cy.city, blank=True) street = models.CharField(max_length=100, blank=True) home_number = models.CharField(max_length=100, blank=True) header_img = models.ImageField(null=True, blank=True, upload_to='img/') more_img = models.ImageField(null=True, blank=True, upload_to='img/') Pub_date = models.DateField(auto_now_add=True) -
Django admin form raises IntegrityError for model with conditional UniqueConstraint
I was asked to add some logic to model uniqueness. Each Payment must have either transaction_id or payment_id filled. Each Payment is identificated by (transaction_id, operation, payment_created_date) or (payment_id, operation, payment_created_date). On database level this works fine. Inserting Payment with same transaction_id, operation, payment_created_date twice causes unique constraint violation. For this model i created admin page. But inserting same row with admin page causes IntegrityError at /admin/finance/payment/add/ duplicate key value violates unique constraint "unique_finance_payment_without_payment_id" DETAIL: Key (transaction_id, operation, payment_created_date)=(dasdasd, Refund, 2021-10-04) already exists. instead of simple user-friendly admin error Please correct the error below. Payment with this Transaction id, Operation and Payment created date already exists. How to make Django admin catch this IntegrityError and show it in admin form? here is my models.py class ReportName(DiModel): name = CharField( max_length=50, blank=False, null=False) def __str__(self): return self.name class Payment(DiModel): class Meta: unique_together = ('transaction_id', 'payment_id', 'operation', 'payment_created_date') constraints=[UniqueConstraint(fields=['transaction_id', 'operation', 'payment_created_date'], condition=Q(payment_id=None), name='unique_finance_payment_without_payment_id'), UniqueConstraint(fields=['payment_id', 'operation', 'payment_created_date'], condition=Q(transaction_id=None), name='unique_finance_payment_without_transaction_id'),] OPERATION_TYPE = [ ('Refund', 'Refund'), ('Charge', 'Charge'), ] CURRENCY_CODE = [ ('EUR', 'EUR'), ('RUB', 'RUB'), ('USD', 'USD'), ('GBP', 'GBP'), ('AUD', 'AUD'), ('PLN', 'PLN'), ('SGD', 'SGD'), ('MYR', 'MYR'), ('RON', 'RON'), ('ZAR', 'ZAR'), ] report_name = ForeignKey(ReportName, on_delete=models.PROTECT, blank=False, null=False, help_text="Processor and report type") operation = … -
Django show image list in table from ManyToMany field
I have created a model to have details of job vacancy. The job model has the following fields: class Job(models.Model): job_position = models.ForeignKey(Position, on_delete=models.PROTECT, related_name='job_position') applicants_to_hire = models.IntegerField(null=True, blank=True, validators=[MinValueValidator(1), MaxValueValidator(15)], default=1) hiring_team = models.ManyToManyField(Employee, related_name='hiring_team') class JobListView(LoginRequiredMixin, ListView): model = Job template_name = 'recruitment/job_list.html' context_object_name = 'job_list' I want to use the hiring_team in a template to show image of each employee (circle avatar), and those images come from the employee model: class Employee(models.Model): image = models.ImageField(blank=True, default='blank_profile_picture.jpg') I've managed to display all images, but they are not in the same table cell, and they add additional table columns: <tbody> {% for job in job_list %} <tr> <td><span class="employee-table-name"><a href="{% url 'recruitment:job_detail' pk=job.pk %}">{{ job.job_position }}</a></span></td> <td>{{ job.applicants_to_hire }}</td> {% for team in job.hiring_team.all %} {% if team.image %} <td><img src="{{ team.image.url }}" class="rounded-circle img-fluid-80" alt="{{ team }}"></td> {% endif %} {% endfor %} <td>{{ job.job_priority }}</td> <td>{{ job.job_status }}</td> <td>{{ job.created|date:"M d, Y" }}</td> </tr> {% endfor %} </tbody> How can I "concatenate" them to display something like the screenshot below: -
Why am I getting TypeError string indices must be integers in this API call? (seeding Django DB)
I am trying to seed a django DB from an external API using this guide (https://medium.com/@chilinski.a/how-to-seed-a-django-api-with-data-from-an-external-api-b577b6e6ad54). I have replicated the code accurately for my own project, I think, but get a TypeError: string indices must be integers when i run python manage.py seed and am not sure why. Here's my code: import requests from django.core.management.base import BaseCommand from nrel_app.models import Nrel def get_nrel(): url = 'https://developer.nrel.gov/api/utility_rates/v3.json?api_key=DEMO_KEY&lat=35.45&lon=-82.98' r = requests.get(url, headers={'Content=Type': 'nrel_app/json'}) Nrels = r.json() return Nrels def seed_nrel(): for i in get_nrel(): Nrels = Nrel( utility_name = i['utility_name'], company_id = i['company_id'], utility_info =i['utility_info'], residential = i['residential'], commercial = i['commercial'], industrial = i['industrial'], ) Nrels.save() class Command(BaseCommand): def handle(self, *args, **options): seed_nrel() print("Completed.") -
Create new RT table in Django SphinxSearch
I have a django site running with sphinxsearch and am having trouble creating a new RT table. I have previously added columns to RT tables using the steps: sudo service sphinxsearch stop Delete the data in var/lib/sphinxsearch Add the field to sphinx.conf sudo service sphinxsearch start After that the new column appears in mysql, and I can confirm it by connection to the DB directly. However, I have now created a full new table, but when I run the same steps, the data file for the new table as well as the table itself are not being created. I have tried to manually go into Mysql to create the table but have had no luck. Most of the sphinx documentation is not RT table based and I'm having trouble finding how to create this... When I try to run a logdebug following, I receive an error saying that the "table_name.lock" file does not exist. The formatting can't be wrong because when it was I received errors simply running sudo sphinxsearch start...so am not sure where to go from here. Thank you! Additional detail: This new table is also part of a new django app, so the sphinx.py file in the … -
Connect ZKTECO device from hosted django Site gives an error
I have created a site that connect ZKTECO K40 device. The connection Method is pretty simple from zk import ZK, const zk = ZK('192.168.1.13', port=4370, timeout=5) conn = zk.connect() This makes a connection while running from a local host connecting in the same network But after hosting the site. The site is not able to ping to the device and can't connect the device. How can i connect to the device connected on pc local network from hosted django site. I have hosted my site on Cpanel. enter image description here -
Sending emails with EmailMessage does not work when I deploy my application
I am developing an application with django. When I send emails locally with EmailMessage it works, but after deployment on heroku it doesn't work anymore. Here is the code in views.py from django.template.loader import render_to_string message = render_to_string("elec_meter/activate_email.html", { "user": user, "domaine": request.META['HTTP_HOST'], "uid": urlsafe_base64_encode(force_bytes(user.id)), "token": default_token_generator.make_token(user), "password": password,"matricule": agent.matricule } ) email_to_send = EmailMessage("Activation du compte", message, to=[email]) email_to_send.send() in settings.py EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" EMAIL_HOST = "smtp.gmail.com" EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST_USER = "my_email" EMAIL_HOST_PASSWORD = "password" EMAIL_USE_SSL = False I need help please -
Saving previous date and adding new date in Django
I have been working on an application where user adds his tasks which he is supposed to perform, once the task is added he can update the progress. In my model I have a date field, where user is supposed to enter the estimated completion date. My task model """Creating KRA Based on Institutional Objectives""" class KraBasedOnIo(models.Model): io = models.ForeignKey(InstitutionalObjectives, on_delete=models.CASCADE, related_name='kra_io') kra_title = models.CharField(max_length = 200) kra_description = models.TextField() kra_target = models.CharField(max_length=200) kra_added_date = models.DateTimeField(auto_now_add=True) estimated_date = models.???? While updating the progress, if the user wants to extend his timeline, I am looking for an option where I can save his current estimated completion date and add the new date also. And when I am displaying his progress I want to show his defined completion date and also the extended completion date in the template. I have tried a work around with model.JSONField() but couldn't reach there. There is no ListField or DictionaryField so what could be a better solution for this? -
How can I Restrict Users on OTT Platform (Like 3 Stream/Account) [Device Limitation]
I'm working on a OTT Platform For API using Django Rest Framework & for Website React & for App React Native. I'm trying to add Device limitation on account like 3 user can watch at a same time per account. How can I do it?