Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
My Django project is opening very slowly on the server
Please check out my site: pyterminator.com The site opens very late. I don't know what the reason is. I used dj-static package in wsgi file. Does this affect performance? wsgi.py : import os from dj_static import Cling from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core.settings') application = Cling(get_wsgi_application()) I bought the "Starter hosting" package and deployed there. Through C-Panel. Could this be the reason for poor performance? I use these packages. arabic-reshaper==3.0.0 asgiref==3.8.1 asn1crypto==1.5.1 certifi==2024.2.2 cffi==1.16.0 chardet==5.2.0 charset-normalizer==3.3.2 click==8.1.7 colorama==0.4.6 cryptography==42.0.6 cssselect2==0.7.0 dj-static==0.0.6 Django==5.0.4 django-cleanup==8.1.0 django-tinymce==4.0.0 html5lib==1.1 idna==3.7 lxml==5.2.1 mysqlclient==2.2.4 oscrypto==1.3.0 pillow==10.3.0 pycparser==2.22 pyHanko==0.24.0 pyhanko-certvalidator==0.26.3 pypdf==4.2.0 pypng==0.20220715.0 python-bidi==0.4.2 python-dotenv==1.0.1 PyYAML==6.0.1 qrcode==7.4.2 reportlab==4.0.9 requests==2.31.0 six==1.16.0 sqlparse==0.5.0 static3==0.7.0 svglib==1.5.1 tinycss2==1.3.0 typing_extensions==4.11.0 tzdata==2024.1 tzlocal==5.2 uritools==4.0.2 urllib3==2.2.1 webencodings==0.5.1 xhtml2pdf==0.2.15 settings.py import os from pathlib import Path # ---------------------- * ------------------------- from django.contrib.messages import constants as messages # ---------------------- * ------------------------- from dotenv import load_dotenv load_dotenv() # ---------------------- * ------------------------- BASE_DIR = Path(__file__).resolve().parent.parent # ---------------------- * ------------------------- SECRET_KEY = "xxxx" # ---------------------- * ------------------------- DEBUG = True ALLOWED_HOSTS = ["pyterminator.com", "127.0.0.1", "www.pyterminator.com"] # ---------------------- * ------------------------- INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_cleanup.apps.CleanupConfig', 'tinymce', # ---> Apps <--- # 'home.apps.HomeConfig', 'post.apps.PostConfig', 'fusion.apps.FusionConfig', 'contact.apps.ContactConfig', 'c_profile.apps.CProfileConfig', ] # ---------------------- * ------------------------- MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', … -
Django forms access (file) field from relation
I have a view that locks like this: def table_form_combined(request: HttpRequest) -> HttpResponse: if request.method == "POST": formset = TransActionFormSet(data=request.POST) print(formset.errors) if formset.is_valid(): formset.save() return render(request, "evidence/table_form_combined.html", {'formset': TransActionFormSet}) My Form looks like this: class TransactionForm(ModelForm): class Meta: model = Transaction fields = ("source_id", "transaction_date", "data", "evidence", "meta_data") widgets = { 'data': Textarea(attrs={'rows': 1}), # set the row amount of # the data Text fields to 1 --> data : Name of Textfield in Model } My model (just the relevant stuff): class TransactionEvidence(Base): file = models.FileField(upload_to='evidence/') class Transaction(Base): evidence = models.ForeignKey( TransactionEvidence, on_delete=models.CASCADE, help_text="A evidence file (i.e. pdf invoice) that can be assigned to a transaction.", ) source_id = models.CharField( "Source ID", max_length=150 ) transaction_date = models.DateTimeField(default=timezone.now, help_text="The transaction date") And finally, my template locks like this: {% extends "website/base.html" %} {% block content %} <table class="table"> <thead> <tr> <th scope="col"> # </th> <th scope="col"> Name </th> <th scope="col"> Transaction Date </th> <th scope="col"> Data</th> <th scope="col"> Evidence</th> <th scope="col"> file</th> <th scope="col"> Amount</th> </tr> </thead> <tbody> {{ formset.management_form }} {% comment %} https://docs.djangoproject.com/en/3.2/topics/forms/formsets/#understanding-the-managementform, without that, the form will be invalid {% endcomment %} {% for form in formset %} <form method="post" enctype="multipart/form-data"> {% csrf_token %} {% if form.source_id.value … -
Django query with OR operator
I'm trying to do an OR operator for a Django query. But for some reason my query syntax is wrong. Not sure why it's wrong. Basically I'm trying to query for the site and get any device with Role as 'Router' or 'Other'. Below is my query. Any help is much appreciated! Thank you in advance. Method 1 tried- from django.db.models import Q numRouters= Device.objects.filter(location__name__startswith=site,Q(role__name__in=["Router"]) | Q(role__name_in=["Other"])) SyntaxError: positional argument follows keyword argument from django.db.models import Q Method 2 tried- numRouters = Device.objects.filter(location__name__startswith=site,Q(role__name__in=["Router"]) | Q(role__name__in=["Other"])) SyntaxError: positional argument follows keyword argument -
ForeignKeyWidget in django-import-export Showing ID Instead of Custom Column Value
I am using the django-import-export library to handle data import and export in my Django application. I have several models with ForeignKey relationships, and I want to display and use the custom column values instead of the IDs in my import/export files. # models.py class YearCategoryMalnutrition(models.Model): id = models.AutoField(primary_key=True) year_recorded = models.CharField(max_length=4, default="") last_update = models.DateTimeField(auto_now=True, null=True) def __str__(self): return self.year_recorded class AgeCategory(models.Model): AGE_CATEGORIES = ( ('0-5 years old (0-60 months)', '0-5 years old (0-60 months)'), ('5.08-10.0 years old (61-120 months)', '5.08-10.0 years old (61-120 months)'), ('10.08-19.0 years old (121-228 months)', '10.08-19.0 years old (121-228 months)'), ('Adults 20 years old above', 'Adults 20 years old above'), ) age_category_name = models.CharField( max_length=50, choices=AGE_CATEGORIES, default='0-5 years old (0-60 months)', ) last_update = models.DateTimeField(auto_now=True, null=True) class Meta: verbose_name_plural = "Age Categories" def __str__(self): return self.age_category_name class LevelCategory(models.Model): LEVEL_CATEGORIES = ( ('National Level', 'National Level'), ('Regional Level', 'Regional Level'), ('Province Level', 'Province Level'), ('Municipality Level', 'Municipality Level'), ('Barangay Level', 'Barangay Level'), ) level_category_name = models.CharField( max_length=50, choices=LEVEL_CATEGORIES, default='National Level', ) last_update = models.DateTimeField(auto_now=True, null=True) class Meta: verbose_name_plural = "Level Categories" def __str__(self): return self.level_category_name class NationalLevel(models.Model): id = models.AutoField(primary_key=True) country_name = models.CharField(max_length=255, default="Philippines") overweight = models.FloatField(default=0.0) underweight = models.FloatField(default=0.0) stunting = models.FloatField(default=0.0) wasting = … -
Django authentication testing failure: Authentication credentials were not provided
I am working on the user logic of my Django project. Despite the fact that logout (using session cookie authentication) works perfectly fine in the browser, it is not working during testing for some reason. It appears as if the cookie from the login response isn't being correctly saved for the subsequent request. Here are the relevant excerpts from my project code: views.py class UserLogoutView(generics.GenericAPIView): permission_classes: list[permissions.BasePermission] = [permissions.IsAuthenticated] def get_serializer_class(self) -> serializers.Serializer: return serializers.Serializer # Return basic Serializer class def delete(self, request: Request) -> Response: response: Response try: session_key: str = request.COOKIES.get("session") token: Token = Token.objects.get(key=session_key) response = Response( status=status.HTTP_200_OK, data={"detail": "Logout successful"}, ) response.delete_cookie(key="session") token.delete() except ObjectDoesNotExist: response = Response( {"error": "Session cookie not found"}, status=status.HTTP_401_UNAUTHORIZED, ) except Exception as error: print(error) response = Response( {"error": str(error)}, status=status.HTTP_400_BAD_REQUEST, ) return response tests_views.py class TestLogoutViews(TestCase): def setUp(self) -> None: self.client = Client() self.data: dict[str, str] = { "username": "testuser", "email": "test@test.com", "password": "Password1", } self.logout_url: str = reverse("user_logout") self.login_url: str = reverse("user_login") self.client.post( reverse("user_register"), json.dumps(self.data), content_type="application/json", ) self.data.pop("email") def test_logout_view_correct_DELETE(self) -> None: # Log in first response: HttpResponse = self.client.post( self.login_url, json.dumps(self.data), content_type="application/json", ) print() print(response.status_code, self.client.cookies) print() # Send the DELETE request response: HttpResponse = self.client.delete(self.logout_url) # Check … -
Changing just the name of the django settings file causes error
I ran into a problem trying originally to use cookiecutter-django when using the docker compose production.yml vs the local.yml files Managed to shrink it down to this: https://github.com/xmclej/django-testing-01 The code is currently defaulted to use "config.settings.base" See the README.md file for the very minimal setup and instructions The problem is that when I change only the DJANGO_SETTINGS_MODULE value from "config.settings.base" to "config.settings.trial". Noting that the two files are identical inside. Get error.. ModuleNotFoundError: No module named 'config.settings.trial' Any thoughts? Originally was trying to use the default cookiecuttter approach of split settings files. Until I hit this little bug. Using config.settings.base ... it works (venv) D:\Beanycode\Projects\django-testing-01>docker compose -f production.yml up [+] Running 2/2 ✔ Container django-testing-01-postgres-1 Running 0.0s ✔ Container django-testing-01-django-1 Recreated 0.1s Attaching to django-1, postgres-1 django-1 | PostgreSQL is available django-1 | start of production entrypoint django-1 | django django-1 | /app django-1 | 10 django-1 | 20 django-1 | 30 django-1 | 50 django-1 | 60 django-1 | [2024-05-14 23:37:22 +0000] [1] [INFO] Starting gunicorn 21.2.0 django-1 | [2024-05-14 23:37:22 +0000] [1] [INFO] Listening at: http://0.0.0.0:5000 (1) django-1 | [2024-05-14 23:37:22 +0000] [1] [INFO] Using worker: sync django-1 | [2024-05-14 23:37:22 +0000] [9] [INFO] Booting worker with pid: … -
djnago scrapy TypeError: RepoSpider.start_requests() missing 1 required positional argument: 'url'
I.m trying to build a webapp to fetch data from a repo. Its near completion but i am facing this error currently The codes: this is the spider code import scrapy from App.models import Repo class RepoSpider(scrapy.Spider): name = "RepoSpider" allowed_domains = ["github.com"] start_urls = [] def start_requests(self, url): yield scrapy.Request(url) def parse(self, response): url = response.url url_parts = url.split('/') username = url_parts[-1] repo = url_parts[-2] description = response.css('.f4.my-3::text').get(default='').strip() language = response.css('.color-fg-default.text-bold.mr-1::text').get(default='') stars = response.css('a.Link.Link--muted strong::text').get(default='0').strip() yield { 'username': username, 'repo': repo, 'description': description, 'top_language': language, 'stars': stars } scraped_repo = Repo( url=url, username=username, description=description, top_language=language, stars=stars ) scraped_repo.save() django view from django.shortcuts import render, redirect from .models import Repo from scrapy.crawler import CrawlerProcess from .tester.tester.spiders.repo import RepoSpider def index(request): if request.method =='POST': url = request.POST.get('url') process = CrawlerProcess() process.crawl(RepoSpider, url) process.start() return render(request, 'index.html') Tried whatever i could get on, but running out of options now. This is a project i need to get done as soon as possible, it would mean a lot to me to have this working -
Is there a way to restrict users to only see children of a parent element they belong to in Django Rest?
I have built a Django REST app for a client that allows users to join communities. The Community model has 20+ models that link back to it in some way (things like events, event dates, meetings, messages etc). I need a way to restrict users to only being able to perform CRUD operations on elements belonging to communities they are a part of. For example if user "John Smith" is a member of the "Animal Rescue Volunteers" community, he should only be able to read messages for that community and should not be able to create/edit messages in other communities. I have seen people use the get_queryset method of a ViewSet to restrict RUD processes like so: class MessageView(viewsets.ModelViewSet): queryset = Message.objects.all() serializer_class = MessageSerializer def get_queryset(self): return self.queryset.filter(message__community__in=self.request.user.communities) However this doesn't solve the problem with Creates and needs to be applied to each ViewSet to work. Is there a better way to do this? -
Only able to upload PNG images with django-ckeditor-5
I am building a simple blog application in Django and istalled django-ckeditor-5. I am able to upload PNG images with no problem, but when I try to upload JPG image of any size (or any other format), the browser throws an alert localhost:8000 says Couldn't upload file: filename.jpg I didn't include any restrictions in the models or in the settings. I basically copied the ckeditor configurations from their documentation. I didn't have this problem with the previous version of ckeditor, but apparently it has some vulnerability issues... Any ideas how I can enable other file formats for images? -
"Method \"GET\" not allowed."
I really need help explaining why I pass the method as DELETE but the error appears "Method "GET" not allowed." Thank you very much. class DeleteUserByUsernameView(APIView): def delete(self, request, username): try: instance = User.objects.filter(username=username) instance.delete() return HttpResponse("Success") except Exception as e: return Response({'error': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) from django.contrib import admin from django.urls import path, include from . import views urlpatterns = [ path('delete/user/<str:username>/', views.DeleteUserByUsernameView.as_view()), path('register/', views.RegisterView.as_view(), name="Register"), path('login/', views.LoginView.as_view(), name="Login"), ] enter image description here enter image description here enter image description here -
Django cannot find page with multiple similar URL paths
I am trying to create a Django site with different views/models spanning from the same level of the URL structure. Here is the URL structure I am trying to create: HOME PAGE -- Country --- State ---- City --- Topic ---- Article I am using the following code in urls.py: urlpatterns = [ path( "<slug:country_slug>/<slug:state_slug>/<slug:city_slug>/", CityIndex.as_view(), name="city_index", ), path( "<slug:country_slug>/<slug:topic_slug>/<slug:article_slug>/", ArticleDetail.as_view(), name="article_detail", ), path( "", HomeIndex.as_view(), name="home", ), The City Index path works fine. The issue I have is trying to access an article. Django only seems to attempt to match the first URL path. I enter a URL: "example-country/example-topic/example-article" Django returns the following error message: Page not found (404) No Destination matches the given query. Request Method: GET Request URL: http://127.0.0.1:8000/example-country/example-topic/example-article/ Raised by: content.views.destinations.CityIndex It seems that, because the pattern is similar to the URL pattern for "city_index", it attempts to match this, then return a 404 error. It doesn't move on to check the next URL pattern for "article_detail", which would then match an article and return a template. I tried switching the "article_detail" URL path to come first, above "city_index". This causes "article_detail" to return a template correctly, but now "city_index" does not. Effectively, Django will match … -
How to save data by Button Click handler in DJANGO
Let's assume I have a buy button. In my card. On the card, I'm showing some car details. If the user clicks on the buy button the car/product details will be saved into a new Table. How i can implement this with the Button Click handler in DJANGO? <div class="card-body"> <img src="{{object.car_image.url}}" class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title fw-bold text-uppercase gap-2"> {{object.car_name}} </h5> <p class="card-text btn btn-sm btn-light disabled">Brand : {{object.car_brand}}</p> <div class="d-flex gap-2"> <p class="btn btn-sm btn-primary disabled">Quantity :{{object.quantity}}</p> <p class="btn btn-sm btn-warning disabled ">Price :{{object.price}}</p> </div> <p class="card-text">{{object.description }}</p> {% if user.is_authenticated %} <button class='btn btn-sm btn-success'>Buy Car</button> {% endif %} </div> -
when trying to send the message form docker worker container it's not sending it's getting connection timeout 110
I have all the firewall port active, tried telnet and other to test connectivity to smtp server it's giving response, also when trying to send the mail in django with send_mail() it's able to sending but when trying to send mail using from django.core.mail import EmailMessage send() it's getting connection timeout 110 the i also increase the timeout to 60s by increasing it in django setting.py for email backend still when trying to send mail it's showing this log error return self.get_connection(fail_silently).send_messages([self]) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/matrixadm/.local/lib/python3.11/site-packages/django/core/mail/backends/smtp.py", line 134, in send_messages sent = self._send(message) ^^^^^^^^^^^^^^^^^^^ File "/home/matrixadm/.local/lib/python3.11/site-packages/django/core/mail/backends/smtp.py", line 152, in _send self.connection.sendmail( File "/usr/local/lib/python3.11/smtplib.py", line 902, in sendmail (code, resp) = self.data(msg) ^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/smtplib.py", line 580, in data (code, msg) = self.getreply() ^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/smtplib.py", line 398, in getreply line = self.file.readline(_MAXLINE + 1) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/socket.py", line 706, in readinto return self._sock.recv_into(b) I tried to send mail but it's showing connection timeout 110 error -
Unable to view the table in Django admin panel
Okay so i am new to django. I created a superuser and then i created a 'Customer' model as shown below in models.py inside my app called 'products' Now , ran the migration command i.e python manage.py makemigrations followed by python manage.py migrate. After i log into the admin panel i see the 'Customers table and as soon as i click on it i get this error attached in the screenshot. Note: A weird thing i noticed , i did not get the migrations directory even after i ran the migration command The Customer model i defined: `from django.db import models Create your models here. class Customer(models.Model): GENDER=( ('Male','Male'), ('Female','Female') ) name=models.CharField(max_length=200) email=models.EmailField(max_length=200) Mobile_Number=models.CharField(max_length=100) Gender=models.CharField(max_length=200,choices=GENDER) admin.py: from django.contrib import admin # Register your models here. from .models import Customer admin.site.register(Customer) The error that i am getting: enter image description here -
Lock file "postmaster.pid" contains wrong PID
I started my app with docker-compose.yml. Everything starts fine and works, but after a few minutes container database stops with lock file "postmaster.pid" contains wrong PID: 7834 instead of 1. I tried to delete postmaster.pid inside docker and containers, but this didn't help. I also did this procedure: How do I fix stale postmaster.pid file on Postgres?. But the problem persists. I don't understand what to do. I want to notice that I've added these lines to /opt/homebrew/var/postgresql@15/postgresql.conf and /opt/homebrew/var/postgresql@15/pg_hba.conf: postgresql.conf # Add settings for extensions here listen_addresses = '*' pg_hba.conf host movies_database app 0.0.0.0/0 md5 /opt/homebrew/var/postgresql@15/postmaster.pid 8111 /opt/homebrew/var/postgresql@15 1715706343 5432 /tmp * 936360 3407872 ready /var/lib/postgresql/data/postmaster.pid 8234 /opt/homebrew/var/postgresql@15 1715706583 5432 /tmp * 936360 3473408 ready docker logs database-1 | 2024-05-14 19:32:32.038 [1] LOG: lock file "postmaster.pid" contains wrong PID: 7834 instead of 1 database-1 | 2024-05-14 19:32:32.038 [1] LOG: performing immediate shutdown because data directory lock file is invalid database-1 | 2024-05-14 19:32:32.038 [1] LOG: received immediate shutdown request database-1 | 2024-05-14 19:32:32.056 [1] LOG: database system is shut down database-1 exited with code 0 docker-compose.yml version: '3.8' services: django: build: context: . volumes: - "./movies_admin:/movies_admin" env_file: - "movies_admin/config/.env" depends_on: - database - elasticsearch database: image: postgres:15.7 environment: - … -
Django Update on UniqueConstraint
I'm trying to work with UniqueConstraint but I've been facing some issues trying to update it the way I want. I have the following model class QueryModel(models.Model): id = models.AutoField(_("query id"), primary_key=True) user = models.ForeignKey(UserModel, on_delete=models.CASCADE) name = models.CharField(_("query name"), max_length=150) status = models.CharField( _("query status"), choices=QueryStatus.choices, default=QueryStatus.ACTIVE, ) is_favorite = models.BooleanField(_("favorite"), default=False) date_created = models.DateTimeField(_("date created"), auto_now_add=True) class Meta(object): app_label = "app" db_table = "query" constraints = [ models.UniqueConstraint( fields=("user",), condition=Q(is_favorite=True), name="unique_favorite_per_user", ) ] So in my system, users can create queries and set them as favorites, but each user can only have 1 favorite query, so I created the UniqueConstraint to enforce that business rule. Then I would have an endpoint to set a query as favorite, but is there a way for me to update that field without having to check all is_favorite fields of each user and manually setting them to False? I found this StackOverflow post from 2 years ago that proposes a solution, but this solution is not working for me, I would really appreciate some help -
Django models: a player can play many games and a game can be played exactly by two players?
I have a problem in my django models.. i have 2 models (tables) Player and Game as many to many relationship, and a third model as a intermediate table between them, that has player username as a foreignkey (the username is the player's table pk) and a game_id fk as well, and an additional attribute score, the problem is more than 2 players can have the same game, and this is not what i want, what i want is every single game can be played exactly and only by two players. how can achieve that using django? here is the models: class Player(models.Model): username = models.CharField(max_length=20, primary_key=True) fname = models.CharField(max_length=20, blank=False) lname = models.CharField(max_length=20, blank=False) avatar = models.ImageField(upload_to='./app/avatars/', blank=True, null=True) is_online = models.BooleanField(default=False) game_theme = models.ImageField(upload_to='./app/themes/', blank=True, null=True) played_games_num = models.IntegerField(default=0) def __str__(self): return self.username class Game(models.Model): mode_choices = { 'classic': 'Classic', 'vs_robot': 'Vs Robot' } difficulty_choices = { -1: 'Vs Player', 1: 'Easy', 2: 'Medium', 3: 'Hard' } game_id = models.AutoField(primary_key=True) mode = models.CharField(max_length=10, choices=mode_choices) difficulty = models.IntegerField(choices=difficulty_choices) game_date_time = models.DateTimeField(auto_now_add=True) duration = models.IntegerField() players = models.ManyToManyField(Player, through='Player_game') def __str__(self): return str(self.game_id) class Player_game(models.Model): username = models.ForeignKey(Player, on_delete=models.CASCADE) game = models.ForeignKey(Game, on_delete=models.CASCADE) score = models.IntegerField() class Meta: unique_together = … -
problem with owl.carousel.min.js?ver=1.0 and owl.carousel.min.js is working fine
I have created project using django and create admin_app and customer_app applciation. In customer_app, there is errror with third parties libraries and error like:Refused to execute script from 'http://127.0.0.1:8000/js/owl.carousel.min.js?ver=1.0' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled. code for settings.py: BASE_DIR = Path(__file__).resolve().parent.parent TEMPLATES_DIR = Path(BASE_DIR, 'templates') ADMIN_STATIC_DIR = Path(BASE_DIR, 'admin_app', 'static') CUSTOMER_STATIC_DIR = Path(BASE_DIR, 'customer_app', 'static') STATIC_URL = '/static/' STATICFILES_DIRS = [ ADMIN_STATIC_DIR, CUSTOMER_STATIC_DIR, ] base.html file script code is: <script src="{% static 'customer_app/js/jquery-3.6.0.min.js' %}"></script> <script src="{% static 'customer_app/js/asyncloader.min.js' %}"></script> <!-- JS bootstrap --> <script src="{% static 'customer_app/js/bootstrap.min.js' %}"></script> <!-- owl-carousel --> <script src="{% static 'customer_app/js/owl.carousel.min.js' %}"></script> <!-- counter-js --> <script src="{% static 'customer_app/js/jquery.waypoints.min.js' %}"></script> <script src="{% static 'customer_app/js/jquery.counterup.min.js' %}"></script> <!-- popper-js --> <script src="{% static 'customer_app/js/popper.min.js' %}"></script> <script src="{% static 'customer_app/js/swiper-bundle.min.js' %}"></script> <!-- Iscotop --> <script src="{% static 'customer_app/js/isotope.pkgd.min.js' %}"></script> <script src="{% static 'customer_app/js/jquery.magnific-popup.min.js' %}"></script> <script src="{% static 'customer_app/js/slick.min.js' %}"></script> <script src="{% static 'customer_app/js/streamlab-core.js' %}"></script> <script src="{% static 'customer_app/js/script.js' %}"></script> I to solve above mentioned error with working owl.carousel.js library effect -
Issue with Custom 404 Page Rendering in Django
I'm encountering an issue with my custom 404 page rendering functionality in Django. Despite setting up the necessary components, the custom 404 page is not being displayed when a page is not found. Here's an overview of my setup: 404 Template (error404.html): <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Page Not Found</title> </head> <body> <h1>404 - Page Not Found</h1> <p>The page you are looking for does not exist.</p> <p>Tommy the train!</p> </body> </html> 404 Template Render View (custom_404_view): from django.shortcuts import render def custom_404_view(request, exception): return render(request, 'home1/error404.html', status=404) URL Configuration (urls.py): handler404 = 'home1.views.custom_404_view' Settings: ALLOWED_HOSTS = ['localhost', '127.0.0.1', '::1'] DEBUG = True Despite configuring everything as mentioned above, the custom 404 page does not appear when a page is not found. I've ensured that DEBUG is set to True in my settings. Can anyone spot what might be causing the issue or suggest any additional troubleshooting steps? I attempted to implement custom 404 page rendering functionality in Django by following the steps outlined in my question. Here's a summary of what I tried and what I expected to happen: Implemented 404 Template: I created a custom HTML template named error404.html containing the necessary markup for a 404 error … -
Make primary key unique across multiple child classes with common parent
I have a django-polymorphic model like this: from polymorphic.models import PolymorphicModel class Item(PolymorphicModel): sku = models.CharField(primary_key=True, max_length=32) class Car(Item): pass class Boat(Item): pass To my horror, it's possible to create instances of the subclasses with the same primary key: Car.objects.create(sku='123') Boat.objects.create(sku='123') # Does NOT crash but I want it to But of course, trying to access the created object will fail horribly: >>> Car.objects.get(sku='123') polymorphic.models.PolymorphicTypeInvalid: ContentType 42 for <class 'demo_application.models.Car'> #123 does not point to a subclass! How do I ensure that all instances of Item have a unique primary key? One option I considered is overriding the save methods of Car & Boat, or listening to pre_save signals. However, that would add a database request whenever I save them, and it feels like a hacky solution. -
How to Serialize nested GM2MField in Django Rest Framework Serializer?
I'm trying to serialize a Django model field called GM2MField using Django Rest Framework's serializers. However, I'm encountering difficulty when it comes to including this field within my serializer. Here's what my model and serializer look like: #models.py from gm2m import GM2MField class Collection(models.Model): app = models.ForeignKey(Apps, on_delete=models.CASCADE, null=True) id = models.CharField(primary_key=True, max_length=32, default=uuid.uuid4, editable=False) rows = GM2MField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return str(self.id) #serializers.py from gm2m_relations.serializers import GM2MSerializer class CollectionSerializer(ModelSerializer): rows = GM2MSerializer( { SomeRow: SomeRowSerializer(), Collection: #how can i serialize this field }, many=True ) class Meta: model = Collection exclude = ['app'] As you can see, the rows field in the Collection model is of type GM2MField, which is a generic Many-to-Many field. I want to include this field in my serializer, but I'm not sure how to properly serialize it. Could someone provide guidance on how to properly serialize the Collection model within the GM2MField in my serializer? Any help would be appreciated. Thank you! -
How do I resolve the following dependancy issues?
ERROR: Cannot install -r requirements.txt (line 10), -r requirements.txt (line 15), intriniorealtime==2.2.0 and requests==2.20.0 because these package versions have conflicting dependencies. The conflict is caused by: The user requested requests==2.20.0 coreapi 2.3.3 depends on requests django-allauth 0.40.0 depends on requests intriniorealtime 2.2.0 depends on requests==2.19.1 To fix this you could try to: loosen the range of package versions you've specified remove package versions to allow pip attempt to solve the dependency conflict My requirements.txt file for python django. amqp ==2.5.2 anyjson ==0.3.3 astroid ==2.4.2 billiard ==3.6.1.0 celery ==4.4.0 certifi ==2019.9.11 cffi ==1.14.0 chardet ==3.0.4 colorama ==0.4.3 coreapi ==2.3.3 coreschema ==0.0.4 cryptography ==2.8 defusedxml ==0.6.0 Django ==2.2.6 django-allauth ==0.40.0 django-appconf ==1.0.6 django-base-url ==2019.7.24 django-compat ==1.0.15 django-cors-headers ==3.7.0 django-crispy-forms ==1.7.2 django-crontab ==0.7.1 django-cryptography ==1.1 django-markdown-deux ==1.0.5 django-pagedown ==0.1.1 django-rest-auth ==0.9.5 django-rest-passwordreset ==1.0.0 django-rest-swagger ==2.2.0 django-timezone-field ==4.0 django-unique-slugify ==1.1 djangorestframework ==3.9.4 djangorestframework-jwt ==1.8.0 future ==0.18.2 idna ==2.7 importlib-metadata ==1.3.0 intrinio-sdk ==5.0.1 intriniorealtime ==2.2.0 isort ==4.3.21 itypes ==1.1.0 Jinja2 ==2.10.3 kombu ==4.6.7 lazy-object-proxy ==1.4.3 markdown2 ==2.3.8 MarkupSafe ==1.1.1 mccabe ==0.6.1 more-itertools ==8.0.2 mysqlclient ==1.4.6 numpy ==1.18.1 oauthlib ==3.1.0 openapi-codec ==1.3.2 packaging ==19.2 pandas ==1.0.2 paypalrestsdk ==1.13.1 Pillow ==7.0.0 pip ==19.2.3 pycparser ==2.19 pyfcm ==1.4.7 PyJWT ==1.4.0 pylint ==2.5.3 pyOpenSSL ==19.1.0 pyparsing ==2.4.2 python-crontab ==2.4.0 … -
How to read the column of a selected excel file using Django
i have multiple header data in excel so how i can import the data in Django models Check the image for better understanding i am beginner at here so please dont mind my question and provide the solution please the problem is to import the data in django models -
How to chose a timezone for the Django Q cron scheduler
I am using Django-Q to create scheduled tasks through a CRON setup. I would need the schedule to have a timezone information. Example : "30 8 * * 1" with UTC would be 8:30 UTC (regardless of the Django timezone defined in my settings) Will I need to create a cluster per timezone and define them as broker depending on the task timezone ? -
Django-tables2: Populate table with data from different database tables (with model.inheritance)
I want to show data from different database tables on a django-tables2 table. I have several apps with each app having some database tables (with each table in its own file). Project structure: --project -all -overview all/models/compound.py class Compound (models.Model): name = models.CharField(max_length = 100, unique = True, verbose_name="Probe") dateAdded = models.DateField(); class Meta: app_label = 'all' all/models/probe.py class Probe(Compound): mechanismOfAction = models.CharField(max_length = 255, verbose_name="Mode of action") def get_absolute_url(self): return reverse('overview:probe_detail', args=[str(self.id)]) def __str__(self): return f'{self.name}, {self.mechanismOfAction}' class Meta: app_label = 'all' all/models/negativeControl.py class NegativeControl(Compound): probeId = models.ForeignKey(Probe, on_delete=models.CASCADE, related_name="controls", verbose_name="Control") class Meta: app_label = 'all' overview/models/usageData.py class UsageData (models.Model): cellularUsageConc = models.CharField (max_length = 50, null = True, verbose_name="Recommended concentration") probeId = models.ForeignKey(Probe, on_delete=models.CASCADE, related_name="usageData") def __str__(self): return f'{self.cellularUsageConc}, {self.inVivoUsage}, {self.recommendation}' class Meta: app_label = 'overview' all/tables.py class AllProbesTable(tables.Table): Probe = tables.Column(accessor="probe.name", linkify=True) control = tables.Column(accessor="probe.controls") mechanismOfAction = tables.Column() cellularUsageConc = tables.Column(accessor="usageData.cellularUsageConc") class Meta: template_name = "django_tables2/bootstrap5-responsive.html" all/views.py class AllProbesView(SingleTableView): table_class = AllProbesTable queryset = queryset = Probe.objects.all().prefetch_related('usageData', 'controls') template_name = "all/probe_list.html" all/templates/all/probe_list.html {% load render_table from django_tables2 %} {% render_table table %} The rendered table shows all headers correct and has data for the "Probe" and "Mode of action". For the "Control", I get "all.NegativeControl.None" and for …