Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do i Fix this django.db.utils.DatabaseError
How do i fix Django Database error. I'm using MongoDB with Djongo. Everything was working fine until recently. When it tested it after some days, it doesnt work. i am able to use get method without error, but when i request a post mehtod , i get this django.db.utils.DatabaseError. Internal Server Error: /category Traceback (most recent call last): File "/Users/sangeethsivan/opt/anaconda3/lib/python3.9/site-packages/djongo/cursor.py", line 51, in execute self.result = Query( File "/Users/sangeethsivan/opt/anaconda3/lib/python3.9/site-packages/djongo/sql2mongo/query.py", line 784, in init self._query = self.parse() File "/Users/sangeethsivan/opt/anaconda3/lib/python3.9/site-packages/djongo/sql2mongo/query.py", line 876, in parse raise e File "/Users/sangeethsivan/opt/anaconda3/lib/python3.9/site-packages/djongo/sql2mongo/query.py", line 857, in parse return handler(self, statement) File "/Users/sangeethsivan/opt/anaconda3/lib/python3.9/site-packages/djongo/sql2mongo/query.py", line 928, in _insert query = InsertQuery(self, self.db, self.connection_properties, sm, self._params) File "/Users/sangeethsivan/opt/anaconda3/lib/python3.9/site-packages/djongo/sql2mongo/query.py", line 340, in init super().init(*args) File "/Users/sangeethsivan/opt/anaconda3/lib/python3.9/site-packages/djongo/sql2mongo/query.py", line 62, in init self.parse() File "/Users/sangeethsivan/opt/anaconda3/lib/python3.9/site-packages/djongo/sql2mongo/query.py", line 410, in parse self._fill_values(statement) File "/Users/sangeethsivan/opt/anaconda3/lib/python3.9/site-packages/djongo/sql2mongo/query.py", line 368, in _fill_values raise SQLDecodeError djongo.exceptions.SQLDecodeError: Keyword: None Sub SQL: None FAILED SQL: ('INSERT INTO "RentApp_category" ("type") VALUES (%(0)s)',) Params: (['Wardrobes'],) Version: 1.3.6 The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Users/sangeethsivan/opt/anaconda3/lib/python3.9/site-packages/django/db/backends/utils.py", line 89, in _execute return self.cursor.execute(sql, params) File "/Users/sangeethsivan/opt/anaconda3/lib/python3.9/site-packages/djongo/cursor.py", line 59, in execute raise db_exe from e djongo.database.DatabaseError The above exception was the direct cause of the following exception: … -
Why am I getting this error when trying to use postgis
When I'm making migrations, I get this error. (project) PS D:\University\FYP\final_project\land_management_system> python manage.py makemigrations Traceback (most recent call last): File "D:\University\FYP\final_project\land_management_system\manage.py", line 22, in <module> main() File "D:\University\FYP\final_project\land_management_system\manage.py", line 18, in main execute_from_command_line(sys.argv) File "D:\University\FYP\final_project\project\Lib\site-packages\django\core\management\__init__.py", line 442, in execute_from_command_line utility.execute() File "D:\University\FYP\final_project\project\Lib\site-packages\django\core\management\__init__.py", line 416, in execute django.setup() File "D:\University\FYP\final_project\project\Lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "D:\University\FYP\final_project\project\Lib\site-packages\django\apps\registry.py", line 124, in populate app_config.ready() File "D:\University\FYP\final_project\project\Lib\site-packages\django\contrib\admin\apps.py", line 27, in ready self.module.autodiscover() File "D:\University\FYP\final_project\project\Lib\site-packages\django\contrib\admin\__init__.py", line 52, in autodiscover autodiscover_modules("admin", register_to=site) File "D:\University\FYP\final_project\project\Lib\site-packages\django\utils\module_loading.py", line 58, in autodiscover_modules import_module("%s.%s" % (app_config.name, module_to_search)) File "C:\Program Files\Python311\Lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1204, in _gcd_import File "<frozen importlib._bootstrap>", line 1176, in _find_and_load File "<frozen importlib._bootstrap>", line 690, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 940, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "D:\University\FYP\final_project\land_management_system\core\admin.py", line 3, in <module> from django.contrib.gis.admin import OSMGeoAdmin ImportError: cannot import name 'OSMGeoAdmin' from 'django.contrib.gis.admin' (D:\University\FYP\final_project\project\Lib\site-packages\django\contrib\gis\admin\__init__.py) Here's imports from my admin code: from django.contrib import admin from .models import User, Land, LandTransfers, NFTs, AuthTokens, TaxesFees from django.contrib.gis.admin import OSMGeoAdmin I've tried adding custom path for GEOS and GDAL in settings, still it didn't help: GDAL_LIBRARY_PATH = r"C:\OSGeo4W\bin\gdal308.dll" GEOS_LIBRARY_PATH = r"C:\OSGeo4W\bin\geos_c.dll" -
Django: Link to own AdminSite in template of TemplateView
I defined my own AdminSite in Django 5.0.2 and added some APPs to this AdminSite. This is working and I can access my own admin page via http://127.0.0.1:8080/my-admin/. Now I would like to add the link of this admin-page ("my-admin") to a template of a templateView. (see the ????????? in the main.html file). The link to the standard admin-page is working fine. I am a beginner with Django and tried a few days to get this up&running, but unfortunately I could not find any solution. Could someone give me an hint, please? mydjango/myadmin/admin.py: from django.contrib.admin import AdminSite class EventAdminSite(AdminSite): site_header = 'Test ADMIN' site_titile = 'Test ADMIN PORTAL' index_title = 'WELCOME TO MY ADMIN PORTAL' my_admin_site = EventAdminSite(name = 'my_admin') mydjango/applications/admin.py: from django.contrib import admin from .models import Application from myadmin.admin import my_admin_site class ApplicationAdmin(admin.ModelAdmin): search_fields = ["name", "dest1_protocol","dest1_port"] exclude = ["created","modified"] admin.site.register(Application) my_admin_site.register(Application,ApplicationAdmin) mydjango\mysettings.py: urlpatterns = [ .. path("my-admin/",my_admin_site.urls), .. ] mydjango/main/views.py: from django.shortcuts import render from django.views.generic.base import TemplateView class IndexView(TemplateView): template_name = 'main/index.html' def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) context['title'] = "Policy-Management" return context mydjango/main/templates/main.html {% load admin_urls %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>{{ title … -
Vue script in my django project is not showing up
I currently nearly finished a django project. On top of it, I just want to use vue to spare some repetition and discover some features that might better the user interaction experience. I referenced vue through CDN link in my base template <scriptsrc="https://unpkg.com/vue@3/dist/vue.global.js"></script>. And under the link, I tried a demo vue code <script> const { createApp, ref } = Vue createApp({ setup() { const notice = ref('Hello vue!') return { notice } } }).mount('#app') </script> On top of my template I added <div id="app">{{notice}} something</div>. I expect the top of my website to show a "hello vue! something", meaning vue is running properly. But I only get "something". Is CDN way of linking vue not acceptable to django or something else I misdid during the process that makes my vue demo code not working? -
Wagtail: Unwanted wagtail queries on every page
I use Wagtail 5.2 and have on everypage this three queries. Why is Wagtail doing this? Even if I go to www.example.com/admin/ (Default Django admin page) I can see this three queries? Is this the default behavior or I am doing something wrong? Is it possible to cache at least the first query somehow? I guess wagtail is trying to get for each the current site objects. -
Optimizing SimpleJWT to imporove performance
I got a issue with SimpleJWT on my API built in Dajngo, it takes 2 secs to response. I know it doesn't seem like a long time but I really need to improve it. On the Profile table in MySQL database, username and password fields are indexed. I was reading the official documentation but I don't see any advice for improve performance. Someone there with a better knowledge than me that who can help me? settings.py SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=6000), 'ALGORITHM': 'HS256', 'SIGNING_KEY': SECRET_KEY, } urls.py (cutted) from rest_framework_simplejwt.views import (TokenObtainPairView, TokenRefreshView) urlpatterns = [ path('', include('api.urls')), path('token/', TokenObtainPairView.as_view(), name='token_obtain_pair') ] I tried indexing the username and password fields on the Profile table. -
I am trying to update a value in my django model but its not getting updated
I have created a view that scans the report_file which is a excel sheet and checks the previous value and compares it with the new value and then calculates the percentage difference. This takes function only executes whenever the report_file gets updated. But for some reason when I try to save the percentage difference it does not get saved. My new value gets saved but the percentage does not. And I have also kept print statements which are printing the correct values. Below is my views.py: @login_required(login_url='my-login') def update_testcase(request, pk): testcase = get_object_or_404(TestCase, pk=pk, user=request.user) if request.method == 'POST': form = TestCasesForm(request.POST, request.FILES, instance=testcase) if form.is_valid(): # Save the form form.save() # Read the uploaded .xlsx file excel_file = testcase.report_file.read() # Extract the total number of test cases using the function from xlsx_utils.py total_test_cases = extract_total_test_cases(excel_file) print(total_test_cases) # Calculate the percentage increase previous_total_test_cases = testcase.total_test_cases print(previous_total_test_cases) if previous_total_test_cases: percentage_increase = ((total_test_cases - previous_total_test_cases) / previous_total_test_cases) * 100 else: percentage_increase = None print(percentage_increase) # Update the model instance with the total number of test cases and percentage increase testcase.total_test_cases = total_test_cases testcase.increase_percentage = percentage_increase testcase.save() return redirect('writer:my-testcases') else: form = TestCasesForm(instance=testcase) context = {'UpdateTestCaseForm': form} return render(request, 'writer/update-testcase.html', context) below is … -
Django error" Its showing template doesnot exists"
check the below iamges.I'm new to django I just tried to run a project downloaded from internet. -
Steam screenshot parser
for a long time I wanted to know how to make a parser or maybe something else so that I could add screenshots from my Steam profile to my site. That is, I do not want to download them, but to collect links to screenshots like this: https://steamuserimages-a.akamaihd.net/ugc/2265940142968960301/6F3FBB0765789516872B71DDDF0C3042E4354F2E/. And then process them on your website. Because I haven't seen something like this through the SteamAPI, and it seems I haven't seen the libraries either, but maybe I wasn't looking for it well. Therefore, I will be glad if you 'throw' something. I make the site on Django -
Gunicorn not able to bind django project
I installed gunicorn inside virtual environment for running a django project in Ubutu 22 and tried to bind the project URL. But the below error appear and I am not able to bind. Can anybody please help me fix this error. Thanks python --version Python 3.10.12 (venv_django_proj) django@ubuntu-Virtual-Machine:~/django_proj/django_proj$ gunicorn django_proj.wsgi [2024-02-19 18:59:13 +0530] [25811] [INFO] Starting gunicorn 20.1.0 [2024-02-19 18:59:13 +0530] [25811] [INFO] Listening at: http://127.0.0.1:8000 (25811) [2024-02-19 18:59:13 +0530] [25811] [INFO] Using worker: sync [2024-02-19 18:59:13 +0530] [25812] [INFO] Booting worker with pid: 25812 [2024-02-19 18:59:13 +0530] [25812] [ERROR] Exception in worker process Traceback (most recent call last): File "/usr/lib/python3/dist-packages/gunicorn/arbiter.py", line 589, in spawn_worker worker.init_process() File "/usr/lib/python3/dist-packages/gunicorn/workers/base.py", line 134, in init_process self.load_wsgi() File "/usr/lib/python3/dist-packages/gunicorn/workers/base.py", line 146, in load_wsgi self.wsgi = self.app.wsgi() File "/usr/lib/python3/dist-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/usr/lib/python3/dist-packages/gunicorn/app/wsgiapp.py", line 58, in load return self.load_wsgiapp() File "/usr/lib/python3/dist-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp return util.import_app(self.app_uri) File "/usr/lib/python3/dist-packages/gunicorn/util.py", line 384, in import_app mod = importlib.import_module(module) File "/usr/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in … -
Some Django form data not appearing in MongoDB database?
I'm encountering an issue with my Django application where I've extended the built-in User model with additional fields like company_name and role, but when I try to register a new user through the signup form, these additional fields are not being saved to the MongoDB database,But other fields are visible. When I submit the signup form, the user is successfully created and saved to the database, but the company_name and role fields are not being populated. However, I've added print statements in my view to check the form data just before saving, and I can see that the additional fields are being captured correctly. [forms.py] from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from django.contrib.auth.models import User from django import forms from django.forms.widgets import PasswordInput, TextInput from django.core.exceptions import ValidationError class CreateUserForm(UserCreationForm): company_name = forms.CharField(max_length=100) role = forms.CharField(max_length=100) email = forms.EmailField(required=True) def clean_email(self): email = self.cleaned_data.get('email') if email and email.endswith('@gmail.com'): raise ValidationError("Gmail addresses are not allowed.") return email class Meta: model = User fields = ['username', 'email','company_name', 'role', 'password1', 'password2'] def save(self, commit=True): user = super(CreateUserForm, self).save(commit=False) user.company_name = self.cleaned_data['company_name'] user.role = self.cleaned_data['role'] if commit: user.save() return user class LoginForm(AuthenticationForm): username = forms.CharField(widget=TextInput()) password = forms.CharField(widget=PasswordInput()) [views.py] from django.shortcuts import render, redirect from … -
How to interact between Models inside model.py?
There is something I want to do but I don't know how to do it. in this case I have 2 Models in project named 1.Music 2.Artist 1. Music Model is saving music details such as musicName,artistName,genre,etc... 2. Artist Model has only one job and that is saving Artist names. I want to write a code for my models to when I'm adding a new music in admin panel, Music Model checks the Artist Model for existence artist names and if artist name existed => just add music details and if artist name not existed Then add a new artist in Artist Model. This is my sample model.py code: class Artist(models.Model): name = models.CharField(max_length=100) class Music(models.Model): name = models.CharField(max_length=100) artist = models.CharField(max_length=100) genre = models.CharField(max_length=100) -
how to sum integer field with a number in django 5 model and save it
i have a cartitem model: class CartItem(models.Model): cart=models.ForeignKey(Cart,related_name='items',on_delete=models.CASCADE) product=models.ForeignKey(Product,on_delete=models.CASCADE) quantity=models.PositiveIntegerField(default=0) when add product to cartitem in view : class AddToCartView(LoginRequiredMixin,View): model = Product def post(self, request, *args, **kwargs): product = get_object_or_404(Product, pk=kwargs['pk']) cart, created = Cart.objects.get_or_create(user=request.user) cart_item, created = CartItem.objects.get_or_create(cart=cart, product=product) # POST request quantity = request.POST.get('quantity') try: quantity=int(quantity) if quantity else 1 except ValueError: quantity=1 cart_item.quantity +=quantity cart_item.save() # Redirect to cart detail view return reverse_lazy('shop:home') An error occurred in view: Attribute Error at /product/2/add-to-cart/ proxy object has no attribute get help me please. add product to cart with this code: cart_item.quantity +=quantity but error occurred. -
All my fields are getting updated except the File Field
I am creating a django CRUD project. I am facing an issue where I am not able to update the File field. I am able to update the all the other fields except the File Field. Below is my models: class TestCase(models.Model): title = models.CharField(max_length=150) report_file = models.FileField(upload_to=user_directory_path,validators=[FileExtensionValidator(allowed_extensions=['xlsx'])]) date_posted = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(CustomUser, max_length=10, on_delete=models.CASCADE, null=True) increase_value = models.IntegerField(null=True, blank=True) total_test_cases = models.IntegerField(null=True, blank=True) category = models.CharField(max_length=10, choices=CATEGORY_CHOICES, null=True, blank=True) My form: class TestCasesForm(ModelForm): class Meta: model = TestCase fields = ['title', 'report_file','category'] and my update view: @login_required(login_url='my-login') def update_view(request, pk): testcase = get_object_or_404(TestCase, pk=pk, user=request.user) if request.method == 'POST': form = TestCasesForm(request.POST, request.FILES, instance=testcase) if form.is_valid(): form.save() return redirect('writer:my-testcases') else: form = TestCasesForm(instance=testcase) context = {'UpdateTestCaseForm': form} return render(request, 'writer/update-testcase.html', context) -
Namespace not solving NoReverseMatch: Reverse for 'login' not found. 'login' is not a valid view function or pattern name
I have this error and don't know exactly the source of it, if it's an error in the apps urls, or in the projects urls. The exact error is "NoReverseMatch: Reverse for 'login' not found. 'login' is not a valid view function or pattern name." The code is where the problem is: <li class="nav-item"> {% if not user.is_authenticated %} <a class="nav-link" href="{% url 'login' %}">Login</a> {% else %} <a class="nav-link" href="{% url 'logout' %}">Logout</a>` {% endif %} </li> Here is my urls: from django.contrib import admin from django.urls import path, include from . import views from django.contrib.auth import views as auth_views from .forms import * urlpatterns = [ path('', views.index, name="index"), path('admin/', admin.site.urls), path('register/', views.UserSignupView.as_view(), name="register"), path('login/', auth_views.LoginView.as_view(template_name="login.html", authentication_form=UserLoginForm)), path('logout/', views.logout_user, name="logout"), ] And my projects urls: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('', include('templates.urls')), path('admin/', admin.site.urls), ] Disclaimer, I have tried adding the namespace, but this flags another issue, so wanted to see if there is any other issues with the code. I have tried to see if the problem is in the projects urls, but to no success. Have tried to see if it's a form problem, but the form has no … -
Getting default image when streaming a video onto the webpage through django
My moto:-* create a webpage which accepts a video file and once submitted through submit button, the video(in form of frames) will display within samepage in another div section. reason for displaying as frames is i need to process each frame. (Rendering frames onto webpage).* My django code:def gen(request): if request.method == 'POST': try: video_file = request.FILES["video"] if video_file: video_filename = "temp_video.mp4" video_filepath = os.path.join(settings.STATIC_ROOT, video_filename) with open(video_filepath, 'wb') as destination: for chunk in video_file.chunks(): destination.write(chunk) video_cap = cv2.VideoCapture(video_filepath) if not video_cap.isOpened(): print("Error: Could not open video file") return "Error in processing video." while True: ret, frame = video_cap.read() if not ret: break else: #cv2.imshow("output",frame) tried this too but not working. frame_bytes = frame.tobytes() yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame_bytes + b'\r\n\r\n') else: print("no video file") except Exception as e: print("An error occurred:", e) return "An error occurred while processing the video." def process_video(request): return StreamingHttpResponse(gen(request),content_type='multipart/x-mixed-replace; boundary=frame') My javascript(in html file):-<script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script> <script> document.getElementById('uploadForm').addEventListener('submit', function (event) { event.preventDefault(); // Prevent default form submission behavior const formData = new FormData(this); fetch(this.action, { method: this.method, body: formData}) .then(response => { // Handle response // Define a function to handle each frame received function handleFrame(frameUrl) { // Create a new image … -
WebSocket Disconnect: No route found for path 'ws/chat_app/3wVCio/'
When I try to connect to handshake with my WebSocket, I'm getting the following error in Django terminal: python3.12/site-packages/channels/routing.py", line 134, in __call__ raise ValueError("No route found for path %r." % path) ValueError: No route found for path 'ws/chat_app/3wVCio/'. WebSocket DISCONNECT /ws/chat_app/3wVCio/ [192.168.0.11:58136] I found, that in previous Django versions, the problem was, that instead of path, for defining the urlpatterns in this case, it should be used url(). However, the url() is depricated and instead of it, the re_path should be used. Unfortunately it did not help me.. Here is the routing, I created - routing.py from django.urls import re_path from .consumers import ChatConsumer # The WebSocket URL pattern for chat rooms is defined by this code websocket_urlpatterns = [ re_path(r'chat_app/(?P<unique_id>\w+)/$', ChatConsumer.as_asgi()), ] This is the WebSocket consumer.py: import json from channels.generic.websocket import AsyncWebsocketConsumer from asgiref.sync import sync_to_async from .models import Message from room_app.models import Room class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.unique_id = self.scope['url_route']['kwargs']['unique_id'] self.room_group_name = f'chat_{self.unique_id}' # Check if the room exists in the database if not await self.room_exists(): await self.close() return # Join room group self.channel_layer.group_add( self.room_group_name, self.channel_name ) self.accept() def disconnect(self, close_code): # Leave room group self.channel_layer.group_discard( self.room_group_name, self.channel_name ) # Receive message from WebSocket def … -
No module named ‘application’` when deploying to AWS elastic beanstalk
I am trying to deploy a django project on elastic beanstalk, I have used this AWS official Doc for django deployment on EB: https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html These are Steps i followed: eb init eb create put CNAME in ALLOWED_HOST eb deploy and when i try to see my website, i get ERROR: "502 Bad Gateway: nginx" So i checked web.stdout.log file and found this error: https://i.stack.imgur.com/iZzcG.png This is my django.config file (present in .ebextensions folder) This is my directory structure: This is my wsgi.py file: enter image description hereenter image description hereenter image description here I want to solve this error. I don't know what's the problem, and I really need someone to help me solve this error, Your help means a lot to me. if you need any additional information let me know. -
django-storage[s3]: using storage and upload_to field together on image field doesnt work
There are sevaral threads/blogs on how you can use django-storage library to upload files/images on different cloud platforms(in my case I'm concerned about only S3). I configured it by adding below settings in settings,py storages to INSTALLED_APPS, AWS settings AWS_ACCESS_KEY_ID = AWS_SECRET_ACCESS_KEY = AWS_STORAGE_BUCKET_NAME = AWS_S3_REGION_NAME = AWS_QUERYSTRING_AUTH = False STORAGES = { "default": { "BACKEND": "path.to.CustomStoragBackendsClass", }, "staticfiles": { "BACKEND": "django.contrib.staticfiles.storage.StaticFilesStorage", }, } class CustomStoragBackendsClass(S3Boto3Storage): default_acl = 'public-read' Now in models, I'm trying to use this as below class MyModel(mdoel.Model): ... main_icon = models.ImageField( null=True, storage=CustomStoragBackendsClass(location="my_model/main_icons", uplaod_to=main_icon_upload_to_path, ) ... and here is the upload_to path function in the same model file def main_icon_upload_to_path(instance, filename): return f"{instance.pk}/{filename}" At first look all this looks fine but for some reason it's not working as expected. I'm still getting the path without instance id in it (basically it seems upload_to is not being used at all, only storage field is being used). My goal is to have a single bucket for all images/files in the app. and then in that bucket will have folders representing each models from where files have been uploaded. and with in model directory, I have another folder which represents the field name, and then id of that model … -
Python Admin Site with Through Parameter
I had the following Model class UserGroup(models.Model): name = models.CharField(max_length=255, unique=True) users = models.ManyToManyField(User, blank=True) def __str__(self): return self.name With my Admin.py below, The query set worked 100% (basically only showing users in the current group and users not in a group at all ) class UserGroupAdmin(admin.ModelAdmin): filter_horizontal = ('users',) def formfield_for_manytomany(self, db_field, request=None, **kwargs): if db_field.name == 'users': object_id = request.resolver_match.kwargs.get('object_id') kwargs['queryset'] = User.objects.filter( Q(usergroup=None) | Q(usergroup=object_id) ) return super().formfield_for_manytomany(db_field, request, **kwargs) admin.site.register(UserGroup, UserGroupAdmin) The output looked like the below Which was great but I changed my Model to use the Through parameter below. class UserGroup(models.Model): name = models.CharField(max_length=255, unique=True) users = models.ManyToManyField(User, blank=True, through='UserToUserGroup') def __str__(self): return self.name class UserToUserGroup(models.Model): user = models.OneToOneField(User, on_delete=models.PROTECT) user_group = models.ForeignKey(UserGroup, on_delete=models.CASCADE) Now My admin site looks like the below. I am having a hard time getting the admin site to look same after my changes to the model. I am still getting use to working with the admin site. I tried some inlines but had no success. I do need to use the filter horizontal and have it look the same. -
filter city field (for each province) based on selected province field in django admin panel
class Province(models.Model): name = models.CharField( max_length=70, unique=True, null=True, blank=True,) def __str__(self): return self.name class City(models.Model): province = models.ForeignKey("election.Province", on_delete=models.CASCADE) name = models.CharField(max_length=70, unique=True, null=True, blank=True,) class Election(models.Model): province = models.ForeignKey("election.Province", on_delete=models.SET_NULL, null=True, blank=True,) city = models.ForeignKey("election.City", on_delete=models.SET_NULL, null=True, blank=True,) I have this models. in admin panel, when selecting a province I want to just see the cites that belonging to that province. I`m begginer ;) -
backend not responding with domain but responding with ip
I have setup 2 different servers for frontend and backend. frontend server is accessible with ip and the domain both. all api requests are being processed by backend long as it comes from the ip. but when i load the ui with domain name, the backend is not accepting requests. returns no response. I have already configured in my application, so this seems like some problem with some aws config.. please help. both are smallest aws ec2, frontend is nextjs backend is django -
Django Q2 - Setting Up A Basic Structure For Function Scheduling
I'm kind of new to using Django different then its basic scope. I scheduled a function that works every minute for trial purposes. I read the documentation many times it is still obscure for me that what is the right way of using the Django Q2 library for scheduling. Can you please provide a clarification for me. Note that, I'm using DjangoORM. In my attempt, I created schedule.py as below script and make it work somehow but I'm not sure what is the correct way to run 'setup_periodic_tasks'. Furthermore, earlier tasks that I run are still showing up everytime I run qcluster despite I deleted them from the Tasks object, so how can I delete them for good? def schedule_price_list_status(): print('PRICE LIST SCHEDULED') def setup_periodic_tasks(**kwargs): print('SETUP TASKS') schedule('my_app.schedules.schedule_price_list_status', schedule_type='I', repeats=2, minutes=1) setup_periodic_tasks() -
Parsing Excel File Raises "No such keys(s): 'io.excel.zip.reader'" Error
I'm attempting to parse an file type 'docx' in my Django application using pandas, but I'm encountering the error "No such keys(s): 'io.excel.zip.reader'". It seems like there's an issue with how the file is being read or with the file format itself. I've checked that the file is indeed an Excel file with the .xlsx extension then its working fine but when i m adding elif statement for file type 'docx' then i got that error. Can someone help me understand what might be causing this error and how to resolve it? Below is a snippet of the code I'm using: import pandas as pd import json from docx import Document if request.method == 'POST': form = UserPermissionForm(request.POST, request.FILES) if form.is_valid(): upload_template_instance = form.save() template_file = upload_template_instance.template_master # Check file extension to determine its type if template_file.name.endswith('.xlsx'): # Parse the Excel file using Pandas df = pd.read_excel(template_file) df.fillna('', inplace=True) df.columns = ["" if 'Unnamed' in str(col) else col for col in df.columns] columns = df.columns.tolist() data = df.values.tolist() elif template_file.name.endswith('.docx'): # Parse the Word document using python-docx doc = Document(template_file) data = [] for paragraph in doc.paragraphs: # Extract text from each paragraph text = paragraph.text # Split text into … -
Django Mysql Database Configuration and Security
Is there a way to access a MySQL database from Django without explicitly providing credentials such as USERNAME, DATABASE NAME, and PASSWORD? I've explored methods like using dotenv or storing credentials in separate files, but I'm interested in alternatives. Are there approaches such as utilising Unix sockets or other methods to achieve this? Could someone provide an example of how to implement such a solution?