Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django-Debug-Toolbar doesn't appear
I am trying a lot to appear Debug-tool but it doesn't appear. First I install it using pipenv: pipenv install django-debug-toolbar Here settings.py: INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "rest_framework", "BookListAPI", "debug_toolbar", # added debug-tool here ] 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", 'debug_toolbar.middleware.DebugToolbarMiddleware', # added debug_toolbar.middleware ] # added INTERNAL_IPS INTERNAL_IPS = [ '127.0.0.1', ] urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path("admin/", admin.site.urls), path("api/", include('BookListAPI.urls')), path("__debug__/", include('debug_toolbar.urls')), ] I don't know why debug-tool doesn't appear. -
Can I get some assistance with a Django/SQLite3 schema?
I am trying to put together a Django app that will show the teams and games for my fantasy football league. I have taken a few cracks at the models, but I can't get my head wrapped around how they will relate. This is what I am trying to accomplish: Each year, there are six teams that make the "Toilet Bowl" tournament, which will crown the worst team in the league. There are three rounds. The worst two teams are not playing the first round. That leaves team 1 playing team 4 and team 2 playing team 3. In round 2, teams 1 and 2 play the losers from round 1. In round 3, the remaining two teams play for the title. These are the models that I have so far. I know that they're not optimal. class Owner(models.Model): name = models.CharField(max_length=200) email = models.EmailField(max_length=100) phone = models.CharField(max_length=12, null=True) def __str__(self): return "%s" % (self.name) class Team(models.Model): owner = models.ForeignKey(Owner, on_delete=models.CASCADE) name = models.CharField(max_length=200) def __str__(self): return self.name class Game(models.Model): year = models.SmallIntegerField( validators=[MinValueValidator(2010), MaxValueValidator(2999), RegexValidator("^(20)([1-5][0-9])$") ]) round = models.SmallIntegerField( validators=[MinValueValidator(1), MaxValueValidator(3)]) teams = models.ManyToManyField(Team) #teams = models.ForeignKey(Team, on_delete=models.CASCADE) #team1_score = models.IntegerField(default=0) #team2_id = models.ForeignKey(Team, on_delete=models.CASCADE) #team2_score = models.IntegerField(default=0) def … -
Django Rest Framework + SimpleJWT returns 401 on unprotected routes
I have configured DRF to use JWT as an authentication scheme and for the most part works correctly however when a user's token & refresh token are no longer valid rather than returning a 200 as an unauthorized user for unprotected routes and displaying the website as if they are no longer logged in the backend returns a 401. I am new to the Django auth scheme / middleware setup but my assumption would be that if the default is AllowAny then a bad token would be ignored. Is there a configuration that I am missing. From the DRF Docs If not specified, this setting defaults to allowing unrestricted access: 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.AllowAny', ] my settings.py REST_FRAMEWORK = { ... "DEFAULT_AUTHENTICATION_CLASSES": ( "rest_framework.authentication.BasicAuthentication", "rest_framework_simplejwt.authentication.JWTAuthentication", ), } SIMPLE_JWT = { "ACCESS_TOKEN_LIFETIME": datetime.timedelta(minutes=15), "REFRESH_TOKEN_LIFETIME": datetime.timedelta(days=2), ... } Example ViewSet that returns 401 with bad access token class PromoApiSet(ViewSet): serializer_class = PromoSerializer def get_queryset(self, *args, **kwargs): time_now = timezone.now() return PromoNotification.objects.filter( end_date__gte=time_now, start_date__lte=time_now ) # @method_decorator(cache_page(120)) def list(self, request): promos = self.get_queryset() serializer = self.serializer_class(promos, many=True) promos_data = serializer.data response_data = {"promos": promos_data} return Response(response_data) -
Filtering broadcasts by date and category at the same time
I am developing a Django website and faced the following problem: I need to filter broadcasts by date (the date is specified by the user) and category. Screenshot: https://i.stack.imgur.com/5V1Or.png Could you tell me how to implement such a thing shown in the screenshot? Attempts to form a get request with parameters were unsuccessful -
change in fonts and spacing in a django app
I installed django bootstrap5 but it seems to have messed up the css and fonts and i can't seem to figure out what went wrong..I have a website am trying to clone, innitially things looked pretty the same until i tried installing django bootstrap and django tailwinds, well i later uninstalled tailwinds but the mess is still there. here is the pic of the changesThe current changes in the interface Here is what it looked like innitially and how the website itself looks like website fonts -
Query with a variable
I would like to execute a query with a variable I tried to do this but it doesn't work def requeteDB(sql_request): with connection.cursor() as cursor: cursor.execute(sql_request) row = cursor.fetchall() return row def queryWithVar(): var = 'something with spaces' return(''' Select col1 From table1 Where col2 = %s ''', [var]) queryWithVar() ('\n Select col1\n From table1\n Where col2 = %s\n ', ['something']) requeteDB(queryWithVar()) TypeError: argument 1 must be a string or unicode object: got tuple instead -
How to use a list in a raw django SQL query that uses `WHERE ... IN (...)`?
How do you inject a list parameter into a Django raw query? Given a list of UUIDs i'd like to be able to inject them into the () in a WHERE ... IN (...) query. list_of_uuids = [ "<UUID_1>", "<UUID_2> ] Output for SQL: SELECT * FROM some_model_table WHERE some_model_table.uuid IN ( "<UUID_1>", "<UUID_2>" ) So I tried doing the following using raw django queries: query_set = SomeModel.objects.raw("SELECT * FROM some_model_table where some_model_table.uuid IN %s", [list_of_uuids]) Unfortunately, the above will give the following error: django.db.utils.ProgrammingError: syntax error at or near "ARRAY": LINE X: WHERE uuid IN ARRAY['00123... Which means the list is interpreted as an array and passed to the SQL query as an array, which cannot be used in an IN query. Enclosing the injected array in () also doesn't work: LINE X: WHERE uuid IN IN (ARRAY['00123... ^ HINT: No operator matches the given name and argument types. You might need to add explicit type casts. Note: I'm aware this particular example can be done with Django ORM, but my actual query is more complex than this and has to be done with raw queries, and contains this WHERE ... IN (...) syntax. I just kept the irrelevant … -
i cant display url tag in template
views.py ` def Product_details (request , product_name): product_detail = Product.objects.get(pk=product_name) return render (request, 'product_detail.html', { 'product_detail' : product_detail, }) ` urls.py ` urlpatterns = [ path('', views.Product_list , name= 'Product_list'), path('product/<int:product_name>/', views.Product_details , name= 'Product_details'), product_detail.html ` <a href="{% url 'Product_details' product.name %} `` display url tag in page -
Pandas Converts My date string value in date column to an integer
I have an excel file which I am using pd.read_excel() to read, inside the excel file are couple of date columns (the date data type is a string and must follow this format: dd/mm/yyyy. The problem I have is that when the excel file gets converted to a dataframe using pd.read_excel(), the values gets converted into an integer. Does anyone know how I can maintain the value in the excel file after it has been converted to a dataframe. Screenshot below: The columns with the date format What the values get converted to after converting the file to a dataframe "43800" is what the value of "Incorporation Date" got converted to. What I have tried: for column in columns_with_date_string: client_entity_df[column] = pd.to_datetime( client_entity_df[column].astype(int) ) client_entity_df[column] = client_entity_df[column].dt.strftime('%d/%m/%Y') This approach returned the values as "01/01/1970", instead of the dates specified TLDR: I basically want to maintain the value of my date columns (12/11/2022) in my excel file where the format is "dd/mm/yyy" when the excel file gets converted to a dataframe, pandas currently changes the values to an integer (which I assume is an epoch) when it converts the file to an integer. -
The Django serializer for MongoDB does not display data correctly
So, I have 2 models, Flow and Steps. I want that when the Flows are displayed, the steps corresponding to this flow should also be displayed, something that doesn't happen even though it should. (I want to specify that before switching to Mongo, I was using another library for the serializer and everything was working perfectly, now not, and I need it this way) Flow Model: class Flow(BaseModel): class BrowserInstance(Enum): CHROME = 'chrome' FIREFOX = 'firefox' name = StringField() url = URLField() browser = StringField(choices=list(item.value for item in BrowserInstance), default=BrowserInstance.CHROME.value) scheduling = StringField() next_schedule = DateTimeField(default=timezone.now, null=True) is_active = BooleanField(default=False) user = ReferenceField(User, reverse_delete_rule=CASCADE, null=False) Step model: class Step(BaseModel): class Action(Enum): CLICK = 'click' TAPPING = 'tapping' SUBMIT = 'submit' CLEAR = 'clear' ENTER = 'enter' step_number = IntField() action = StringField(choices=list(item.value for item in Action), default=Action.CLICK.value) selector_xpath = StringField(max_length=254) content = StringField(max_length=254, blank=True) flow = ReferenceField(Flow, reverse_delete_rule=CASCADE, related_name='steps') Step Serializer class StepSerializer(DocumentSerializer): class Meta: pattern = Step fields = ('id', 'step_number', 'action', 'selector_xpath', 'content') FlowSerializer class FlowSerializer(DocumentSerializer): steps = StepSerializer(many=True, required=False, allow_null=True) class Meta: model = Flow fields = "__all__" When I execute the get / retrieve endpoint, next to the steps I receive the value null (if I … -
how to set relevent foreign key django in form
I want to submit video in section wise. i create section.When i want create a video i want to set my course name by default and want to show relevent section. Course class Course(models.Model): instructor = models.ForeignKey(UserProfile,on_delete=models.CASCADE) name = models.CharField(max_length = 50 , null = False,unique = True) slug = models.CharField(max_length = 50 , null = False , unique = True) Section: class SectionVideo(models.Model): course = models.ForeignKey(Course , null = False , on_delete=models.CASCADE) name = models.CharField(max_length = 50 , null = False) slug = models.CharField(max_length = 50 , null = False ) serial_number = models.IntegerField(null=False) video: class Video(models.Model): section_video = models.ForeignKey(SectionVideo , null = False , on_delete = models.CASCADE) course = models.ForeignKey(Course , null = False , on_delete = models.CASCADE) title = models.CharField(max_length = 100 , null = False) video_description = models.CharField(max_length = 500 , null = True) how i will make my create-form for videos. -
Django: Filter matching objects using 2 fields
Sorry if the title is not very telling I have the following classes: class Event(Model): ... class IOCType(Model): name = CharField(max_length=50) class IOCInfo(Model): event = ForeignKey(Event, on_delete=CASCADE, related_name="iocs" ioc_type = ForeignKey(IOCType, on_delete=CASCADE) value = CharField(max_lenght=50) Each event has one or several IOCs associated with it, which are stored in the IOCInfo table. This is how my IOCInfo table looks like after creating some events: id value event_id ioc_type_id 1 some-value1 eventid1 4 2 some-value2 eventid1 8 3 some-value3 eventid1 8 4 some-value4 eventid1 1 5 some-value3 eventid2 8 6 some-value1 eventid2 1 7 some-value2 eventid3 8 8 some-value3 eventid4 8 What I want to do is to take an event, compare its IOCInfo with those of other events and get back those events that match. This is what I have done so far and it works, but I fear that as the database grows and the app has more users this query will end up being a bottleneck def search_matches(event): matches = Event.objects.none() for ioc in event.iocs.all(): matches |= Event.objects.filter( iocs__ioc_type=ioc.ioc_type, iocs__value=ioc.value ) return matches.exclude(event=event.id) If I pass the eventid2 to The above function, it will return eventid1 and eventid4 as expected. Any suggestions to improve this function using any … -
Django Channels AsyncWebSocketConsumer ConnectionClosedError 1005
I am writing a django channels application and noticed an exception when handling a heartbeat function related to websocket status code which I haven't been able to find any existing issues for. This is in an AsyncWebsocketConsumer backed by redis. ConnectionClosedError: websockets.exceptions.ConnectionClosedError: received 1005 (no status code [internal]); then sent 1005 (no status code [internal]) async def receive(self, text_data): try: if text_data == "healthcheck": await self.send( text_data=json.dumps({"type": "healthcheck", "data": self.group_name}) ) else: logger.info(f"Unsupported WS Event: {text_data}") pass except: logger.exception("Failed to handle message from client") Also receive this error RuntimeError: RuntimeError: Unexpected ASGI message 'websocket.send', after sending 'websocket.close'. My disconnect implementation is async def disconnect(self, close_code): try: # Leave room group await self.channel_layer.group_discard(self.group_name, self.channel_name) await self.log_request("disconnect") except: logger.exception("Failed to disconnect user from socket") -
In DRF, how to get dictionary format in JSON response rather than List of dcitionaries
How to get dictionary format in JSON response rather than List of dictionaries. Right now am getting response like list of dictionaries and I want to get response without list. #Response I get for example [ { "id": 40, "full_name": "Don Ser 1", "email": "Donny@sfds.com", "phone": 12345, "address_line_1": "sdsdsdsd", "address_line_2": "dsdsdsd", }, { "id": 41, "full_name": "Don Ser 2", "email": "Donny@sfds.com", "phone": 121356456, "address_line_1": "sdsdsdsd", "address_line_2": "dsdsdsd", } ] #Response I Like to get is without List. [ { "id": 40, "full_name": "Don Ser 1", "email": "Donny@sfds.com", "phone": 12345, "address_line_1": "sdsdsdsd", "address_line_2": "dsdsdsd", }, { "id": 41, "full_name": "Don Ser 2", "email": "Donny@sfds.com", "phone": 121356456, "address_line_1": "sdsdsdsd", "address_line_2": "dsdsdsd", } } How do I achieve this? Additionally I like to know why it returned it in List rather than dictionary? -
pest practice in for loop
1- in the code below I get an error name should be unique because there is a loop in for... def test_new_user_email_normalized(self): """Test email is normalized for new users.""" sample_emails = [ ["test1@EXAMPLE.com", "test1@example.com"], ["Test2@Example.com", "Test2@example.com"], ["TEST3@EXAMPLE.com", "TEST3@example.com"], ["test4@example.COM", "test4@example.com"], ] for email, expected in sample_emails: user = get_user_model().objects.create_user(email, name, "sample123") self.assertEqual(user.email, expected) I fixed the problem by editing the code to be like that def test_new_user_email_normalized(self): """Test email is normalized for new users.""" sample_emails = [ ["test1@EXAMPLE.com", "test1@example.com"], ["Test2@Example.com", "Test2@example.com"], ["TEST3@EXAMPLE.com", "TEST3@example.com"], ["test4@example.COM", "test4@example.com"], ] n = 1 # new for email, expected in sample_emails: n = n + 1 # new name = "name" + str(n) # new user = get_user_model().objects.create_user(email, name, "sample123") self.assertEqual(user.email, expected) and here is my question did I do it right as the best practice or anything else or there is a better way like in my question 2 for example? 2- can I add my condition in "for" itself like for email, expected in sample_emails and n in range(1,5): -
Django-cron library does not seems to work?
my project.settings.py CRON_CLASSES = ["user_statistic_status.cron.UserLoginCronJob",] my user_statistic_status.cron.py class UserLoginCronJob(CronJobBase): # checking if the user has taken a class in the last 24 h RUN_EVERY_MINS = 1 # every 2 hours schedule = Schedule(run_every_mins=RUN_EVERY_MINS) code = 'user_statistic_status.UserLoginCronJob' def do(self, request): today: date = timezone.now().date() print(f"Today's date is {today}") My app is registered in the settings.py When I run python manage.py runcrons I get : Running Crons ======================================== [✘] user_statistic_status.UserLoginCronJob Can anyone help out here, not sure why my task is not being triggered at all as I don't get the print() call -
How to properly set Passkeys for Django?
I'm trying to apply Passkeys to a Django project, but I'm new to both and am finding difficulties. So following instructions I found here on how to add Passkeys I'm supposed to the following code to my settings.py file: AUTHENTICATION_BACKENDS = \['passkeys.backend.PasskeyModelBackend'\] # Change your authentication backend FIDO_SERVER_ID="localhost" # Server rp id for FIDO2, it the full domain of your project FIDO_SERVER_NAME="MTGStore" import passkeys KEY_ATTACHMENT = NONE | passkeys.Attachment.CROSS_PLATFORM | passkeys.Attachment.PLATFORM NONE is not a keyword in Python though, so I've tried using None but that gave me a TypeError: unsupported operand type(s) for *: 'NoneType' and 'AuthenticatorAttachment' error. Also thought I am using localhost for my server ID, I'm not sure what to add for my authentication backend. What am I missing? Thanks! -
Query set to count all records on secondary table in ManyToMany relationship in Django Templates
How to count the total number of readers associated with each book in the index.html file? The first loop loops through readers and provides a sum for the number of books associated with each reader. The second loop does not count the number of books a reader has read (I understand why). I'm trying to count the total number of readers associated with each book. Is there a way to complete this task within the index.html file? Or should this be done in views.py? -
cronjob is failing to send email in production server whereas in localhost it is working fine
I'm working on a project in which a reminder email has to be sent whenever the scheduled time is met. For example, if the reminder date and time is set to the Dec17, 6am. then the email has to be sent automatically on Dec17, 6am. This works fine in my local host without any issue, But when I deploy it in production environment the auto email is not getting sent. `def my_scheduled_job(): try: if settings.RUN_SCHEDULER: utc = pytz.utc ist = pytz.timezone('Asia/Calcutta') json_data = {} tickets = Ticket.objects.filter(is_active = True).exclude(state_history__state__item = 'Completed') for rem in tickets: for dt in rem.reminder.all(): ind_utc = datetime.today() + timedelta(hours=5, minutes=30) remainder_date = dt.date_time d1 = datetime.strptime(remainder_date.strftime('%Y-%m-%d %H:%M:%S'), '%Y-%m-%d %H:%M:%S') d2 = datetime.strptime(ind_utc.strftime('%Y-%m-%d %H:%M'), '%Y-%m-%d %H:%M') if d1 == d2: to_addr, obj_cnt = [], rem.reminder.count() filt_cnt = rem.reminder.filter(id__gte = dt.id).count() if obj_cnt == filt_cnt: if rem.users.all(): for user in rem.users.all(): user_name = User.objects.values_list('username',flat=True).get(id=user.id) to_addr.append(user_name) else: for group in rem.groups.all(): users = User.objects.filter(groups__id=group.id) for user in users: to_addr.append(user.username) to_addr = list(set(to_addr)) json_data['tickets'] = rem # json_data['urlObject'] = base.HOSTNAME html = render_to_string('email/cronjob.html', json_data) mail = mail_function('sending mail from FMS', to_addr, html) cron_logger.info("-------Scheduled mail sent to assigned user-----") elif (obj_cnt-1) == filt_cnt: if rem.users.all(): for user in rem.users.all(): user_name … -
How to solve CSRF verification faileld?
Request aborted. Help Reason given for failure: Origin checking failed - https://teamsparrowpp-qrgen-production 6a43.up.railway.app does not match any trusted origins. I have <form method="POST">{% csrf_token %} on my html. I have tried adding on settings CSRF_TRUSTED_ORIGINS = ['https://teamsparrowpp-qrgen-production-6a43.up.railway.app'] But it's not working. -
Django Apache and name-based VirtualHost
I have recently locally deployed Django project on Apache server Fedora 36. Everything work good when accessing site by ip. The issue that could not access it by hostname. I am getting "Bad Request (400)" error. here my httpd.conf <VirtualHost *:80> ServerName calljournal.local alias /static /var/www/django_project/call_journal/static <Directory /var/www/django_project/call_journal/static> Require all granted </Directory> <Directory /var/www/django_project/call_journal> Require all granted </Directory> WSGIDaemonProcess calljournal.local python-path=/var/www/django_project/virt/lib/python3.8/site-packages WSGIProcessGroup calljournal.local WSGIScriptAlias / /var/www/django_project/call_journal/call_journal/wsgi.py redirect / https://192.168.1.109 </VirtualHost> and my hosts file ::1 localhost localhost.localdomain localhost6 localhost6.localdomain6 192.168.1.109 calljournal.local -
Subquery in Django ORM
I have following models. My goal is to extract 2 recent Comments per Post. Is that possible? class Post(models.Model): author = models.ForeignKey(Author, related_name="posts", on_delete=models.CASCADE) title = models.CharField(max_length=256) text = models.TextField(blank=True, default="") created_at = models.DateTimeField(default=datetime.now, blank=True) @property def comments_number(self): return self.comments.count() def __str__(self, *args, **kwargs): return f"{self.title}" class Comment(models.Model): post = models.ForeignKey(Post, related_name="comments", on_delete=models.CASCADE) author = models.ForeignKey(Author, related_name="comment", on_delete=models.CASCADE) text = models.TextField() created_at = models.DateTimeField(default=datetime.now, blank=True) The closest try I've got is this one: newest = Comment.objects.filter(post=OuterRef('pk')).order_by('-created_at') recent_comments = Post.objects.annotate(newest_comments=Subquery(newest.values('text')[:2])) And than when I call recent_comments.values_list() I can see the newest one comment per Post obj (only one) but this is not what I want exactly. I have spend a lot of time on it guys and have no clue... -
Multiple Django Projects using IIS but Getting Blank Page on Second Site
I'm running two django projects in IIS with wfastcgi enabled. The first django project is running without an issue but the second project displays a blank page (code 200) returned. Second Project Info: A virtual folder, within it's own application pool in IIS, is created to host the second project. The second project was created in an python environment folder. The second project runs from django using python manage.py runserver 0.0.0.0:8080, but displays a blank page when browsing to the virtual folder page. The root folder was granted with "everyone" full control access to all sub-folders for the second project, wfastcgi application and handler is pointing to the virtual environment python and wfastcgi file correctly. Can you have two wfastcgi applications and handlers "Second Python FastCGI" C:\project_folder\project_env\Scripts\python.exe|C:\project_folder\project_env\lib\site-packages\wfastcgi.py" I wanted them separate so that two developers don't interfere with each others work, but they need to run within the same server and port. -
Django queryset filter with if condition?
I want to write conditions for fields in a model in Django filter. but i don't know how to do it.I try but it doesn't work views.py telefonS = MateryalEkle.objects.filter( eklenmeTarihi__range=(baslangicTarihi, bitisTarihi), dosyaBilgileriBaglanti__durum="ŞUBEDE", (islemDurumu="İŞLEM BEKLİYOR" or islemDurumu="GELEN" ) and exportDurumu = "" ).values('cinsi').annotate(Count('cinsi')) models.py class MateryalEkle(models.Model): cinsi = models.CharField(max_length=50, choices=MATERYALCINSI, verbose_name='MATERYAL CİNSİ') islemDurumu = models.CharField(max_length=50, choices=ISLEMDURUM, verbose_name='İşlem Durumu', default='İŞLEM BEKLİYOR') exportDurumu = models.CharField(max_length=50, choices=EXPORTDURUM, verbose_name='Export Durumu', blank=True) imajTuru = models.CharField(max_length=50, choices=IMAJTURU, verbose_name='İmaj Türü', blank=Tru -
I'm creating update in model using django framework pthon and facing issue of page not found 404
Using the URLconf defined in BVH.urls, Django tried these URL patterns, in this order: