Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AuditLog rows have a wrong timezone in timestamp column
I installed AuditLog according to the documentation. Changes are being logged just fine and are save to DB with the right timezone (UTC+6). But when I browse them in admin panel, they come in UTC+0 timezone. Any common ways to fix this? How to change the tz in records stored by the usage of django-auditlog in django admin panel This did not help. -
Display Output von Python subprocess in HTML
I created a website with Django. Various suprocesses are started via a Python script, from which I would like to see the output displayed on my website. This is my python script "example.py" result = subprocess.Popen(<Command>, stdout=subprocess.PIPE) Now i want to display the Output in HTML. I also dont reall know which item i should use to display. However, I don't know how this works and haven't found the right answer yet. -
AWS Lambda: deterministic=True requires SQLite 3.8.3 or higher
I have a website already hosted on AWS Lambda and testing to see if the api works. But when I run it on the website it gives me the error. NotSupportedError at /api/ deterministic=True requires SQLite 3.8.3 or higher Request Method: GET Request URL: https://2dx7zf9yt5.execute-api.us-east-1.amazonaws.com/dev/api/ Django Version: 4.2.4 Exception Type: NotSupportedError Exception Value: deterministic=True requires SQLite 3.8.3 or higher Exception Location: /var/task/django/db/backends/sqlite3/_functions.py, line 45, in register Raised during: blog_api.views.PostList Python Executable: /var/lang/bin/python3.11 Python Version: 3.11.6 Python Path: ['/var/task', '/opt/python/lib/python3.11/site-packages', '/opt/python', '/var/lang/lib/python3.11/site-packages', '/var/runtime', '/var/lang/lib/python311.zip', '/var/lang/lib/python3.11', '/var/lang/lib/python3.11/lib-dynload', '/var/lang/lib/python3.11/site-packages', '/opt/python/lib/python3.11/site-packages', '/opt/python', '/var/task'] Server time: Tue, 31 Oct 2023 12:14:06 +0000 I saw a different related question that shows me that I have to install pysqlite3, but I keep ending up with the error ERROR: Failed building wheel for pysqlite3 Even when I installed the wheel, setuptools and cmake. I am running Python3.11.3 I am hoping to learn django from this experience hosting on awls but its abit tough. -
QuerySet object has no attribute _meta showing
'QuerySet' object has no attribute '_meta' def bugtracker_add(request): if request.method == "POST": try: project_id = Project.objects.get(id=project) users_created_by = Users.objects.filter(id=request.session['user_id']).filter(~Q(status=2)) # when filtering we need to pass in array list [] it will save default in database we not passing any request.post.get. Just passing through instance how login and save id by passing array list assigned_users_id = Users.objects.get(id=assigned_to) report_users_id = Users.objects.get(id=bugtracker_report_to) bugtracker_details = BugTracker.objects.create(name=name, project=project_id, priority=priority, assigned_to=assigned_users_id, report_to=report_users_id, status=status, description=description, created_by=users_created_by[0]) bugtracker_details.save() bug_id = BugTracker.objects.get(id=bugtracker_details.id) users_updated_by = Users.objects.filter(id=request.session['user_id']).filter(~Q(status=2)) bughistory_details = BugHistory.objects.create(bug_tracker=bug_id, status=bugtracker_details.status, updated_by=users_updated_by[0]) bughistory_details.save() if bugtracker_details: sender = BugTracker.objects.filter(created_by=request.session['user_id']).filter(~Q(status=2)).filter(~Q(status=4)) assigned = Users.objects.filter(id=assigned_to) print(assigned) for ass in assigned: assign = ass.user.id print(assign) receiver = User.objects.get(id=assign) sended = bugtracker_details.created_by message = f'Hello to you assigned BugTracker by {sended.first_name}' print(message) notify.send(sender, recipient=receiver, verb='Message', description=message) except Exception as e: print(e) return redirect("pms_project:bugtracker_list") try: project_data = Project.objects.values('id', 'name').filter(~Q(status=2)) users_data = Users.objects.values('id', 'first_name').filter(~Q(status=2)) users_report_data = Users.objects.values('id', 'first_name') return render(request, 'bugtracker/add.html', {"project_id": project_data, 'users_id': users_data, 'users_report_id': users_report_data}) except Exception as e: print(e) return render(request, 'bugtracker/add.html', {}) not getting where to change in my app i am using with out app name I have stored with model name in database. when written to send notification from custom model to user model at reciptient gettting insingle instances only but. still … -
Django don't load imports
I have a trouble. One of my computers (mac) have a problem. All those imports are don't load. But another pc has no this bug Already try to reinstall vs code, it's not helped me -
Is there any way to create and save pyrogram account session using django?
I wonder, if there any way to create sessions for multiple accounts of telegram using pyrogram on Django framework. I want to create django app, that registers users and users register their own telegram accounts and use their telegram accounts to manage their chats, messages and so on. I've tried with pyrogram, but pyrogram authorizing through terminal. I should do authorizing on Django -
on django admin panal dashboard, I want to customize to display charts by using charts.js. how can i send context data to it
I am editing admin panal dashboard. I want to display charts using chart.js. but how can I send context data to the template I am overriding? -
ImportError: No module named bootstrap_form
ubuntu 16.04 python 2.7 Django 1.8 I have bootrstrap_form/ package inside project directory /app/django_jblog/settings.py INSTALLED_APPS = ( ... 'bootstrap_form' ) root@project:/app# /app/manage.py runfcgi Traceback (most recent call last): File "/app/manage.py", line 11, in <module> execute_from_command_line(sys.argv) File "/app/env/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line utility.execute() File "/app/env/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 312, in execute django.setup() File "/app/env/local/lib/python2.7/site-packages/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/app/env/local/lib/python2.7/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/app/env/local/lib/python2.7/site-packages/django/apps/config.py", line 86, in create module = import_module(entry) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) ImportError: No module named bootstrap_form directory structure: I'm running inside Docker contianer. All dependencies installed using virtualenv -
Vue.js returning blank values in the select option tag
I have this code line in my profie.html that is suppose to show the division dropdown values using vue.js v-for and {{ val.division_name }}. Instead this code returns a dropdown values that are blank, but I can tell there are values being rendered by the dropdown, it is just blank values. <select name="division_id" class="form-control form-select" id="division-id" aria-label="Default select example" v-model="formData.division_id" @change="onDivisionChange" required> <option value="0">Select Division</option> <option v-for="val in divisionListVue" :value="val.id">{{ val.division_name }}</option> </select> This is my custom-vue.js const app = Vue.createApp({ data() { return { divisionListVue: [], // Initialize divisionList with an empty array calendarListVue: [], // Initialize calendarList with an empty array formData: { division_id: 0, // Initialize division_id with 0 division_name: '', // Initialize with an empty string calendar_id: null, // Initialize calendar_id with 0 calendar_name: '', // Initialize with an empty string }, }; }, methods: { showModal() { // Show the Bootstrap modal by selecting it with its ID and calling the 'modal' method // $('#myModal').modal('show'); $("#modal1").modal('show'); // Show the modal on page load }, // Function to fetch division data fetchDivisionData() { fetch('/users/api/divisions/') // Replace with the actual API endpoint .then(response => response.json()) .then(data => { console.log(data); this.divisionListVue = data; console.log(this.divisionListVue); }) .catch(error => { … -
self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT) AssertionError: 404 != 204
I have this simple unit test class DeletePersonViewTest(TestCase): def setUp(self): self.client = APIClient() self.test_user = {'phone_number': '508304389', 'name': 'testArwa', 'password': 'testpassword'} self.user = User.objects.create_user(**self.test_user) self.client.force_authenticate(user=self.user) self.client_profile, created = ClientProfile.objects.get_or_create(user=self.user) self.test_person = {'name': 'testPerson', 'profile': self.client_profile} self.test_person_instance = Person.objects.create(**self.test_person) self.user_pk = self.test_person_instance.pk self.url = reverse('delete_persons', args=[self.user_pk]) def test_200(self): response = self.client.delete(self.url) self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT) and here is the path path('accounts/profile/delete/persons/<pk>', accountsViews.DeletePersonView.as_view(),name='delete_persons'), but I got this error self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT) AssertionError: 404 != 204 anyone can help me fixing it please ? -
Django Asyc function execution
I am trying to execute the functions in async mode using Django DRF APIView, so that the API returns the response instantly. I am using Django 4.1.12, adrf for async View. Below is the code : import asyncio from asgiref.sync import sync_to_async from adrf.views import APIView def sensitive_sync_function(): count = 0 while True: count = count + 1 print("Running in Async mode !") time.sleep(1) if count == 10: print("Processing done !") break return None class AsyncGroupManagementView(APIView): async def get(self, request, format=None): async_function = sync_to_async(sensitive_sync_function) return Response(response, status=status.HTTP_200_OK, headers=headers) The Api call executes successfully and returns response, but I am not sure if the sensitive_sync_function() executed or not as I am not able to see any logs on terminal. Do I have to explicitly execute this task later ? My end goal is to run the function in async mode, so the API response is returned and the function keeps on executing in background. Is this the correct approach or should I use celery here ? Any AWS cloud based solution for this scenario are also welcomed ! -
Django many to many field returns empty query set even after it has the the elements
this is my models.py and I add values in my admin panel and its showing values in admin panel but if I print the size_variant object it returns query set '[]'. class ColorVariant(BaseModel): color_name = models.CharField(max_length=100) price = models.IntegerField(default=0) def __str__(self) -> str: return self.color_name class SizeVariant(BaseModel): size_name = models.CharField(max_length=10) price = models.IntegerField(default=0) def __str__(self) -> str: return self.size_name class Product(BaseModel): product_name = models.CharField(max_length=100) slug = models.SlugField(unique=True,null=True,blank=True) category = models.ForeignKey(Category,on_delete=models.CASCADE,related_name="products") original_price = models.IntegerField() discounted_price = models.IntegerField() product_description = models.TextField() color_variant = models.ManyToManyField(ColorVariant,blank=True) size_variant = models.ManyToManyField(SizeVariant,blank=True) def save(self, *args, **kwargs): self.slug= slugify(self.product_name) super(Product,self).save(*args,**kwargs) def __str__(self) -> str: # return self.product_name this is my views.py def get_product(request,slug): product_obj = Product.objects.get(slug=slug) print(product_obj.size_variant.all()) product_images = ProductImage.objects.filter(product__slug=slug) return render(request,'products/product.html',{'product_images':product_images,'product_obj':product_obj}) after running this its shows "<QuerySet []>" how can I do it ?? -
How to enable right click in a new tab but normal clicking (left-click) redirects to new page using the same tab?
I am using a form in my project having multiple pages to fill information, these below are some of the items in my left side menu to switch to different pages while filling the form. So currently I am using the functionality to redirect the page on the same tab when clicking on any of these items. But when I right click, open in new window or new tab window doesn't appear. I want to enable open in a new tab only when right clicking on these items. <li id="arrival_button" class="nav-item w-100 side_bar_buttons"> <a onclick="save_and_redirect('mainform','arrival_information')" class="nav-link align-middle px-0 black_color"> <span class="ms-1 d-sm-inline">Arrival Information</span> </a </li> <li id="food_drinks_button" class="nav-item w-100 side_bar_buttons"> <a onclick="save_and_redirect('mainform', 'food_and_drinks');" class="nav-link align-middle px-0 black_color"> <span class="ms-1 d-sm-inline">Food & Drinks</span> </a> </li> <li id="guest_button" class="nav-item w-100 side_bar_buttons"> <a onclick="save_and_redirect('mainform', 'guest_req');" class="nav-link align-middle px-0 black_color"> <span class="ms-1 d-sm-inline">Guest Requirements</span> </a> </li> I already know about using target="_blank" with tags in Django but obviously like I already explained I dont want to use this functionality to always open them in a new tab only when I want to right click on them. -
Exploring the Replication of Odoo.sh Features and Building a Web Application (Django)
I'm interested in replicating the features of odoo.sh. Could anyone provide any valuable resources or links to assist in this endeavor? I've discovered a script that partially automates odoo.sh features, but I intend to create a comprehensive web application (using Python/Django) for this purpose. Is this feasible, and where should I begin? Is there a way to explore the source code of odoo.sh or gain insights into its architecture? Additionally, what other technology stack components should I be familiar with besides Python/Django, Docker, and basic cloud and system administration (e.g., Docker, AWS, etc.)? -
Real Time Search in django Rendered Templetes
Project Details:- template is rendered by using pagination in django view . I used for loop in Templete (only for tr that contains td ) to display all results within the html table. Pagination Logic is added to templete below the table tag. There are various columns in table . I want to Implement Real Time Search Functionlty to a table Rendered by django. Also , search should me made from all pages. And Only that entries should be shown which contains that string fron search box. -
makemigrations - No changes detected - Django 4.2 only
Well, I was folloging Django Girls Tutorial but using django version 4.2 All was right until I need makemigrations when I created the model. I put the new app "blog" on INSTALLED_APPS in settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog', ] Also, I don't think is necessary, but added the register on admin.py: from django.contrib import admin from .models import Post admin.site.register(Post) After adding all this content and installation, I need to execute makemigrations to generate the 0001_initial.py file migration inside ./blog/migrations directory, but it says me the following message: No changes detected Included the name of my app after the makemigrations command, and still changes were not detected I searched this error on internet and tried different migrate variations, but the only one that worked for me was the next one> ./manage.py migrate --run-syncdb Then it worked, I'm using the default django SGDB sqlite3, the database tables were created after this command and after running the server I can use the models as normal. The problem of doing this comes when I want to edit the models, I execute makemigrations and it still doesn't detect changes. The previous command --run-syncdb only works for creating the … -
Django exception process in production mode
I built a inventory management system using Django. When I sale some products, I need to check whether there are enough products in system. I rewrite save function in models.py and raise an exception when quantity is less than 0. I want to get the exception and show it in views.py. However, no details are showed on web when raising an exception. How should I do, or whether there is other method to solve my need? Here is code: # views.py def custom_exception_handler(request, exception): if isinstance(exception, ValueError): import pdb; pdb.set_trace() error_message = str(exception) return render(request, '500.html', context={'error_message': error_message}, status=500) # models.py def save(self, *args, **kwargs): obj = Stock.objects.get(id=self.stock_id.id) left_quantity = obj.quantity - self.quantity if left_quantity < 0: raise ValueError('No enough inventory') defaults = {'quantity': left_quantity, 'update_time': self.consume_time} for key, value in defaults.items(): setattr(obj, key, value) obj.save() super(RepairOutStock, self).save(*args, **kwargs) # settings.py handler500 = 'spare_parts.views.custom_error_view' # 500 error # templates/500.html <!DOCTYPE html> <html> <h2>{{ error_message }}</h2> </html> -
Nginx not working with Docker, Django and Gunicorn
I've been struggling to Dockerize an existing Django app for over a week now and I'm a bit out of ideas how to proceed. I've copied the prod environment and environment setup but I'm still struggling with the last part that is related to Nginx. I'll outline my Docker files and the YML file that brings the app to life. The Django app, the SQL DB, the Redis instance and the CRON server are all working but the last piece of the puzzle is the Nginx container. The docker-compose.yml is: version: '3.8' services: xyz_web: image: xyz-web:latest networks: - xyz_backend volumes: - ../app:/app - xyz_static:/app/static depends_on: - xyz_db - xyz_cache # ports: # - 8000:8000 command: gunicorn xyz_src.wsgi:application --bind :8000 --workers 1 --threads=3 --access-logfile - env_file: - django/.env xyz_cron: image: xyz-web:latest networks: - xyz_backend volumes: - ../app:/app depends_on: - xyz_db - xyz_cache command: cron -f env_file: - django/.env xyz_cache: image: xyz-cache:latest networks: - xyz_backend volumes: - ../build/redis/data:/data command: /bin/sh -c "redis-server --requirepass $$REDIS_CACHE_PASS" env_file: - redis/.env xyz_db: image: xyz-db:latest networks: - xyz_backend volumes: - ../build/mysql/data:/var/lib/mysql - ../build/mysql/mysqld:/var/run/mysqld ports: - 3306:3306 env_file: - mysql/.env xyz_proxy: image: xyz-proxy:latest networks: - xyz_backend volumes: - xyz_static:/app/static ports: - 8000:80 depends_on: - xyz_web networks: xyz_backend: external: … -
Django DB Query for nested models
I have 3 models in my project: User, Device and Report. A user can own several Devices and each Device will provide several Reports. I want to find the latest report for each device for the currently logged in user. My models are currently: class Device(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) device_id = models.CharField(max_length=50) device_name = models.CharField(max_length=100) def __str__(self): return self.device_id class Report(models.Model): device_id = models.ForeignKey('Device', on_delete=models.CASCADE) coordinates = models.JSONField(null=True) fill = models.IntegerField() date = models.DateTimeField() def __str__(self): return str(self.device_id) This query returns all of the Devices and their associated Reports for the logged in user: device_list = Report.objects.filter(device_id__owner__username=request.user) I'm having difficulty in filtering for only the latest report from each device. -
Assign user to a group to specific database
Does anyone know how to assign a user to a group (to a specific database)? Django offical documentation is not really clear about it. What will be the syntax in this case? from django.contrib.auth.models import User from django.contrib.auth.models import Group user = User.objects.using('db').get(pk=1) admin_group = Group.objects.using('db').get(name='admin') # Need to add this to specific database 'db' instead of default admin_group.user_set.add(user) -
ModuleNotFoundError: No module named 'shop'
I'm currently working with a e-commerce django project. After rewriting my code, I can't get to display my shop products due to a "ModuleNotFoundError". It is saying that Module 'shop' is not there but I already ensured the it is declare in the INSTALLED_APPS. Here the traceback: "Exception has occurred: ModuleNotFoundError No module named 'shop' File "C:\Users\msi\Desktop\shop_name_WebPOS_project\shop_name_webpos_project\shop\tests.py", line 4, in from shop.models import Bikes, Category, Item_Category, Gears, Parts, Services ModuleNotFoundError: No module named 'shop'" here's my code for views.py: from django.shortcuts import render, get_object_or_404 from shop.models import Bikes, Category, Item_Category, Gears, Parts, Services here's my installed apps: INSTALLED_APPS = [ 'admin_interface', 'colorfield', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'admin_site', 'authenticate', 'base_app', 'canvas', 'pos', 'shop', ] and here's for the models: from django.db import models from django.conf import settings class Category(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name class Meta: ordering = ['name'] verbose_name_plural = 'Bicycle Categories' verbose_name = 'Category' class Brands(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name class Meta: ordering = ['name'] verbose_name_plural = 'Product Brands' verbose_name = 'Brand' class Bikes(models.Model): category = models.ForeignKey(Category, related_name='items', on_delete=models.CASCADE) name = models.CharField(max_length=255) brand = models.ForeignKey(Brands, related_name='bike_brand', on_delete=models.CASCADE, null=True, blank=True) description = models.TextField(blank=True, null=True) price = models.DecimalField(max_digits=10, decimal_places=2) image = models.ImageField(upload_to='items\shop_bikes', blank=True, null=True) … -
Implementing Custom Groups and Permissions for Organization Members in Django
I'm working on a Django project where I need to implement a feature that allows each organization to create groups and assign custom permissions to the members of those groups. I want to ensure that organization administrators can create specific groups only for their organization and assign limited permissions related to the app's features. My "Organization" model is defined as follows: class Organization(models.Model): name = models.CharField(max_length=64) owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='owner_organizations') slug = models.SlugField(unique=True) pic = models.ImageField(upload_to="organizations/pics/", default='organizations/pics/default.png') I also have an "OrganizationMember" model that links users to organizations: class OrganizationMember(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='organization_memberships') organization = models.ForeignKey(Organization, on_delete=models.CASCADE, related_name='members') # Here, I want to figure out how to manage groups and custom permissions for members of each organization. I noticed that Django provides default models for groups (django.contrib.auth.models.Group) and permissions (django.contrib.auth.models.Permission), but I'm not sure how to efficiently implement this feature. How can I proceed to allow administrators of each organization to create groups and assign custom permissions to the members of those groups? I would also like to enable each member to be a part of multiple groups and have additional individual permissions. I would greatly appreciate any suggestions, guidance, or examples on how to tackle this … -
Is it possible to make Django urlpatterns from a string?
I have a list of strings that is used to define navigation pane in a Django layout template. I want to use the same list for view function names and use a loop to define urlpatterns in urls.py accordingly. Example: menu = ["register", "login", "logout"] urlpatterns = [path("", views.index, name="index"),] From the above, I want to arrive at urlpatterns = [ path("", views.index, name="index"), path("/register", views.register, name="register"), path("/login", views.login, name="login"), path("/logout", views.logout, name="logout"), ] I am able to pass the route as str and kwargs as a dict, but struggling with transforming the string into a name of a callable views function. Is this possible? for i in menu: url = f'"/{i}"' #works when passed as parameter to path() rev = {"name": i} #works when passed as parameter to path() v = f"views.{i}" #this does not work v = include(f"views.{i}", namespace="myapp") #this does not work either urlpatterns.append(path(url, v, rev)) -
Wagtailing include a inline panel (one to many) relationship within the site settings
I am looking to extend the site settings for a Wagtail Project so that the admin can add instances where they were published. That will be used to populate several places around the site, but namely the footer. I feel like my solution below is fairly janky. I seem not be be able to access the setting values in a django template or maybe I not not attacking it the right way. My approach feels like it isn't great here. Any help is appreciated! class Publication(Orderable): page: ParentalKey = ParentalKey("home.PublishedBy", on_delete=models.CASCADE, related_name='publications') name: CharField = models.CharField(max_length=100) url: URLField = models.URLField(blank=True, null=True) image: OneToOneField = models.OneToOneField(Image, related_name='+', on_delete=models.CASCADE) @register_setting class PublishedBy(BaseGenericSetting, ClusterableModel): panels: list[MultiFieldPanel] = [ MultiFieldPanel( [ InlinePanel('publications', label="Publications", min_num=1, max_num=7) ] ) ] -
How can I create a RESTful API using Python and a web framework like Flask or Django?
I'm looking to develop a RESTful API using Python, and I'm considering using web frameworks such as Flask or Django to facilitate the process. The primary goal is to expose a set of endpoints that allow clients to interact with my application over HTTP in a RESTful manner.