Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
Django: extra argument using field from parent table
I'm trying to pull a value from a table in an app with no foreignkey association to another table in a separate app. While using .extra() is fairly straightforward, I'm wondering how one uses a field from the parent table in the WHERE clause of the select argument in .extra(). I would prefer to use Django's built in mechanisms rather than resorting to raw sql. The main area of focus is the queryset argument in association.views.py. I've tried simply setting the product_code equal to consequent but this does not return any values for price (product_code and consequent have common records), whereas using raw SQL returns the correct values. My assumption would be that consequent is coming through as a list rather than individual values. Consider one app as 'association' and the other app as 'pricing'. Here are the two models from each app and the views.py file from the 'brand' app: pricing.models.py class CurrentSchedule(models.Model): price_schedule_id = models.IntegerField(null=True, blank=True) price_schedule_name = models.CharField(max_length=200, null=True, blank=True) unit_charge_amount = models.FloatField(null=True, blank=True) product_code = models.CharField(max_length=50, null=True, blank=True) association.models.py class AssociationData(models.Model): antecedent = models.CharField(max_length=10, primary_key=True) consequent = models.CharField(max_length=10, null=True) confidence = models.FloatField(null=True) lift = models.FloatField(null=True) class Meta: ordering = ['antecedent','-confidence'] association.views.py def association_price_table(request): """ Generates the … -
Django send Messages by WhatsApp
Goodnight. I'm developing a system where users, in addition to all the bureaucratic part, can register their clients' whatsapp so that automatic billing messages, congratulations, etc. are sent. Where the user would read the QR code and the system would be in charge of sending messages over time, using the user's whatsapp, thus opening a user<-> clinet conversation. I've seen a system working like this, but researching I didn't find many ways, just Twilio and selenium. Any suggestions for simplifying this process? And if it's Selenium, how to keep sessions loaded with so many users, so that the qr code doesn't need to be read all the time? Thanks! I thought about using Selenium on heroku, with automation a few times a day, to execute pending messages. But I don't know if selenium with webdrive would work and the question of hundreds of open sections in webdriver. -
Not an executable object: 'SELECT * FROM LoanParcel'
I want to use the database by creating it as a dataframe, and I've used sqlalchemy for importing create_engine, but I'm stuck with the not an executable object: 'SELECT * FROM LoanParcel', where LoanParcel is the name of the database I want to create as a dataframe, how should I fix it? views.py from sqlalchemy import create_engine engine = create_engine("mysql+pymysql://mariadb:mariadb@localhost:9051/mariadb") def user_detail(req, id): conn = engine.connect() QLoanParcel = "SELECT * FROM LoanParcel" dfParcel = pd.read_sql(QLoanParcel, conn) conn.close() df = dfParcel.drop(["id", "date_add", "start_date"], axis = 1) return render(req,'pages/user_detail.html') -
Django add language code to url in html if condition
I have a navbar that shows active when it is in the current section. I have internationalised the web so now the url includes the language code. How can I add the language code in the if condition below? {% if '/{LANGUAGE_CODE}/accounts/dashboard/' == request.path %} active {% endif %} webpage url: http://127.0.0.1:8000/en/accounts/dashboard {% load i18n %} {% get_current_language as LANGUAGE_CODE %} <aside class="col-md-3"> <!-- SIDEBAR --> <ul class="list-group"> <a class="list-group-item {% if '/{LANGUAGE_CODE}/accounts/dashboard/' == request.path %} active {% endif %}" href="{% url 'dashboard' %}"> Dashboard </a> [continues...] I tried {{LANGUAGE_CODE}} and some pasting. Any ideas how to get the if condition working? -
How to set ordering of Apps and models in Django admin dashboard
i would like to set a specific order of the models list of an app in the django dashboard. my models look like this: i've tried several tutorial like this one and looked other people solution inside SO like this questions How to use custom AdminSite class? Set ordering of Apps and models in Django admin dashboard Reorder app and models in Django admin but none of these works, they either use a third party library or they don't specify where to put the pieces of code. This one seem to be the most promising but i tried to put the piece of code, class WebsiteAdminSite(admin.AdminSite): def get_app_list(self, request): """ Return a sorted list of all the installed apps that have been registered in this site. """ ordering = { "Menues": 1, "Entrees": 2, "First_dishes": 3, "Second_dishes": 4, "Side_dishes": 5, "Desserts": 6, "Wines": 7, "Opening_hours": 8, "Contacts": 9, "Gallery_images": 10, } app_dict = self._build_app_dict(request) # a.sort(key=lambda x: b.index(x[0])) # Sort the apps alphabetically. app_list = sorted(app_dict.values(), key=lambda x: x['name'].lower()) # Sort the models alphabetically within each app. for app in app_list: app['models'].sort(key=lambda x: ordering[x['name']]) return app_list inside the admin.py of my app but it doesn't work. i can't provide any … -
Django Custom Authentication Backend does not work
I've made a user model with USERNAME_FIELD defined as phone_number. So that is login, it requires phone_number and password. But I want users to be able to also login through their emails. So I created an authentication backend class: authentication.py: from django.contrib.auth import get_user_model class CustomAuthBackend: def authenticate(self, username=None, password=None): try: user = get_user_model().objects.get(email=username) if password: if user.check_password(password): return user return None except: return None def get_user(self, user_id): try: user = get_user_model().objects.get(pk=user_id) return user except: return None forms.py: class UserLoginForm(forms.Form): username = forms.CharField(label="Phone Number / Email") password = forms.CharField(widget=forms.PasswordInput(), label="Password") views.py: class UserLogin(View): form_class = UserLoginForm template_name = "accounts/login.html" def get(self, request): return render(request, self.template_name, {"form": self.form_class}) def post(self, request): form = self.form_class(request.POST) if form.is_valid(): cd = form.cleaned_data user = authenticate( request, username=cd["username"], password=cd["password"] ) if user: login(request, user) messages.success(request, "Logged in successfully.", "success") return redirect("home:home") else: messages.error(request, "Username and/or password is wrong.", "danger") return render(request, self.template_name, {"form": form}) messages.error(request, "Login failed", "danger") return render(request, self.template_name, {"form": form}) Users can login with their phone numbers properly. But it login always fails when I type an email in username field. -
Related Field got invalid lookup: icontains in admin.py
I know this problem have been posted before with its respective solution, but I do not know what is the problem in this specific case, Im trying to add a searching bar in the admin page of a specific class called "Dish" here is the context: Error in browser FieldError at /admin/menu/dish/ Related Field got invalid lookup: icontains Request Method: GET Request URL: http://www.lupita.restaurant/admin/menu/dish/?q=naranja Django Version: 4.0.6 Exception Type: FieldError Exception Value: Related Field got invalid lookup: icontains Exception Location: /usr/local/lib/python3.10/site-packages/django/db/models/sql/query.py, line 1262, in build_lookup Python Executable: /usr/local/bin/uwsgi Python Version: 3.10.5 Python Path: ['/home/juanfrax/lupita', '/var/www', '.', '', '/var/www', '/usr/local/lib/python310.zip', '/usr/local/lib/python3.10', '/usr/local/lib/python3.10/lib-dynload', '/home/juanfrax/.local/lib/python3.10/site-packages', '/usr/local/lib/python3.10/site-packages'] Server time: Fri, 10 Feb 2023 03:38:57 +0000 Traceback Switch to copy-and-paste view /usr/local/lib/python3.10/site-packages/django/core/handlers/exception.py, line 55, in inner response = get_response(request) … Local vars /usr/local/lib/python3.10/site-packages/django/core/handlers/base.py, line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) … Local vars /usr/local/lib/python3.10/site-packages/django/contrib/admin/options.py, line 683, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) … Local vars /usr/local/lib/python3.10/site-packages/django/utils/decorators.py, line 133, in _wrapped_view response = view_func(request, *args, **kwargs) … Local vars /usr/local/lib/python3.10/site-packages/django/views/decorators/cache.py, line 62, in _wrapped_view_func response = view_func(request, *args, **kwargs) … Local vars **models.py: ** class Dish(models.Model): name = models.CharField(max_length=50) nombre = models.CharField(max_length=50) description = models.TextField(max_length=500) descripcion = models.TextField(max_length=500) category = models.ForeignKey('Category', null=True, on_delete=models.SET_NULL) categoria = … -
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> … -
Pass session data to new session Django
Hello Iam working on Django website and I need to pass saved session data to new one after assigning a new session to the user. Example is when a player is doing an online quiz and his browser crashes, so that the data saved for the session will be assignment to a new one after re-login. I've been trying to look for possible workarounds, but I couldn't come up with an answer, as many sources state that django can't detect a new session after a crash unless the user logs out manually.