Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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: -
Django - How to display a list friend requests
I am currently following a guide on making friends in Django and stumbled upon a problem. As i am fairly new to Django and Python, i am unsure of to display a list of friend requests that has been to a user. I am following this guide https://medium.com/analytics-vidhya/add-friends-with-689a2fa4e41d and i have tried to implement the for loop in Step 5 part 2 as they stated that they can display a list of all friend requests. However, i can not seem to display anything and they have not shown their code on how to do so. Here is my friend_request function in views.py in an attempt to try and gather all friend requests. All my other code are the same as guide previously linked above. So if possible, can anyone guide me on how to display all friend requests that are sent to a user? def friend_requests(request, requestID): all_friend_requests = FriendRequest.objects.get(to_user=requestID) context = { 'all_friend_requests': all_friend_requests } return ('/', context) -
running django project on another pc
I am using mysql as the database of the django project, mysql is installed on the computer I will install, but after the migrate process on the other computer I installed, an error comes up and only django does its own migrate process, the models in my models.py files do not pass to the database. ?:(mysql.w002) MariaDB Strict Mode is not set for database connection 'default' HINT: MariaDB's strict mode fixes many data intergity problems in mariadb, such as data truncation upon insertion,by escalating warnings into errors. It is strongly recommended you active it see: https://docs.djangoproject.com/en/ref/databases/mysql-sql-mode enter image description here -
quickbooks-api did not recognize attribute auth
I recently update may Django app which is connected to quickbooks to python 3.9.16. Due to this change, I've an issue : QuickBooks' object has no attribute 'auth_client': My code is : try: auth_client = AuthClient( client_id=CLIENT_ID, client_secret=CLIENT_SECRET, environment=ENV, redirect_uri=REDIRECT_URI, ) except Exception as exc: logging.info('log credentials SELECT Errors: {} - {}'.format(companyId, exc)) chek = 'Nok' # creating the client object to access the QBO account - if not able to connect, make 3 tries dans then stop if chek != 'Nok': tries = 1 logging.info('Trying to connect to QBO') for i in range(tries): try: client = QuickBooks( auth_client=auth_client, refresh_token=REFRESH_TOKEN, company_id=COMPANY_ID, ) # get the refresh token returned refresh_token_new = client.auth_client.refresh_token Error is on last lign. seems that it does not understand: client.auth_client in requirements.txt I have (extract): sqlalchemy intuit-oauth python-quickbooks pandas unidecode gunicorn without version infos.So should be last version -
Javascript file is not working on templates in django?
Static setting is right?My javascript file is not running in django templates? Tried using static file setting and loading static before tags -
How to filter objects by value of one of its fields in django?
I have django application with urls.py: path('<str:slug>/', views.article), When user types name of product in my website, the view is triggered: def article(request, slug): videos = models.Video.objects.filter(article=slug) return render(request, 'videos/at_detail.html', {'videos': videos}) If I add print(slug) somewhere in function it returns the word I entered in url, so this part works. models: class article(models.Model): name = models.CharField(max_length=30, null=True) slug = AutoSlugField(populate_from='name', unique=True, default=None) created_on = models.DateTimeField(default=timezone.now) owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, default=None) def __str__(self): return self.name class Meta: verbose_name = "Articles" class Video(models.Model): video_id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False ) title = models.CharField(max_length=50) description = models.CharField(max_length=500) file = models.FileField() article = models.ForeignKey(at, on_delete=models.CASCADE) def __str__(self): return str(self.title) + " - " + str(self.at) class Meta: verbose_name_plural = "Videos" verbose_name = "Video" What doesn't work, and what I'm trying to do, is to get all objects, which have same value 'article', that what I entered in my url. So for example: if I type 127.0.0.1:8000/blueberry/ I will get all objects with field article=blueberry. Is this possible and if it is, how can I do that?