Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
How to grab the active tabs URL from an opend browser(64-bit Linux system) using python
i trying to make an desktop monitoring system for linux based OS. When I work with this code I get the currently opend applications in my system and browser tabs and its title also. But I want the urls too. If any one know about this please help. Here is my views.py file from django.http import JsonResponse import subprocess import re import threading import time from urllib.parse import urlparse opened_applications = [] def get_domain_name(url): parsed_url = urlparse(url) domain = parsed_url.netloc if domain.startswith("www."): domain = domain[4:] # Remove 'www.' if present return domain def extract_search_query(title): # Common patterns indicating a search query in browser titles search_patterns = ["Google Search", "Google", "Bing", "Yahoo", "DuckDuckGo"] # Check if any of the search patterns are present in the title for pattern in search_patterns: if pattern.lower() in title.lower(): # Extract the search query using string manipulation query_start_index = title.lower().find(pattern.lower()) + len(pattern) search_query = title[query_start_index:].strip() return search_query return "Search Query Placeholder" def monitor_opened_applications(): global opened_applications try: while True: # Get a list of window titles using wmctrl output = subprocess.check_output(["wmctrl", "-lx"]).decode("utf-8") # Extract application names from window titles new_opened_applications = [] for line in output.split("\n"): # print("++++++++++", line) if line: match = re.match(r"^(\w+\s+\S+)\s+(\S+)\s+(.+)$", line) if match: … -
message from channels not gettion to reciver the right
when i send a message from a user not getting to the recipient or recevier.but only getting the message who sended as revceived message and it was to in sended messages. # consumer.py import json from channels.consumer import AsyncConsumer from channels.generic.websocket import WebsocketConsumer, AsyncWebsocketConsumer from channels.db import database_sync_to_async from rest_framework.authtoken.models import Token from rest_framework_simplejwt.tokens import RefreshToken,AccessToken from asgiref.sync import async_to_sync from api.models import UserModel as User,Message,Rooms from django.db.models import Q import uuid class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): token=(self.scope['url_route']['kwargs']['token']) receiver_id=self.scope['url_route']['kwargs']['receiver_id'] receiver= await self.get_user_by_id(receiver_id) sender=await self.get_user_object(token=token) gname=await self.get_room(sender,receiver) self.roomGroupName = gname await self.channel_layer.group_add( self.roomGroupName, self.channel_name ) await self.accept() async def disconnect(self, close_code): await self.channel_layer.group_discard( self.roomGroupName, self.channel_layer ) async def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json["message"] username = text_data_json["username"] print(self.roomGroupName, self.channel_name) user= await self.get_user_object(token=(self.scope['url_route']['kwargs']['token'])) await self.channel_layer.group_send( self.roomGroupName, { "type": "sendMessage", "message": message, "username": username, }) async def sendMessage(self, event): message = event["message"] user_id = self.scope['url_route']['kwargs']['receiver_id'] print(user_id,'fdsfsdfsdfsdfwerrrrrreee') receiver= await self.get_user_by_id(user_id) token=self.scope['url_route']['kwargs']['token'] print(token) user = await self.get_user_object(token) print(user) await self.create_message(sender=user,message=message,room_name=self.roomGroupName,receiver=receiver) await self.send(text_data=json.dumps({"message": message, "username": user.username,'to':'ihsan'})) @database_sync_to_async def get_user_by_id(self,id): return User.objects.filter(id=id).first() @database_sync_to_async def get_user_object(self, token): token=AccessToken(token=token) return User.objects.get(id=token.payload['user_id']) @database_sync_to_async def create_message(self,sender,receiver,message,room_name): messageObj=Message.objects.create(sender=sender,receiver=receiver,message=message) room=Rooms.objects.get(groupName=room_name) messageObj.save() room.messages.add(messageObj) room.save() return messageObj @database_sync_to_async def get_room(self,user1,user2): print(user1.id,user2.id) room=Rooms.objects.filter(Q(users__id=user1.id)&Q(users__id=user2.id)).first() if room: return room.groupName else: room=Rooms(groupName=str(uuid.uuid1())) room.save() room.users.add(user1) room.users.add(user2) return room.groupName … -
Django form problem on Model object and redirect
I'm facing 2 problems when creating Form in Django: Problem on redirect after submitting Form Model object is not iterable Specifically, I'm creating feedback form and all my code is as below. There are 4 files and using crispy_form to show the form in html file. Everything works fine except after I click on submit button. It cannot return to the same feedback form with blank fields, and it shows the error 'BugTypes' object is not iterable Please check and help. Thank you! # models.py from django.db import models # Create your models here. class BugTypes(models.Model): bugType = models.CharField(max_length=100) def __str__(self): return self.bugType class UserFeedback(models.Model): username = models.CharField(max_length=100) problem = models.CharField(max_length=255) bugType = models.ManyToManyField("BugTypes", related_name='userFeedBack') feedback = models.TextField() def __str__(self): return self. Problem # forms.py from django import forms from survey.models import UserFeedback, BugTypes class FeedbackForm(forms.ModelForm): username = forms.CharField( widget = forms.TextInput( attrs={'class': 'form-control'} ) ) problem = forms.CharField( widget = forms.TextInput( attrs = {'class': 'form-control'} ) ) bugType = forms.ModelChoiceField( queryset = BugTypes.objects.all(), widget = forms.Select( attrs={'class': 'form-control'} )) feedback = forms.CharField( widget = forms.Textarea( attrs = {'class': 'form-control'} )) class Meta: model = UserFeedback fields = "__all__" # views.py from django.shortcuts import render from django.urls import reverse from … -
'int' object has no attribute 'username'
iam try to loop through a following users list,and i got this error say "'int' object has no attribute 'username'" def Home(request): profile = Profile.objects.get(user=request.user) posts = Post_Upload.objects.all() #show only the user posts you following user_following_list = FollowersCount.objects.filter(user=request.user).values_list('follower', flat=True) print(user_following_list) feed_lists = Post_Upload.objects.filter(user__in=user_following_list) #user suggestion all_users = User.objects.all() all_following_users = [] for users in user_following_list: user_list = User.objects.get(username=users.username) all_following_users.append(user_list) new_suggestion = [ X for x in list(all_users) if (x not in list(all_following_users))] current_user = User.objects.filter(username=request.user.username) final_suggestion = [X for x in list(new_suggestion) if (x not in list(current_user))] random.shuffle(final_suggestion) user_profile = [] user_profile_list = [] for users in final_suggestion: user_profile.append((users.id)) for ids in user_profile: profiles = Profile.objects.filter(id=ids) user_profile_list.append(profiles) suggestion_user_profile_list = list(chain(*user_profile_list)) context = {"posts":feed_lists,"profile":profile,"suggestion_user_profile_list":suggestion_user_profile_list[:4]} return render(request,'index.html',context) i try to change the users.username into users then i am getting this error say "User matching query does not exist." the problem are showing here user_list = User.objects.get(username=users.username) -
KeyError at / 118 in django deployment
I have created a workflow for my repository and everything even the deployment is going fine and i have created the model in same environment as in the docker and workflow is running but still i am getting this: Environment: Request Method: GET Request URL: http://mysite-olvdmbamqa-el.a.run.app/ Django Version: 4.0.2 Python Version: 3.11.5 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'welcome_deck', 'movie_recommender', 'irisapp'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "/usr/local/lib/python3.11/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/usr/local/lib/python3.11/site-packages/django/core/handlers/base.py", line 167, in _get_response callback, callback_args, callback_kwargs = self.resolve_request(request) File "/usr/local/lib/python3.11/site-packages/django/core/handlers/base.py", line 290, in resolve_request resolver_match = resolver.resolve(request.path_info) File "/usr/local/lib/python3.11/site-packages/django/urls/resolvers.py", line 592, in resolve for pattern in self.url_patterns: File "/usr/local/lib/python3.11/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/usr/local/lib/python3.11/site-packages/django/urls/resolvers.py", line 634, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/usr/local/lib/python3.11/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/usr/local/lib/python3.11/site-packages/django/urls/resolvers.py", line 627, in urlconf_module return import_module(self.urlconf_name) File "/usr/local/lib/python3.11/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 <source code not available> File "<frozen importlib._bootstrap>", line 1176, in _find_and_load <source code not available> File "<frozen importlib._bootstrap>", line 1147, in _find_and_load_unlocked <source code not available> … -
Annotate django queryset based on related field attributes
Suppose you have this models structure in a django project from django.db import models class Object(models.Model): name = models.CharField(max_length=100) class ObjectEvent(models.Model): class EventTypes(models.IntegerChoices): CREATED = 1, "Created" SCHEDULED = 2, "Scheduled" COMPLETED = 3, "Completed" CANCELED = 4, "Canceled" event_type = models.IntegerField(choices=EventTypes.choices) object = models.ForeignKey(Object, on_delete=models.CASCADE, related_name="events") I now want to access the derived property ended which is defined as every object that have an event of type COMPLETED or CANCELED. I already did that with the @property decorator, but as I want to be able to filter using ended attribute. So I'm trying to implement this through the annotate queryset method. class ObjectManager(models.Manager): def get_queryset(self): qs = super().get_queryset() qs = qs.annotate( ended=models.Case( models.When( events__event_type__in=( ObjectEvent.EventTypes.COMPLETED, ObjectEvent.EventTypes.CANCELED, ), then=models.Value(True), ), default=models.Value(False), output_field=models.BooleanField( verbose_name="Object ended", ), ) ) return qs class Object(models.Model): objects = ObjectManager() name = models.CharField(max_length=100) fake_data.json [ { "model": "main.object", "pk": 1, "fields": { "name": "task1" } }, { "model": "main.object", "pk": 2, "fields": { "name": "task2" } }, { "model": "main.object", "pk": 3, "fields": { "name": "task3" } }, { "model": "main.object", "pk": 4, "fields": { "name": "task4" } }, { "model": "main.objectevent", "pk": 1, "fields": { "event_type": 1, "object": 1 } }, { "model": "main.objectevent", "pk": … -
Sending a notification to single user using web socket in django
In my drf project, I have added the functionality where notifications are being broadcasted to all web socket users. What I want is to send notification to single user. I hope I will get a solution to my problem. I am using django-channels and web sockets. -
Why not just set Django's ALLOWED_HOSTS to ["*"]?
I understand why validation of the host header is important but I do not understand why this would be the responsibility of Django. The docs for the settings mysteriously mention which are possible even under many seemingly-safe web server configurations. and the docs for the host header validation mention something similar: Because even seemingly-secure web server configurations are susceptible to fake Host headers and Previous versions of this document recommended configuring your web server to ensure it validates incoming HTTP Host headers. While this is still recommended, in many common web servers a configuration that seems to validate the Host header may not in fact do so. For instance, even if Apache [..] In 2024, is there still any reason to fear these "many" (undocumented) "seemingly-safe server configurations" or can I just use a sane proxy server and let that do the validation instead? Setting ALLOWED_HOSTS to ["*"] removes one more thing to think about while deploying. -
How to add a custom check in `validate_constaints` function considering the instance yet to be committed?
I'd like to use this constraint on my Django model: models.UniqueConstraint( fields=["edificio", "studio"], condition=models.Q(attiva=True), name="unique_attiva_per_edificio_studio", violation_error_message=_( "cannot have two active configurations for the same studio", ), ) But since I'm on MariaDB (and I cannot change it) conditional constraints/indexes aren't supported yet. So I'm extending the validate_constraints function in my EdificioConfigurazione model to check it. def validate_constraints(self, exclude=None): super().validate_constraints(exclude) # TODO: this will be removed once MySQL/MariaDB supports conditional constraints manager = EdificioConfigurazione.objects multiple_attiva_per_edificio = ( manager.values("edificio", "studio") .annotate( rcount=models.Count("id", filter=models.F("attiva")), ) .filter(rcount__gt=1) ) if multiple_attiva_per_edificio.exists(): violation_error_message = _( "cannot have two active configurations for the same studio", ) raise ValidationError(violation_error_message) Assuming this is the right approach to do this (I'm open to suggestions), I cannot enforce this check since the instance to be added/modified (which is self) is not committed to the DB yet. How can I use the instance? My idea would be looking at the self.pk field and: if self.pk is None: I add the instance to the queryset before the checks else: the instance is already in the DB (I'm modifying it for example) so I need to update the queryset to use it instead of the one committed. Once again, I don't know if extending … -
use dynamic string for model key in django
For exampkle I have tabel like this, class FormSelector(models.Model): prefs = models.JSONField(default=dict,null=True, blank=True) items = models.JSONField(default=dict,null=True, blank=True) then in views, I want to do like this, json = {"prefs":[1,2],"items":[2,3,4]} mo = FormSelector.objects.last() for key in json: // key is string "prefs","items" mo.{key} = di[key] // I want to do the equivalent to mo.prefs , mo.items Is there any good method to do this? -
Does React have XSS attack protection?
The object from Django Rest Framework is: Object { id: 3, user: {…}, photos: (1) […], caption: '<script>console.log("Hacked lol")</script>'} and my React component is: function Post({post}) { return ( <div id="post" className="post w-full max-w-xl p-2 mt-4 rounded-2xl bg-main-box"> <div id="post-caption"> {post.caption} </div> </div> ) Will it prevent this XSS attack on caption or will it put the caption as it is? -
Why does using logging in django corrupt log files?
When I was using logging in my django project, I found that after 2-3 requests for an excuse, the log file got corrupted. Why in settings.py LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'formatters': { 'standard': { 'format': '%(asctime)s %(levelname)-8s [%(pathname)s:%(lineno)d] [%(funcName)s] [%(message)s]' } }, 'handlers': { 'console_handler': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'standard', }, 'info_handler': { 'level': 'INFO', 'class': 'logging.handlers.TimedRotatingFileHandler', 'formatter': 'standard', 'filename': os.path.join(INFO_LOG_DIR, 'info.log'), 'when': 'midnight', 'backupCount': 30, 'encoding': 'UTF-8', }, 'error_handler': { 'level': 'ERROR', 'class': 'logging.handlers.TimedRotatingFileHandler', 'formatter': 'standard', 'filename': os.path.join(ERROR_LOG_DIR, 'error.log'), 'when': 'midnight', 'backupCount': 30, 'encoding': 'UTF-8', }, 'homework': { 'level': 'DEBUG', 'class': 'logging.handlers.RotatingFileHandler', 'formatter': 'standard', 'filename': os.path.join(HOMEWORK_LOG_DIR, 'homework.log'), 'maxBytes': 1024 * 1024 * 10, 'backupCount': 100, 'encoding': 'UTF-8', } }, 'loggers': { 'data_analysis': { 'handlers': ['console_handler', 'info_handler', 'error_handler'], 'level': 'DEBUG', 'propagate': True, }, 'homework': { 'handlers': ['homework', 'console_handler'], 'level': 'DEBUG', 'propagate': True, } }, } in other py file: log = logging.getLogger("data_analysis") But after sending a few requests, the log file looks like this python version: 3.6.8 django version: 3.2.3 Part of my project uses multithreading, but when I was testing, I commented out the multithreaded code I want to be able to log properly -
NameError in Choices= LACTATION STAGES in meta class in models. py
It is just saying that in ... lactation_stage = models.Instegerfield(editable=False, choices= LACTATION_STAGES,) there is a nameError in name'LACTATION_STAGES, is not defined Just expecting some one to help me i am a beginner -
ModuleNotFound error in migration of new model
This is my model: class Company(models.Model): class LTRCharField(models.CharField): def formfield(self, **kwargs): defaults = {'widget': TextInput(attrs={'dir': 'ltr'})} defaults.update(kwargs) return super().formfield(**defaults) title = models.CharField(_('company title'), max_length=255) logo = FileBrowseField( _('company logo'), max_length=255, directory='company/', extensions=['.png'] ) address = models.TextField(_('company address')) phone = LTRCharField(_('company phone'), max_length=20) class Meta: verbose_name = _('company') verbose_name_plural = _('company') def __str__(self): return self.title The migrate management command gives me this error: ModuleNotFoundError: No module named 'company.models.Company'; 'company.models' is not a package When I look at the migration file I see this line has error: import company.models.Company I can't figure out what is the issue here? -
Django - Adding more options to AdminTimeWidget
I tried to add more time choices to AdminTimeWidget by overriding DateTimeShortcuts refering to this post also another similar posts on SO. My problems is I am getting Uncaught ReferenceError: DateTimeShortcuts is not defined and jQuery.Deferred exception: DateTimeShortcuts is not defined ReferenceError: DateTimeShortcuts is not defined at HTMLDocument error on console. I am newbie to django, I did not understant why I am getting this error. Here is how I implemented it: (function($) { $(document).ready(function() { DateTimeShortcuts.clockHours.default_ = [ ['16:30', 16.5], ['17:30', 17.5], ['18:00', 18], ['19:00', 19], ['20:00', 20], ]; DateTimeShortcuts.handleClockQuicklink = function (num, val) { let d; if (val == -1) { d = DateTimeShortcuts.now(); } else { const h = val | 0; const m = (val - h) * 60; d = new Date(1970, 1, 1, h, m, 0, 0); } DateTimeShortcuts.clockInputs[num].value = d.strftime(get_format('TIME_INPUT_FORMATS')[0]); DateTimeShortcuts.clockInputs[num].focus(); DateTimeShortcuts.dismissClock(num); }; }); })(jQuery); and in my ModelAdmin I included this JS file in Media class as below: @admin.register(models.MyModel) class MyAdminModel(): // other stuff list_filter = [("created", custom_titled_datetime_range_filter("By created"))] class Media: js = ("admin/js/DateTimeShortcuts.js",) Also I have a custom datetime range filter implemented as: def custom_titled_datetime_range_filter(title): class CustomDateTimeRangeFilter(DateTimeRangeFilter): def __init__(self, field, request, params, model, model_admin, field_path): super().__init__(field, request, params, model, model_admin, field_path) … -
'error: subprocess-exited-with-error' while installing my requirements/local.txt file after cloning the repo [duplicate]
Installing build dependencies ... done Getting requirements to build wheel ... done Preparing metadata (pyproject.toml) ... error error: subprocess-exited-with-error × Preparing metadata (pyproject.toml) did not run successfully. │ exit code: 1 ╰─> [8 lines of output] running dist_info creating C:\Users\Dell\AppData\Local\Temp\pip-modern-metadata-o75tij8k\psycopg_c.egg-info writing C:\Users\Dell\AppData\Local\Temp\pip-modern-metadata-o75tij8k\psycopg_c.egg-info\PKG-INFO writing dependency_links to C:\Users\Dell\AppData\Local\Temp\pip-modern-metadata-o75tij8k\psycopg_c.egg-info\dependency_links.txt writing top-level names to C:\Users\Dell\AppData\Local\Temp\pip-modern-metadata-o75tij8k\psycopg_c.egg-info\top_level.txt writing manifest file 'C:\Users\Dell\AppData\Local\Temp\pip-modern-metadata-o75tij8k\psycopg_c.egg-info\SOURCES.txt' couldn't run 'pg_config' --includedir: [WinError 2] The system cannot find the file specified error: [WinError 2] The system cannot find the file specified [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: metadata-generation-failed × Encountered error while generating package metadata. ╰─> See above for output. note: This is an issue with the package mentioned above, not pip. hint: See above for details. I'm encountering this error while installing requirements/local.txt after cloning repo, what could be the reason and a solution for this? I was expecting all the dependencies to be installed but encountered this error -
Manager isn't available in django
My Register view is like below. class UserRegisterView( FormView ): template_name = 'register.html' form_class = UserCreationForm redirect_authenticated_user = True success_url = reverse_lazy('dashboard') # name of URL def form_valid( self, form ): user = form.save() if user is not None: login( self.request, user ) return super( UserRegisterView, self ).form_valid( form ) def get( self, *args, **kwargs ): if self.request.user.is_authenticated: return redirect('register') return super( UserRegisterView, self ).get( *args, **kwargs ) My model is like below. from django.db import models from django.contrib.auth.models import AbstractUser # Create your models here. class User(AbstractUser): GENDER_CHOICES = ( ('M', 'Male'), ('F', 'Female'), ('O', 'Other'), ) USER_TYPE = ( ('S', 'Super Admin'), ('A', 'Admin'), ('P', 'Patient'), ('D', 'Doctor'), ('U', 'User'), ) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) date_of_birth = models.DateField(null=True, blank=True ) gender = models.CharField(max_length=1, choices=GENDER_CHOICES) user_type = models.CharField(max_length=1, choices=USER_TYPE) username = models.EmailField(unique=True) email = models.EmailField(unique=True) phone = models.CharField(max_length=15, blank=True, null=True) address = models.TextField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) active = models.BooleanField(default=True) REQUIRED_FIELDS = [] def __str__(self): return f"{self.first_name} {self.last_name}" I am getting error Manager isn't available; 'auth.User' has been swapped for 'hospital.User'