Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to run threads with django
How to run thread with Django how to send data inside views file from django.shortcuts import render from django.http.response import HttpResponse from datetime import datetime from .pnet import Worker1 global value value = False def home(request): global value if value == False: Worker1.start() print(a) value = True today = datetime.today() return render(request, "home.html")` pnet.py import threading class Worker1(threading.Thread): def run(self): a = 10` -
Not Working the Migrationfrom Django to Postgres and MongoDb
I am a newcomer to MongoDB and currently attempting to establish a connection between MongoDB and Django. However, I have been successful in establishing a connection with Postgres, but I am facing difficulties in connecting to MongoDB. Although there are no errors occurring during the migration process, I am not seeing any migration on the MongoDB side. Setting.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'base_app.apps.BaseAppConfig', 'document_app.apps.DocumentAppConfig', ] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'HOST': os.environ.get('POSTGRES_HOST'), 'NAME': os.environ.get('POSTGRES_NAME'), 'USER': os.environ.get('POSTGRES_USER'), 'PASSWORD': os.environ.get('POSTGRES_PASSWORD'), 'PORT': os.environ.get('POSTGRES_PORT'), }, "mongodb": { "ENGINE": "djongo", "NAME": os.environ.get('MONGO_DB_NAME'), "CLIENT": { "host": os.environ.get('MONGO_DB_HOST'), "port": int(os.environ.get('MONGO_DB_PORT')), # "username": os.environ.get('MONGO_DB_USERNAME'), # "password": os.environ.get('MONGO_DB_PASSWORD'), }, 'TEST': { 'MIRROR': 'default', }, } } DATABASE_ROUTERS = ['base_app.utils.routers.MyRouter', 'document_app.utils.routers.MyRouter'] base_app/model.py class PostgresModel(models.Model): # fields for Postgres database here title = models.CharField(max_length=100) content = models.TextField() class Meta: db_table = 'postgres_model' app_label = 'base_app' managed = True abstract = False document_app\models.py from djongo import models as djmodels from django.db import models class MongoDBModel(djmodels.Model): # fields for MongoDB database here name = models.CharField(max_length=100) age = models.IntegerField() address = models.CharField(max_length=200) class Meta: db_table = 'mongodb_model' app_label = 'document_app' managed = True abstract = False class MongoDBDocument(djmodels.Model): # fields for MongoDB database here name = … -
django - mariadb 1146 error after change database
used pytest-django==3.5.0 aws rds-mariadb 10.6 To upgrade the version 10.3 to 10.6 of my mariaDB, I upgraded and switched the version of green using blue/green of aws rds. On the surface, both the table and the data seemed fine. But after the change, django throws error 1146. After changing the database, I thought it was a cache problem, so I tried changing the url route address, but it didn't work. I also tried running makemigrations and migrate in manage.py but it didn't work. Now, I think the django Model's meta doesn't seem to apply. Because my actual table name is alarminfo in lowercase but the error log says (1146, "Table 'db.AlarmInfo' doesn't exist") are indicated in uppercase. class AlarmInfo(models.Model): alarmUID = models.BigAutoField(db_column='AlarmUID', primary_key=True) # Field name made lowercase. userUID = models.BigIntegerField(db_column='UserUID') # Field name made lowercase. alarmType = models.IntegerField(db_column='AlarmType') # Field name made lowercase. content = models.TextField(db_column='Content') # Field name made lowercase. registerDate = models.DateTimeField(db_column='RegisterDate') # Field name made lowercase. class Meta: managed = False db_table = 'alarminfo' I'm assuming this might be the problem, but I haven't been able to find a solution. Is this something that has changed in mariadb 10.6 or the action I need to take … -
Trying to get the other user but keep getting the current user
I have this simple friendship model for users. I am trying to get the friends of the user that is currently logged in. Since friends means a relationship doesn't matter if you are user or friend I would like to get all the users that are not the current user. The friendship model: # WHEN A USER BECOMES FRIENDS WITH ANOTHER USER class Friendship(models.Model): user = models.ForeignKey( User, on_delete=models.CASCADE ) friend = models.ForeignKey( User, on_delete=models.CASCADE, related_name="friends" ) created_at = models.DateTimeField(auto_now_add=True, verbose_name="created at") updated_at = models.DateTimeField(auto_now=True, verbose_name="updated at") class Meta: unique_together = ["user", "friend"] verbose_name = "friendship" verbose_name_plural = "friendships" ordering = ["created_at"] def __str__(self): return "{} is friends with {}".format(self.user, self.friend) def save(self, *args, **kwargs): if self.user == self.friend: return "Same person friendship should happen mentally" else: super().save(*args, **kwargs) The function I am using to get the friends: def get_friends(queryset, request, *args, **kwargs): id = kwargs['user'] user = User.objects.get(id=id) friends = [f.user for f in Friendship.objects.all().filter((Q(user=user) | Q(friend=user)))] return queryset.filter(user__in=friends) I keep getting the logged in user as friend instead of the other users that are not the logged in user. What am I doing wrong here please? -
How to Update file name in FileField after file is uploaded on s3 via presigned post URL in Django?
I have integrated django-storages in Django Project. for large file sizes, I have used a pre-signed URL to upload files from externally without taking a load on my server. by pre-signed URL, Files uploaded successfully in the s3 bucket AWS, after uploading the file in s3 I need to update the name of the file in FileField. -
How to change Log out icon in jazzmin django theme?
i have django project with jazzmin theme library i use, i've change icon for sidebar with "icons:{...}" and i want to change the user menu icons, the logout menu: what i know is, we can use this line: "usermenu_links" : {} but i don't quite understand how to pointing for the log out button, any idea? -
How to add multiple options to a feature in Django?
My last question for today. I created a filter to only show items with certain values. A list of social measures is displayed. There are two questions about having children and unemployment. We have or don't have children, and we are or aren't unemployed. The main problem is that the filter doesn't work correctly, due to the fact that I only add one option "no" to the entity. For example, we have a social measure "child allowance", and it's paid regardless of income. I created this measure with having children "yes" and unemployment "no". And if the user selects having children "yes" and unemployment "yes", then the page won't show this measure, although the person is entitled to it. Because only "no" was introduced into unemployment. How to enter "no" and "yes" at the same time when creating a measure? And for the site to show this measure regardless of the choice of unemployment. measure_list.html <div class="headtext"> <h3>Choose your life features</h3> </div> <form action="{% url 'filter' %}" method="get" name="filter"> <h3>Do you have children?</h3> <ul> {% for measure in view.get_children %} <li> <input type="checkbox" class="checked" name="children" value="{{ measure.children }}"> <span>{{ measure.children }}</span> </li> {% endfor %} </ul> <h3>Are you unemployed?</h3> <ul> … -
Add values to django database from an external python streamlit app
I have a streamlit app that runs machine learning on an image given by the user. I also implemented authentication using django along with a gallery type app that allows users to view stored images if logged in. I want to add the ability to automatically apend the image uploaded on my streamlit app to the database if the user is logged in. What would be the best way to do this? I tried importing my create view into the streamlit app and defining the variables manually. I also tried to import the model and work with that but I couldn't get either of them to work. I also shifted my streamlit app into the same directory as the django app to prevent PATH errors. -
all of my venv is suddenly unable to create process
it's showing Unable to create process using '"C:\Users\JUNG HAN\AppData\Local\Microsoft\WindowsApps\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\python.exe"' I dont know where PythonSoftwareFoundation folder was created from but it was installed today few hours ago I just found. What is this and why it suddenly created and my venv is referencing the python.exe file in that folder? I haven't tried anything yet ................................................................................................... -
Nginx + Django: Waiting for server response too long
I'm using NGINX+uWSGI to deploy my blog. However, I found that the server response took too long time (>3s) when I was going to visit blog articles' pages (But if I visited other pages the response time is rather short). I checked the waterfall in Chrome network analysis and I noticed that when loading the article pages, the "waiting for server response" took about 3s that is much more than other steps. I'm wondering what could be the possible reasons for this problem? Here is the .conf files of NGINX: user www-data; worker_processes auto; pid /run/nginx.pid; include /etc/nginx/modules-enabled/*.conf; events { worker_connections 768; # multi_accept on; } http { ## # Basic Settings ## sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; # server_tokens off; client_max_body_size 64m; client_body_buffer_size 128k; #Cache_settings proxy_cache_path /var/lib/nginx/cache levels=1:2 keys_zone=main:10m max_size=100m; proxy_cache_key "$scheme$request_method$host$request_uri$is_args$args"; proxy_cache_valid 200 302 10m; server_names_hash_bucket_size 64; # server_name_in_redirect off; include /etc/nginx/mime.types; default_type application/octet-stream; ## # SSL Settings ## ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3; # Dropping SSLv3, ref: POODLE ssl_prefer_server_ciphers on; ## # Logging Settings ## access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; ## # Gzip Settings ## gzip on; gzip_vary on; gzip_proxied any; gzip_comp_level 6; gzip_buffers 16 8k; gzip_http_version 1.1; gzip_types text/plain text/css application/json application/javascript … -
How to add appropriate image size width and height in Django?
I have **models **for image and upload image, how to generate size width and height in django? this models.py class article(models.model): image1 = models.ImageField(upload_to='images', blank=True) code head.html <meta property="og:image" content="{{ article.image1 }}" /> <meta property="og:image:secure_url" content="{{ article.image1 }}" /> <meta property="og:image:width" content=" " /> <meta property="og:image:height" content=" " />``` add size height and width generate -
Django filter query to get chat messages among two friends?
I am trying to create a chat api, i have structured the messages model to look like this class ChatMessage(models.Model): user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name="user") sender = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name="sender") reciever = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name="reciever") message = models.CharField(max_length=10000000000) is_read = models.BooleanField(default=False) date = models.DateTimeField(auto_now_add=True) Now i am trying to write the API view to get all messages that belongs only to me and the person that i am chatting with. Let me elaborate: Let's say Destiny is texting John, there would definitely be alot of messages that have been sent between me (Destiny) and the user (John), so i want to get all that text. This is the view that i have written to do this class GetMessages(generics.ListAPIView): serializer_class = MessageSerializer def get_queryset(self): sender_id = self.kwargs['sender_id'] reciever_id = self.kwargs['reciever_id'] messages = ChatMessage.objects.filter(sender=sender_id, reciever=reciever_id) return messages urls path("api/get-messages/<sender_id>/<reciever_id>/", views.GetMessages.as_view()), This is what this view returns ## url - http://127.0.0.1:8000/api/get-messages/2/1/ [ { "id": 2, "sender": 2, "reciever": 1, "message": "Hey Destiny", "is_read": false } ] if i swap the sender_id and reciever_id, this is the response i get # url - http://127.0.0.1:8000/api/get-messages/1/2/ [ { "id": 1, "sender": 1, "reciever": 2, "message": "Hello Sammy", "is_read": false }, { "id": 3, … -
CSS/SCSS changes won't come through
I am trying to hide a number by modifying the scss/css. It is the tag in the picture: poll-row__number. Screenshot from the tag Strange thing is also it is not in the scss file the inspector is showing but another. I am running an Adhocracy installation (Nginx on Ubuntu Linux). I changed all the poll-row__number references in css/ scss files to display:none / visibility:hidden. Rebooted the server and deleted my cache from my browser, tried Chrome, FireFox and Safari. But the number stays visible. When I change it in the inspector, it dissapears. I can't find a div for that also. When I grep How can I search for the exact phrase: it finds nothing systemwide. What am I doing wrong and what else do you want for information to help me fix this strange ptoblem. I tried all I can think of. -
How to handle a file form request and send by REST API
I'm trying to upload files, documents and images (once) using a Django form. The idea is to send it over an internal REST API that processes the file, stores it, and does other things. The API is working but I can't successfully send the file over the API. This is my code. Here I process the form Here I make de API request -
How to solve Error : maximum recursion depth exceeded / i get error when use wizard forms in view.py
i try create a view with SessionWizardView in django than create a conditional steps so i create a function for condition step (in function use self.get_cleaned_data_for_step) than get error RecursionError: maximum recursion depth exceeded # my code view.py is : class ProfileUser(LoginRequiredMixin, SessionWizardView): file_storage = FileSystemStorage(location=os.path.join(settings.MEDIA_ROOT, 'files')) login_url = 'login' template_name = 'gyms/profile.html' STEP_ONE, STEP_TWO, STEP_THREE, STEP_FOUR = '0', '1', '2', '3' def check_type_user_master(self): data = self.get_cleaned_data_for_step('0') print(data) def return_true(self): return True condition_dict = { STEP_ONE: return_true, STEP_TWO: return_true, STEP_THREE: check_type_user_master, } form_list = [ (STEP_ONE, FormLocationStepOne), (STEP_TWO, ChoiceTypeUser), (STEP_THREE, FormMasterStepTwo), ] def done(self, form_list, **kwargs): return render(self.request, 'done.html', { 'form_data': [form.cleaned_data for form in form_list], }) -
Connect local domain to Django
I have several applications that I'm running on Docker. Each one of them has own domain, however when I start containers I can access them only on 127.0.0.1:8000 or 127.0.0.1:8001. But I need to reach them on domain like test1.mydomain.local and test2.mydomain.local. I tried to change my host file like this: 127.0.0.1 *.mydomain.local 127.0.0.1 localhost However when I start docker again - it doesn't work. I have .env file where all domains are written down but I don't get how to get this worked. Please help me to figure it out. -
Django Rest Framework Rate Limit Dynamic based on User Type
I'm building an API using Django Rest Framework (DRF) and I'm facing an issue with rate limiting. Specifically, I need to set different rate limits for different types of users: Staff members: 1000 requests per day Normal users: 100 requests per day Anonymous users: 10 requests per day I've tried several approaches but haven't been successful so far. Can anyone provide guidance on how to achieve dynamic rate limiting based on user type using DRF? Thanks in advance for your help! I've been trying to set up dynamic rate limiting in Django Rest Framework (DRF) based on user type. Specifically, I've created four throttling classes using the built-in DRF throttling classes: PublicThrottle, PrivateAnonThrottle, PrivateFreeUserThrottle, and PrivatePaidUserThrottle. I've defined the throttle rate for the PublicThrottle class as 1000/day, and set the scope attribute for each of the other classes to a unique value. For the PrivatePaidUserThrottle class, I've overridden the allow_request method to check if the user making the request is a staff member. If so, I want to use the private_paid_user scope, otherwise I want to use the private_free_user scope. What I expected: I expected that the rate limits would be enforced based on the user type. Specifically, I expected … -
Is it possible to extract text from a Wagtail streamfield block and strip formatting
I'm trying to extract the text from a Wagtail PostPage, and display that text in a Django page outside of Wagtail. The relevant part of my PostPage model is: body = StreamField([ ('heading', blocks.CharBlock()), ('paragraph', blocks.RichTextBlock()), ('image', ImageChooserBlock()), ], blank=True) In my template, I am displaying the posts that get passed like so: {% for blog in blogs %} <a class="blog-post-link" href="{% pageurl blog %}">{{ blog.title}}</a> {{ blog.body|truncatewords_html:10 }} <a href="{% pageurl blog %}">Read More</a> {% endfor %} This works, but the text that returns has all the formatting that was applied in the DraftTail editor. Is there any way to pull just the text and pass it to the template from the wagtail side, or would the text have to be reformatted in the template using custom template tags or something else? Extra question: I was concerned about blog.body pulling in the heading or the image defined in the streamfield, but so far it seems to jump to the first paragraph when looking for what to display. This is good, but is there a way to guarantee this behavior? -
django - crispy forms default usage of __str__ method
In my crispy form the labels of the choices of a CheckboxSelectMultiple() field pupulate from the default str method of the objects represented. The set of objects is defined in a list containing ids, with those ids crispy calls the str methods. Is it possible to write a custom string representation (for instance as a class' @property) and tell crispy to use that instead? If yes, which point in the pipeline would give the best programmer's practice (models/views/template) ? Overriding the default str method provides the desired results, but is totally unacceptable because of side effects. models.py class School(models.Model): nice_name_for_forms = models.CharField(max_length=100) @property def label_from_instance(self): return '%s' % (self.nice_name_for_forms) views.py school_list = School.objects.all().values_list('id', flat=True) form = MyForm(request.POST, school_list=school_list) forms.py class MyForm(forms.ModelForm): class Meta: model = MyForm fields = '__all__' labels = {'schools' : 'My Schools'} widgets = {'schools' : forms.CheckboxSelectMultiple()} def __init__(self, *args, **kwargs): self.school_list = kwargs.pop('school_list') super().__init__(*args, **kwargs) self.fields['schools'].queryset = self.fields['schools'].queryset.filter(id__in=self.school_list).distinct() self.helper = FormHelper() self.helper.use_custom_control = False self.helper.layout = Layout( Row(CheckboxAllFieldCompact('schools', wrapper_class='col-4 col-md-2')) checkbox_all_field.html <!-- crispy/checkbox_all_field.html --> {% load crispy_forms_field %} {% load i18n %} <div id="div_checkbox_all_{{ field.html_name }}" class="no-form-control control-group {{ wrapper_class }}"> <div class="controls" style="max-height:250px;overflow:auto"> <label for="{{ field.name_for_label }}" class="label_title inline">{{ field.label }}</label> <br /> <label class="block"> … -
ModuleNotFoundError at /enquire/ No module named 'PIL
Here is the image of the error that I am getting I am hosting on pythonanywhere.com and keep getting this error. I have tried running pip install Pillow but it says requirements satisfied Here is the traceback image -
Django: UpdateView form is validated with the previous page submit form button. How to avoid this?
I have the following: Main page: has <form id="mainForm" action="url_update"> --> it takes me with a submit button to the update page Update page: has <form id="updateForm" action""> --> by clicking on submit, it checks the Update Class (UpdadeView) as a valid form and then redirects me to get_success_url page The problem is that by clicking on the first submit, it automatically validates the form in my UpdateClass and redirect me to get_success_url page. I don't even see the update page. How to fix this. my views.py is as follows: My Update Class is a typical UpdateView Class with def get_success_url(self, *args, **kwargs): # some lines def form_valid(self, form): # some lines -
User password is not hashed when creating through Django admin panel
I have inherited the user class to make custom authentication. I do not get password hashing this way. It just stores as plain text in MySQL database. I have created staff through admin panel and unable to login as staff. Furthermore I have also created auth API endpoints using DRF and Djoser and am unable to login with the user profiles created through Django admin panel. Here is my code. models.py from django.contrib.auth.models import AbstractUser class User(AbstractUser): pass admin.py from .models import User class UserAdmin(admin.ModelAdmin): pass admin.site.register(User, UserAdmin) I have seen old replies in Stack Overflow suggesting changing the parent class to django.contrib.auth.admin.UserAdmin . When I try this the add user template form only has 3 fields. Username, Password and Password Confirmation. admin.py from django.contrib.auth.admin import UserAdmin as DefaultUserAdmin from .models import User class UserAdmin(DefaultUserAdmin): pass admin.site.register(User, UserAdmin) How do I solve this problem. -
"Error: unknown shorthand flag: 'n' in -nstances" when trying to connect Google Cloud Proxy to Postgresql (Django)
I'm following a google tutorial to set up Django on Cloud Run with Postgresql connected via Google Cloud Proxy. However I keep hitting an error on this command in the Google Cloud Shell. cloud shell input: xyz@cloudshell:~ (project-xyz)$ ./cloud-sql-proxy -instances="amz-reporting-files-21:us-west1-c:api-20230212"=tcp:5432 returns: Error: unknown shorthand flag: 'n' in -nstances=amz-reporting-files-21:us-west1-c:Iamz-ads-api-20230212=tcp:5432 Usage: cloud-sql-proxy INSTANCE_CONNECTION_NAME... [flags] Flags: -a, --address string () Address to bind Cloud SQL instance listeners. (default "127.0.0.1") --admin-port string Port for localhost-only admin server (default "9091") -i, --auto-iam-authn () Enables Automatic IAM Authentication for all instances -c, --credentials-file string Use service account key file as a source of IAM credentials. --debug Enable the admin server on localhost --disable-metrics Disable Cloud Monitoring integration (used with --telemetry-project) --disable-traces Disable Cloud Trace integration (used with --telemetry-project) --fuse string Mount a directory at the path using FUSE to access Cloud SQL instances. --fuse-tmp-dir string Temp dir for Unix sockets created with FUSE (default "/tmp/csql-tmp") -g, --gcloud-auth Use gcloud's user credentials as a source of IAM credentials. --health-check Enables health check endpoints /startup, /liveness, and /readiness on localhost. -h, --help Display help information for cloud-sql-proxy --http-address string Address for Prometheus and health check server (default "localhost") --http-port string Port for Prometheus and health check server (default … -
Django file uploads becoming corrupted when saved to the server
I'm using Django for a web application and I'm having issues with file uploads becoming corrupted when saved to the server. The files are uploaded from the Django admin site, and I'm using a FileField to save them to the server. The issue is that the uploaded files become corrupted after they are saved to the server. When I try to open the files, I get an error message saying that the file is damaged or corrupted. I've tried uploading files of different sizes and types, but the issue persists. Here is my model that contains FileField class Paper(models.Model): subject = models.ForeignKey(Subject, on_delete=models.CASCADE) display_name = models.CharField(max_length=200) source_file = models.FileField() I've checked my server settings and everything seems to be configured properly. I've also checked the server logs, but there are no error messages or warnings related to file uploads. I'm not sure what could be causing this issue. Has anyone else experienced this issue with Django file uploads? Is there a known solution to this issue? -
I got UnicodeDecodeError in Django while dumping data into JSON, Unicode does not recognize characters of the Russian alphabet
I'm new to Django so I need some help. I needed to create fixtures and did it with this command python manage.py dumpdata products.ProductCategory > category.json Then I got this { "model": "products.productcategory", "pk": 1, "fields": { "name": "╬фхцфр", "description": "╬яшёрэшх юфхцф√" } } And when I try to loaddata Django gives me an error: UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte Are there any ways to encode this JSON or dump data correctly? I searched in the documentation, but unfortunately I did not find anything worthwhile