Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Converting Date to "1434758400000" with pd.datetime in Django
I'm working on a Django project, and I've encountered an issue when using the pd.datetime function. When I try to convert a date using pd.datetime, it's returning a value like "1434758400000" instead of a proper datetime object. I'm puzzled by this behavior and unsure of what could be causing it. Here's a code snippet that illustrates the problem: # Convert the 'date' column to a datetime object df['date'] = pd.to_datetime(df['date']) # Create a DataFrame to represent all unique date-district combinations unique_dates = pd.date_range(start=df['date'].min(), end=df['date'].max()) unique_districts = df['pdistrict'].unique() date_district_combinations = pd.MultiIndex.from_product([unique_dates, unique_districts], names=['date', 'pdistrict']) full_df = pd.DataFrame(index=date_district_combinations).reset_index() # Merge this new DataFrame with your original data to fill in missing combinations filled_df = full_df.merge(df, on=['date', 'pdistrict'], how='left') # Fill missing 'cases' with 0 or cumulative sum filled_df['cases'].fillna(0, inplace=True) The output of this code is something like: "1434758400000". I would expect the output to be a valid datetime object, but this unexpected behavior is causing issues in my project. Has anyone encountered this before or can provide insights into what might be going wrong? I've checked my code and the input date format, and they seem correct. Could there be any configuration settings in Django or Pandas that could cause this issue? … -
Password authentication failed while running taiga on localhost through source code
I am trying to configure taiga on localhost with source code .At start while creating taiga database i had put password which is same as django password and as well as machine paasword . Still it shows password authentication failed for user taiga . Given below is the command and after which it shows errro enter image description here command :- python manage.py migrate --noinput output :- taiga issue taiga issue 978×506 122 KB I have done some changes in pg_hba file Database administrative login by Unix domain socket local all postgres peer TYPE DATABASE USER ADDRESS METHOD “local” is for Unix domain socket connections only local all all md5 IPv4 local connections: host all all 127.0.0.1/32 scram-sha-256 IPv6 local connections: host all all ::1/128 scram-sha-256 Allow replication connections from localhost, by a user with the replication privilege. local replication all peer host replication all 127.0.0.1/32 scram-sha-256 host replication all ::1/128 scram-sha-256 local all taiga peer local all taiga md5 local all taiga peer host taiga taiga 127.0.0.1/32 md5 Here the password is same as the password of Taiga database user , postgres and django as well as machine. Below is the output when i try to access postgres with … -
Django-import-export. Export selected records only?
I'm using the great django-import-export addition. We standard have 2 options import and export. I would like to have an extra option to export selected records only. Would be a nice addition. How can I achieve this? I use the standard configuration in the Django admin. -
TypeError at / TodoListServices.list_todo_paginate() missing 1 required positional argument: 'page'
//Views class TodoList(APIView): def get(self,request,page=None, format=None): todos = [] if page is not None: todos = TodoListServices.list_todo_paginate(page) else: todos = TodoListServices.list_todo_paginate(1) serializer = TodoSerializer(todos, many=True, context={'request': request}) return Response(serializer.data, status=status.HTTP_200_OK) //Services class TodoListServices: @staticmethod def list_todo_paginate(page): page_number = page page_size = 10 if page_number is None: page_number = 1 todos = todo.objects.all()[ (page_number - 1) * page_size: page_number * page_size ] return todos I am getting a TypeError : missing 1 required positional argument how do I solve this ? -
Increase email sending limit SMTP Go daddy
I have a GoDaddy workspace email which I am using in Django project using smtp smtpout.secureserver.net port 587 the problem is when on new user creation in my Django project I sent out verification email and as soon as it sends 5 emails it reach limit and gives error "it has exceeded its 24-hour sending limit. Messages to 5 recipients out of 5 allowed have been sent. Relay quota will reset in 24 hours." -
Django project with qn informix database
I'm currently working on a django project that connects to my infomix database (using the 64-bit ODBC driver) and it works perfectly, the problem is that when I try to insert the data in Arabic language, it doesn't work and I get an odbc error. I tried using 32-bit ODBC and it worked as it should. I was wondering how to get 64-bit odbc to accept the encoding or features of other languages or can I use another approach to connect my project to infomix? as using 32-bit odbc is not an option. I hope you can help me and thank you in advance. Inserting data in aranic into my infomix database -
What is to best way in Django to replace emails with other notification solution?
I have a site with an increasing number of user (now about 500 active users). I need to send notifications to them several times a day and I see that the email notification is not the best way to notify them because they get lots of emails from others. I need to send personal informations like tasks, notifications about comments, etc. so I need to send DM's. I wonder if somebody has experience with chat solutions like Discord, Viber, Telegram, Discord, WhatsApp. I'm using Slack for some purposes but I don't want to add the users to a Slack channel to send DM's. I 'm sending about 3.000-5.000 notifications in a month. The budget is an important thing because I don't want to bill extra fees to the users for using a chat app and not email. Thank you in advance! -
Website not working without www in https domain
I have made a django chatting application that works when the URL is https://www.aniconnect.org but it does not work when it is just https://aniconnect.org I don't know why this is happening but I did some digging and it supposedly might be caused by my nginx configuration or something is wrong with letsencrypt, my SSL certificate provider. The following is my nginx configuration: server { listen 80; server_name www.aniconnect.org my.ip.address aniconnect.org; listen 443 ssl; ssl_certificate /etc/letsencrypt/live/www.aniconnect.org/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/www.aniconnect.org/privkey.pem; include /etc/letsencrypt/options-ssl-nginx.conf; ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { alias /home/gamedeveloper/anime_chat/anime_chat_app/static/; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } location /ws/ { proxy_pass http://127.0.0.1:8001; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; } } I followed the guide at https://certbot.eff.org/instructions?ws=nginx&os=ubuntufocal to get my ssl certificate for www.aniconnect.org which worked (also the reason why the site might be only visible at www.aniconnect.org) and I tried to activate my SSL certificate for aniconnect.org using certbot and this was the output: gamedeveloper@animechatapp:~$ sudo certbot --nginx Saving debug log to /var/log/letsencrypt/letsencrypt.log Which names would you like to activate HTTPS for? We recommend selecting either all domains, or all domains in a VirtualHost/server block. - - - - … -
RuntimeError: Failed to lock Pipfile.lock - while installing mysqlclient
when I try to install mysqlclient on my Django project, I am facing this error. since I am a complete beginner for python-jango, could someone help me out on solving this issue? -
How can do i use django to register a new user?
I’m fairly new to django. How can i use abstractBaseUser class to create a custom user (with basic email, password, username, etc) and create a function based view that handles the httpRequest after it was mapped from the urls in the app? I basically want to create a function based view that processes a specific POST request to create a new user and returns a response with the successful user creation announcement. I want to handle user login as well. Thank you in advance! I thought about just processing the Http request and validating the fields and then saving the new user object in the database if the user submitted valid information. -
Restrict Access to DRF subdomain on host
I have a main domain which is for my Vue.js that is domain.com and I also have a sub-domain for my DRF backend with the name of api.domain.com; I do not want that the api and urls in my backend to be accessible under the corresponded url; e.g if anyone enters the url of api.domain.com/companies my backend info and data are being shown there but I want to remove access for anyone to see all of the pages of the backend subdomain. How can I do that? -
How to delete row when use Django only templates
I tried several options but to no avail. How can I get the job done if I only use templates? I want to delete the selected record with a button. I also have an add button in the html, after the add button it shows me the base again. All entries come with a delete button, but I can't get the job done. urls.py: urlpatterns = [ path("", views.index, name='index'), path("all_flat", views.all_flat, name='all_flat'), path("contact", views.contact, name='contact'), path("about", views.about, name='about'), path("save", views.testing, name='save'), #path("save/<int:pk>", views.delete, name='delete'), ] views.py: @api_view(['GET', 'POST']) def testing(request): mydata = models.FlatModelSqlite.objects.all() serializer_class = serializers.FlatSerializerSqlite(mydata, many=True) if request.method == "GET": html_save = "MyHome/save.html" template = loader.get_template(html_save) context = { 'mymembers': serializer_class.data, 'flatP': ForecastField_all(), } return HttpResponse(template.render(context, request)) elif request.method == "POST": item_serializer = serializers.FlatSerializerSqlite(data=request.data) if item_serializer.is_valid(): item_serializer.save() return HttpResponseRedirect(redirect_to='save') else: er = item_serializer.errors html_save = "MyHome/save.html" template = loader.get_template(html_save) context = { 'mymembers': serializer_class.data, 'flatP': ForecastField_all(), 'errors': er, } return HttpResponse(template.render(context, request)) #@api_view(['GET', 'POST']) #def delete(request, pk): # if request.method == 'POST': # flat_delete = models.FlatModelSqlite.objects.get(pk=pk) # flat_delete.delete() # return HttpResponse(redirect_to='save') html /save: {% for x in mymembers %} <tr> <td>{{ x.id }}</td> <td>{{ x.Address_N }}</td> <td>{{ x.Project_N }}</td> <td>{{ x.Fasi }}</td> <td>{{ x.Status }}</td> <td> <form method="post"> … -
ERROR An error occurred (AccessDenied) when calling the DeleteObject operation: Access Denied
Deleting Object from s3 cause Access Denied Error my s3 IAM { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "s3:*", "s3-object-lambda:*" ], "Resource": "*" } ] } settings.py INSTALLED_APPS = [ 'storages', ] DEFAULT_FILE_STORAGE = "storages.backends.s3boto3.S3Boto3Storage" django code def UpdateCompanyView(request): user = request.user company = user.company old_logo = company.logo if old_logo and 'logo' in serializer.validated_data and data_logo is not None: old_logo.delete() #old_logo.delete(save=False)#I've tried this also other all actions working put, add, but deleting occurring this error -
Issue when trying to connect to mssql using Django
I'm trying to connect my mssql to my Django project. I've tried using pyodbc outside of the project and that works. But when i'll try to connect inside the project it doesn't work.. I have tried "mssql-django" and "pyodbc-django". The error i get is: [Microsoft][ODBC SQL Server Driver]Invalid connection string attribute (0)') At the driver string i have also tried, "ODBC Driver 17 for SQL Server". DATABASES = { "default": { "ENGINE": "mssql", "NAME": "####", "USER": "####", "PASSWORD": "####", "HOST": "####", "PORT": "", "OPTIONS": {"driver": "SQL Server", ## "ODBC Driver 17 for SQL Server" }, }, } -
Static files deploy on Render
How to deploy python-django static files in cloud like render I've deployed the webapp but i'm not able to get my static files I've also used the command python manage.py collectstatic -
Why can’t I log in using the token contained in the cookie on mobile?
The front end uses React and the back end uses Django, each communicates with a server with a different domain in AWS, and the login functions work well on the web Currently, my functions only work when I am logged in, but when I move to another page, the token contained in the cookie disappears and the login expires Of course, the login expiration setting is set so that it expires when the refreshtoken expires. The current problem is that it works well on the web, but when I log in through mobile, the server sends me a refresh token in the header, but maybe it doesn't recognize it, or the login expires right away when I move to another page The logic is to put only the refresh token in the header as httponly, set samesite=none and secure, and receive the access token as a response upon logging in, store it in a local cookie, and reissue it by refreshing the header every time it expires Why does the token disappear when changing pages only on mobile devices? I'm not sure if it's a problem with the token settings coming from the header, or if the problem is that … -
Django db rollback specific commits
I have a django model called User I have a method that takes a list of different user updates like this [user1_payload, user2_payload, user3_payload,...,user100_payload] Some updates can fail in the database. There is another third party api which takes a list of user updates and perform the update action on their end. I would like to take only the successful updates in the database and call the third party api. Keep in mind that the third party api can also have some failed update operations and will return a response like this: { "successful_users": [1, 3, 5,...], "failed_users": [2, 4,...] } In case of the failed users in the third party api, i want to rollback those updates in my db. How can I achieve this using minimum number of db transactions and minimum number of api calls using django? -
RuntimeError Failed to lock Pipfile.lock
im a beginner on learning Django. That too on my new Mac. while I was install mysqlclient for my project using this command pipenv install mysqlclient I get this error saying RuntimeError: Failed to lock Pipfile.lock! how can I fix this? demo) chandanm@Chandans-MacBook-Air demo % pipenv install mysqlclient Courtesy Notice: Pipenv found itself running within a virtual environment, so it will automatically use that environment, instead of creating its own for any project. You can set PIPENV_IGNORE_VIRTUALENVS=1 to force pipenv to ignore that environment and create its own instead. You can set PIPENV_VERBOSITY=-1 to suppress this warning. Installing mysqlclient... Resolving mysqlclient... Added mysqlclient to Pipfile's [packages] ... ✔ Installation Succeeded Pipfile.lock (e35515) out of date, updating to (537503)... Locking [packages] dependencies... Building requirements... Resolving dependencies... ✘ Locking Failed! ⠴ Locking...False ERROR:pip.subprocessor:Getting requirements to build wheel exited with 1 [ResolutionFailure]: File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/pipenv/resolver.py", line 645, in _main [ResolutionFailure]: resolve_packages( [ResolutionFailure]: File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/pipenv/resolver.py", line 612, in resolve_packages [ResolutionFailure]: results, resolver = resolve( [ResolutionFailure]: ^^^^^^^^ [ResolutionFailure]: File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/pipenv/resolver.py", line 592, in resolve [ResolutionFailure]: return resolve_deps( [ResolutionFailure]: ^^^^^^^^^^^^^ [ResolutionFailure]: File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/pipenv/utils/resolver.py", line 908, in resolve_deps [ResolutionFailure]: results, hashes, internal_resolver = actually_resolve_deps( [ResolutionFailure]: ^^^^^^^^^^^^^^^^^^^^^^ [ResolutionFailure]: File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/pipenv/utils/resolver.py", line 681, in actually_resolve_deps [ResolutionFailure]: resolver.resolve() [ResolutionFailure]: File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/pipenv/utils/resolver.py", … -
Django deployment failure
I'm in the process of trying to deploy a Django project, and I'm running into difficulties getting it on the web. Let me run through the issues I'm having at the moment: I SSH into a remote server and am trying to deploy the project there. I don't currently have a domain name, so right now I'm using the IP address. I have set up both Gunicorn and Nginx and have them running, but when I go to the browser and try to access the site via 'https://...', I get the following error: Request Method: GET Request URL: http://**.**.***.***/ Using the URLconf defined in apegd_ai_core.urls, Django tried these URL patterns, in this order: admin/ The empty path didn’t match any of these. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. I have a Gunicorn .service file under '/etc/systemd/system' called 'apegd_ai.service'. The configuration is as follows: [Unit] Description=Gunicorn instance to serve application After=network.target [Service] User=john Group=john WorkingDirectory=/home/john/graph_django/apegd_ai_core ExecStart=/home/bobby/Documents/graph_project/vDect2/bin/gunicorn -w 4 -b 0.0.0.0:8007 --error-logfile /home/john/gra> Environment="DJANGO_SECRET_KEY=encrptedsecretkey" [Install] WantedBy=multi-user.target I have an Nginx configuration file called apegd_ai.conf under /etc/nginx/sites-enabled, which looks like this: server … -
How can I add Svelte to my docker container with Django?
I have managed to create a docker and get running a django project. This is the Dockerfile FROM python:3.12-slim-bullseye ENV PYTHONUNBUFFERED 1 COPY ./requirements.txt /requirements.txt RUN pip install -r /requirements.txt RUN mkdir /app WORKDIR /app COPY ./app /app RUN adduser --disabled-login user USER user and this is the dockercompose version: "3.9" services: db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=XXXXX - POSTGRES_USER=XXX - POSTGRES_PASSWORD=XXX app: build: context: . command: > sh -c "python manage.py collectstatic --noinput && python manage.py migrate && python manage.py runserver 0.0.0.0:XXXX" volumes: - ./app:/app ports: - "XXXXX" environment: - POSTGRES_NAME=XXXXX - POSTGRES_USER=XXXXXX - POSTGRES_PASSWORD=XXXXX depends_on: - db What do I need to modify to be able to add Svelte in the same docker? And what if I wanted to add SvelteKit? I saw something about multistage builds but I don't fully understand it -
"django.db.utils.ProgrammingError: relation does not exist" In production
I've been working on a feature for the past couple of months that hinges on a new one-to-many relation called "user_company". While in the development environment, I only had to migrate once the company model was created and haven't had any problems with it since but I haven't been able to update the production environment due to a "Django.db.utils.ProgrammingError: relation "app_company" does not exist" error. This throws the docker into a loop of "You can't run the app since it won't compile" and "I can't migrate the tables since the app ain't running" what can I do to either circumvent the error and migrate the table before it fails or ignore the table long enough for it to compile? Currently the user.company attribute looks like this: ... company = models.ForeignKey( Company, verbose_name=_("Company"), help_text=_("Company name where the user works at"), default=Company.get_default(), on_delete=models.CASCADE ) ... while the company model looks like this: class Company(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=100) description = models.TextField(max_length=500) file = models.FileField(blank=True, null=True, upload_to=partial( storage.upload_location, path="pidenomina"), validators=[file.FileValidator(allowed_extensions=['csv'], max_size=5242880)], verbose_name='File') # TODO - Created at def __str__(self): return self.name def get_default(): try: return Company.objects.first().pk except Company.DoesNotExist: company = Company.objects.create(id=1, name="Void", description="") company.save() return company Any help is appreciated, cheers. -
Cookiecutter Django Docker Hot Reloading Not Detecting Changes
I have recently created a new Docker project using cookiecutter-django. I've done this before and "hot reloading" has worked, however for some reason changes are not being detected properly in this project. The docs start to reload, and then detect no changes, as shown in the image below. Does anyone know why this is, or how to fix it? Thanks for any help anyone can offer! -
How can Django QuerySet filters modify the fields for comparison? (Like inet6_aton for IP addresses.)
Take this MySQL database for example, which stores IP addresses as strings in either IPv4 or IPv6 format. name | ip ------+--------------------------------------- Tony | 127.0.0.1 Jones | 2001:db8:3333:4444:5555:6666:7777:8888 This is the equivalent SQL I need to run, where VALUE is the variable determined by the website's user and already converted to a numeric value for comparison: select name from customers where name like 'J%' and hex(inet6_aton(ip)) > VALUE; Here is my filter, which would work if the ip field was already the numeric equivalent instead of a string: filter = Q(name__startswith="J") filter &= Q(ip__gt=VALUE) Alas, the ip values in the database are only stored as strings. (This is not my decision, and I cannot change it.) I need to perform the hex and inet6_aton functions on the fields in the database. How can I achieve this? Note: This is a very simplified version of what I am working with. These filters will apply to multiple searches across dozens of tables per search. I fear I may need to rework much of the established code to get this to work. -
How to get current user categories in ModelForm?
There is word study app. Currecnt user create own category with set of words. The idea is to customize the list of options in the selection form for the current user. models.py class ModelWords(models.Model): class Meta: verbose_name = 'Words' verbose_name_plural = 'Words' your_language_name = models.CharField(max_length=40) eng_name = models.CharField(max_length=40) cat = models.ForeignKey('ModelCatsWords', on_delete=models.CASCADE, null=True) author = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) def __str__(self): return self.your_language_name class ModelCatsWords(models.Model): class Meta: verbose_name = 'Categories' verbose_name_plural = 'Categories' name = models.CharField(max_length=100, db_index=True) author = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) def __str__(self): return self.name def get_absolute_url(self): return reverse('category', kwargs={'cat_id': self.pk}) There is two forms. The first form to add words to it and there is a list of user categories to choose, another form to add categories. forms.py class WordsFrom(forms.ModelForm): cat = forms.ChoiceField(choices=[], required=False, label="select cat") def __init__(self, *args, **kwargs): self.request = kwargs.pop('request', None) super(WordsFrom, self).__init__(*args, **kwargs) self.fields['cat'].choices = ModelCatsWords.objects.filter(author=self.request.user.id).values_list('name') for visible in self.visible_fields(): visible.field.widget.attrs['placeholder'] = visible.field.label class Meta: model = ModelWords fields = ['your_language_name', 'eng_name','cat'] labels = { 'your_language_name' : 'word on your language', 'eng_name' : 'word on english', 'cat' : 'categorie' } class ModelCatsWordsForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['name'].widget.attrs['placeholder'] = 'categorie' class Meta: model = ModelCatsWords fields = ['name'] labels = { 'name': 'Categorie' } There is views.py class … -
Django: can't load images but static files OK
I'm learning Django, and I've spent a week+ trying to display images in my app. I think that there's an issue with my settings but I'm perplexed since the static files are loading, though the images with similar settings are not. What confuses me so much is that my static files are loaded ok at MEDIA_ROOT/static, but that image files aren't found at MEDIA_ROOT/media. Based on settings.py, static seems like it would live at # C:\Users\...\final\static but it's clear that this isn't true. structure ├── final │ ├── dogtracks │ │ ├── static | │ │ ├── dogtracks │ ├── media | │ ├── images settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') ... MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') # C:\Users\...\final\media models.py class Animal(models.Model): ... photo = models.ImageField(upload_to='images', null=True, blank=True) ... class AnimalForm(ModelForm): class Meta: model = Animal fields = ['name', 'breed', 'species', 'birthday', 'photo'] html {% if pet.photo %} <img src="final{{ pet.photo.url }}" /> {% else %} <img src="{% static 'dogtracks/noun-pet.png' %}" /> {% endif %} I've read dozens of answers here on SO and gone through tutorials online. I've moved the location of my images folder to try to show these images.