Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to show validation errors in template using CreateView Django
I am using an extended User model and a generic CreateView. class SignUp(CreateView): form_class = forms.SignUpForm success_url = '/accounts/login/' template_name = 'accounts/signup.html' How do I access the form validation errors in my template? They must be there because when I do {{ form.as_p }} the errors show up. I have tried {{ form.errors }} and {{ field.errors }} but there is nothing in them. Is there a simple tag I can call in my template to show the errors? Thanks. -
Add pre-filled resizable text boxes (forms.Textarea) to the django form
I need to create a form, where text-boxes would be resizable (so Textarea widget has to be used) and pre-filled. I tried to pre-fill them through .initial and value attribute. Problem: If Textarea widget is used: text boxes are resizable but no value is shown forms.CharField(label='', widget=forms.Textarea(attrs={"rows": 1, "cols": 50, "value":column_data}) self.fields[f'inserted_value_{column_name}'].initial=column_data If TextInput widget is used: text boxes are not resizable but value is shown forms.CharField(label='', widget=forms.TextInput(attrs={"rows": 1, "cols": 50, "value":column_data}) There amount of form elements (always the same Text-box) is going to be dynamic, so they are created in def __init__ and should also get their value there. Theoretically value attribute should work, but it returns me empty text-boxes. -
Changing form action based on select option value
I am trying to change the form url_for action based on the selected option: Django template: <form name="List_select" id="List_select" method ="POST"> <div class="modal-body"> <label>Move Item</label> <select class="form-control" id="Lists"> <option value="{{ url_for('complete_item', titleID = item.id) }}">Move to Done</option> <option value="{{ url_for('doing_item', titleID = item.id) }}">Move to Doing</option> <option value="{{ url_for('revert_item', titleID = item.id) }}">Move to To Do</option> </select> <input class="btn btn-primary" type="submit" value="Move"> </div> JQuery $(function() { $(".Lists").change(function(){ value = $(this).val() $('.List_select').attr('action', value) }) }); When I try select an option and press the Move button, however I get: Method Not Allowed The method is not allowed for the requested URL. -
Quick fix: Flipping the side on which DMs are displayed on a social media platform
Within the DM function on my social media platform I would like the received messages to appear on the left hand side and the sent messages to appear on the right hand side. Currently it is the other way round. (Sent messages (light pink) = #D7A5EB, received messages (dark pink) = #CC64C3) Ì have been trial-and-erroring this for a while now, but it simply refuses to allow sent messages (I.e. the ones that the currently logged-in user sent) on the right hand side. thread.html: {% extends 'landing/base.html' %} {% load crispy_forms_tags %} {% block content %} <div class="container"> <div class="row"> <div class="card col-md-12 mt-5 p-3 shadow-sm"> {% if thread.receiver == request.user %} <h5><a href="{% url 'profile' thread.user.profile.pk %}"><img class="rounded-circle post-img" height="50" width="50" src="{{ thread.user.profile.picture.url }}" /></a> @{{ thread.user }}</h5> {% else %} <h5>@{{ thread.receiver }}</h5> {% endif %} </div> </div> {% if message_list.all.count == 0 %} <div class="row my-5"> <div class="col-md-12"> <p class="empty-text">No messages yet.</p> </div> </div> {% endif %} {% for message in message_list %} <div class="row"> {% if message.sender_user == request.user %} <div class="col-md-12 my-1"> {% if message.image %} <div class="message-sender-container ms-auto"> <img src="{{ message.image.url }}" class="message-image" /> </div> {% endif %} <div class="sent-message my-3"> <p>{{ message.body }}</p> … -
Drop a table in django with id
I need to drop a table in django using a model in code. After dropping a table, id of each record should start from 1. Is it possible? -
I'm stumped trying to figure out how to get the sum of all active and inactive investment balances using Django
I am trying to query "locked_total_balance" locked_total_balance = Investment.objects.filter(is_active=True).aggregate( total_balance=Sum('balance')) and "total_available_balance" total_available_balance = Investment.objects.filter(is_active=False).aggregate( total_balance=Sum('balance')) but its not working. Here is my model class Investment(models.Model): PLAN_CHOICES = ( ("Basic - Daily 2% for 180 Days", "Basic - Daily 2% for 180 Days"), ("Premium - Daily 4% for 360 Days", "Premium - Daily 4% for 360 Days"), ) user = models.ForeignKey( User, on_delete=models.CASCADE, null=True, blank=True) plan = models.CharField(max_length=100, choices=PLAN_CHOICES, null=True) deposit_amount = models.IntegerField(default=0, null=True) basic_interest = models.IntegerField(default=0, null=True) premium_interest = models.IntegerField(default=0, null=True) investment_return = models.IntegerField(default=0, null=True) withdraw_amount = models.IntegerField(default=0, null=True, blank=True) balance = models.IntegerField(default=0, null=True, blank=True) locked_balance = models.IntegerField(default=0, null=True, blank=True) investment_id = models.CharField(max_length=10, null=True, blank=True) is_active = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now=True, null=True) due_date = models.DateTimeField(null=True) def __str__(self): return str(self.investment_id) -
Nginx exits with 127 status code, but before prints out: /bin/sh: python: not found
I'm building a web application with python, nginx and gunicorn. And docker-compose build command works fine, but when I run a built image as a container, I'm getting the next output: root@ubuntuos:/home/eliot/Documents/development/python/projects/BarAPI/JustPub# docker-compose up Creating network "justpub_default" with the default driver Creating justpub_db_1 ... done Creating justpub_web_1 ... done Creating justpub_nginx_1 ... done Attaching to justpub_db_1, justpub_web_1, justpub_nginx_1 nginx_1 | /bin/sh: python: not found db_1 | db_1 | PostgreSQL Database directory appears to contain a database; Skipping initialization db_1 | db_1 | 2022-06-19 14:08:35.192 UTC [1] LOG: starting PostgreSQL 13.0 on x86_64-pc-linux-musl, compiled by gcc (Alpine 9.3.0) 9.3.0, 64-bit db_1 | 2022-06-19 14:08:35.192 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432 db_1 | 2022-06-19 14:08:35.192 UTC [1] LOG: listening on IPv6 address "::", port 5432 db_1 | 2022-06-19 14:08:35.196 UTC [1] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432" db_1 | 2022-06-19 14:08:35.200 UTC [22] LOG: database system was shut down at 2022-06-19 14:08:26 UTC db_1 | 2022-06-19 14:08:35.204 UTC [1] LOG: database system is ready to accept connections justpub_nginx_1 exited with code 127 web_1 | [2022-06-19 14:08:36 +0000] [1] [INFO] Starting gunicorn 20.1.0 web_1 | [2022-06-19 14:08:36 +0000] [1] [INFO] Listening at: http://0.0.0.0:8000 (1) web_1 | [2022-06-19 14:08:36 +0000] … -
ValueError: Field 'id' expected a number but got 'update_Item'. Cart Javascript in django
I can't post my prodcutid, please helping me. And sometime my Javascrip can't update, I had alredy saved my javascrip code but in the my brower javascrip does not changed. Please help me to solve my probelm, I am newbiew in here, Thanks cart.js var updateBtns = document.getElementsByClassName('update-cart') for (i = 0; i < updateBtns.length; i++) { updateBtns[i].addEventListener('click', function(){ var productId = this.dataset.product var action = this.dataset.action console.log('productId :', productId ,'Action:', action) console.log('USER:', user) if (user == 'AnonymousUser'){ addCookieItem(productId, action) }else{ updateUserOrder(productId, action) } }) } function addCookieItem(productId, action){ console.log("Not logged in ...") if (action == 'add'){ if (cart[productId] == undefined){ cart[productId] = {'quantity':1} }else{ cart[productId]['quantity'] += 1 } } if (action == 'remove'){ cart[productId]['quantity'] -= 1 if (cart[productId]['quantity'] <= 0 ){ console.log('Remove Item') delete cart[productId] } } console.log('Cart:', cart) document.cookie = 'cart=' + JSON.stringify(cart) + ";domain=;path=/" location.reload() } function updateUserOrder(productId, action){ console.log('User is logged in, sending data...') console.log('productIdCart:', productId) console.log('Action:', action) console.log('Cart:', cart) var url = 'update_Item' fetch(url, { method :'POST', headers : { 'Content-Type' : 'application/json', 'X-CSRFToken' : csrftoken, }, body:JSON.stringify({'productId': productId, 'action': action}) }) .then((response) =>{ return response.json(); }) .then((data) =>{ console.log('data:',data); // window.location.reload(data); location.reload() }); } prduk.html <button data-product="{{product.id}}" data-action="add" class="btn update-cart btntdt" style="padding-left:-20xp" >Tambah</button> Error … -
Can't get the picture to show in django
<img class="img-fluid" alt="Responsive image" src="{% static 'product.image.url' %}" /> Cant get the picture to show on the web page. -
Django runserver issues - ImportError: DLL load failed while importing _sqlite3: The specified module could not be found
I had a perfectly working Django test server in venv, I made no changes after getting the server to run now I get this error the next day: Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Anaconda3\lib\threading.py", line 973, in _bootstrap_inner self.run() File "C:\Anaconda3\lib\threading.py", line 910, in run self._target(*self._args, **self._kwargs) File "C:\Users\User1\Desktop\PROGRAMMING\Django\jose_portilla\django_lectures\My_Django_Stuff\myDjangoEnv2\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\User1\Desktop\PROGRAMMING\Django\jose_portilla\django_lectures\My_Django_Stuff\myDjangoEnv2\lib\site-packages\django\core\management\commands\runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "C:\Users\User1\Desktop\PROGRAMMING\Django\jose_portilla\django_lectures\My_Django_Stuff\myDjangoEnv2\lib\site-packages\django\db\backends\sqlite3\base.py", line 15, in <module> from sqlite3 import dbapi2 as Database File "C:\Anaconda3\lib\sqlite3\__init__.py", line 57, in <module> from sqlite3.dbapi2 import * File "C:\Anaconda3\lib\sqlite3\dbapi2.py", line 27, in <module> from _sqlite3 import * ImportError: DLL load failed while importing _sqlite3: The specified module could not be found. -
Integrating Wagtail Into Django
I have confirmed that my django project works perfectly. However, I am interested in integrating wagtail CMS to the project. I am following Wagtail documentation, for a proper guidance. However, on clicking python manage.py runserver. I get the error shown below. Wagtail Integration Error I have removed all my created apps from INSTALLED_APP, I have also removed them from the available URLs. Unfortunately, non of the above method fixed the problem for me. Your guide on how to fix this type of error will be appreciated. -
Problem with sending email in django using SMTP with new google rules
I am using smtp to send emails in django app but for some reasons it stops working and i found this on the google page. I do not want to use SendGrid or others.because in my app i send more than 1000000 emails per semester and it was working well before this new condition. How can i solve this problem ? Thanks. -
Connecting an internet-facing Django web app (served with Gunicorn) with a non-internet-facing local application to be used by the Django web app
Use case of the internal app: take in a list of words (200-300 words), perform some analysis on them and return large tuples of data, anywhere from 5-10 tuples per word. The Django application will block waiting for the results of the internal app to serve the webpages that needs the word analyses. The reason I want to separate them is because the internal app uses a lot of memory, and integrating the word-analysis (i.e. the task of the internal app) into the Django app will cause high memory usage because of gunicorn forking multiple workers. The internal app uses about 1GB of memory once loaded, but is not compute-intense. Now, assuming I want to host the Django web app and the internal app on the same server, what comes to my mind is to use a flask application for the internal app, and put it behind gunicorn. So two questions: Is there a better way to accomplish this? Is using gunicorn the right way to go for the internal app? -
Django project on AWS EC2, what should put in ALLOWED_HOSTS?
Problem I deployed my project on AWS EC2 with docker. When ALLOWED_HOSTS is set as '*', the web site works fine, it looks just what it should be. After switched ALLOWED_HOSTS from '*' to AWS EC2 Public IPv4 DNS, the website response with Bad request 400. It is weird. Why it happened? Or should I put another value instead of Public IPv4 DNS ? Here are my project config nginx.conf user root; worker_processes 1; error_log /var/log/nginx/error.log warn; pid /var/run/nginx.pid; events { worker_connections 1024; } http { include /etc/nginx/mime.types; default_type application/octet-stream; log_format main '$host $remote_addr - $remote_user [$time_local] ' '"$request" $status $body_bytes_sent ' '"$http_referer" "$http_user_agent" ' '$request_time'; access_log /var/log/nginx/access.log main; access_log /dev/stdout; error_log /var/log/nginx/error.log; error_log /dev/stdout info; sendfile on; #tcp_nopush on; keepalive_timeout 65; # Gzip Compression gzip on; # gzip_min_length 1000; gzip_types text/plain application/xml; gzip_proxied expired no-cache no-store private auth; gzip_vary on; include /etc/nginx/conf.d/*.conf; } custom_nginx.conf # the upstream component nginx needs to connect to upstream uwsgi { server unix:/code/demo.sock; } # configuration of the server server { # the port your site will be served on listen 80; listen [::]:80; client_max_body_size 75M; # adjust to taste # Django media location /media/ { alias /code/media/; # your Django project's media files … -
CSS in sub static folder not working properly in Django
I know it's a simple problem but I want to know what I missed. I'm sure the solution is simple. Here is the problem: settings.py: STATIC_URL = 'static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') The tree with the problem: ├── manage.py ├── static │ ├── css │ │ ├── bootstrap.min.css │ │ └── style.css │ └── js └── templates ├── hi.html .html file: {% load static %} <!DOCTYPE html> <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}"> <link rel="stylesheet" href="{% static 'css/style.css' %}"> and the boom does not work but some codes work and some do not. I'm not quite sure what's going on there. when there is no subfolder: ├── manage.py ├── static │ ├── bootstrap.min.css │ └── style.css └── templates ├── hi.html and when I use it this way it works fine! {% load static %} <link rel="stylesheet" href="{% static 'bootstrap.min.css' %}"> <link rel="stylesheet" href="{% static 'cstyle.css' %}"> Am I really missing something? I'm not sure, I haven't opened a project from scratch with django for a long time. Thanks in advance. -
Django Redirects + FeinCMS - URL variable
I am using an older server with Python 2.7 and Django 1.11.7 with FeinCMS as the CMS. If I wanted to redirect any incoming URL from a request that had mixed casing to the proper URL in all lowercase letters, how would I go about doing that? Is there a way to edit the incoming request and, if the page is matched but it's detected not to be a match to the lowercase URL, it will do a redirect to the page? I have the original function below and one that I edited and made enough progress to get the proper page to show up, but the URL in the address bar still has the mixed casing. Any help would be greatly appreciated. Original Function: def dispatch(self, request, *args, **kwargs): try: return super(Handler, self).dispatch(request, *args, **kwargs) except Http404 as e: if settings.FEINCMS_CMS_404_PAGE is not None: logger.info( "Http404 raised for '%s', attempting redirect to" " FEINCMS_CMS_404_PAGE", args[0]) try: # Fudge environment so that we end up resolving the right # page. # Note: request.path is used by the page redirect processor # to determine if the redirect can be taken, must be == to # page url. # Also clear out … -
django avatar upload default value
I got a profile page where I can upload an avatar pic, but when there is no avatar there is this weblink "False" How can I change it to "No Image" string and to remove the weblink tag as well? Is it intended to work as a weblink to the default image? This template uses {{ form.as_p }} to output a page. -
How to give arguments to Class in python
I am trying to create a Django app. I want create function to pass some initial text to text area. I tried following : Here is required part of views.py : from django import forms class createform(forms.Form): def __init__(self, title, value): self.newtitle = forms.CharField(max_length=30, label='Enter Title:', widget=forms.TextInput(attrs={'value': title})) self.content = forms.CharField(widget=forms.Textarea(attrs={'value': value}), label='Enter the description:') def create(request): return render(request, "encyclopedia/create.html", { "form": createform('this title','this content') }) But when I try to run this I get following error: -
django multi select field saves only one value
I have a form that you can select a province and its' cities. This is the model that my form is using in my app: class ScientificSchedule(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) province = models.CharField(max_length=100, blank=True) city = models.CharField(max_length=2048, blank=True) #other fields and the form: class ScientificScheduleForm(forms.ModelForm): class Meta: model = ScientificSchedule fields = '__all__' also these are my views and HTML code: class ScientificScheduleView(FormView): model = ScientificSchedule template_name = 'reg/scientific-schedule.html' form_class = ScientificScheduleForm success_url = '/scientific/schedule' def post(self, request): form = ScientificScheduleForm(request.POST) if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) def form_valid(self, form): form.save() return super(ScientificScheduleView, self).form_valid(form) and this is part of the form which is for city and province fields: <form id="manager-users" method="POST" autocomplete="off" class="ant-form ant-form-horizontal"> {% csrf_token %} <div class="ant-row-flex ant-row-flex-space-between" style="margin-left: -10px; margin-right: -10px;"> <div class="ant-col ant-col-xs-24 ant-col-md-12" style="padding-left: 10px; padding-right: 10px;"> <div class="ant-row ant-form-item formItemRow"> <div class="ant-col ant-form-item-label"><label for="province" class="ant-form-item-required" title="province">province</label></div> <div class="ant-col ant-form-item-control-wrapper"> <div class="ant-form-item-control has-success"> <span class="ant-form-item-children"> <div id="province" class="ant-select ant-select-selection ant-select-selection--single" style="width: 100%;"> <select name="province" class="ant-col ant-select-selection ant-select-selection--single" role="combobox" aria-autocomplete="list" aria-haspopup="true" tabindex="-1"> <option value="" class=""> - </option> </select> </div> </span> </div> </div> </div> </div> <div class="ant-col ant-col-xs-24 ant-col-md-12" style="padding-left: 10px; padding-right: 10px;"> <div class="ant-row ant-form-item formItemRow"> <div class="ant-col ant-form-item-label"><label for="city" class="ant-form-item-required" title="city">city</label></div> <div class="ant-col … -
Is there any way to add address autocomplete to django forms?
I am trying to use address autocomplete api and I want to use django forms to save address on database. forms: class AdressInputForm(forms.ModelForm): class Meta: model = AdressInput fields = '__all__' views: def new(request): if request.method == 'POST': form = AdressInputForm(request.POST) form.save() else: form = AdressInputForm() return render(request, 'example_app/index.html', {'form': form}) html: <div class="autocomplete-container" id="autocomplete-container"></div> css: body { font: 16px; background: #f3f5f6; } .autocomplete-container { margin-bottom: 20px; margin-right: 50%; } .input-container { display: flex; position: relative; } .input-container input { flex: 1; outline: none; border: 1px solid rgba(0, 0, 0, 0.2); padding: 10px; padding-right: 31px; font-size: 16px; } .autocomplete-items { position: absolute; border: 1px solid rgba(0, 0, 0, 0.1); box-shadow: 0px 2px 10px 2px rgba(0, 0, 0, 0.1); border-top: none; background-color: #fff; z-index: 99; top: calc(100% + 2px); left: 0; right: 0; } .autocomplete-items div { padding: 10px; cursor: pointer; } .autocomplete-items div:hover { /*when hovering an item:*/ background-color: rgba(0, 0, 0, 0.1); } .autocomplete-items .autocomplete-active { /*when navigating through the items using the arrow keys:*/ background-color: rgba(0, 0, 0, 0.1); } .clear-button { color: rgba(0, 0, 0, 0.4); cursor: pointer; position: absolute; right: 5px; top: 0; height: 100%; display: none; align-items: center; } .clear-button.visible { display: flex; } .clear-button:hover … -
How to check if user has passed the form?
I have a Person class in models.py, a class has a code field (charfield). A user should enter code on the page with the form where he will enter the code user will be allowed to enter the site. It is similar to registration but without actually registration. So, how do i check if he is entered a code? Is there anything similar to "is_authorized" function, but NOT for User model? I tried to add more fields to the User model and authorize on these fields but faced with a lot of problems there is an easier solution? -
Can I move django app simply to the apps folder?
I have django project. and it has apps folder which contains 6-7 apps. I created an app by running manage.py startapp myapp. And it located BASEDIR. Is correct simply move myapp to apps folder. Thanks. -
Django admin add record using signal
I dont have problem with saving the record when the user login, the problem here is for example the user login June 19, 2022 8am and accidentally logout, and if that user login again I dont want the data insert again, I just want that 1 record insert per day, even the user login multiple times class UserLogs(models.Model): user = models.OneToOneField(User, related_name="profile", on_delete=models.CASCADE) time_in = models.DateTimeField(null=True, blank=True) time_out = models.DateTimeField(null=True, blank=True) @receiver(user_logged_in) def post_login(sender, request, user, **kwargs): print(user) insert = UserLogs( fullname = user, time_in = datetime.now() ) print(insert.id) if insert.id.exists(): insert.save() else: print('dont save!') -
Bad Gateway python-telegram-bot with webhook and Nginx
I'm trying to set up a webhook with python-telegram-bot and Nginx. I am faced with a problem, my bot doesn't get messages from telegram. I also tried to make GET/POST queries from the postman and I always get a "502 Bad Gateway" error. I also launched the netstat to monitor port 5000 where my telegram bot connects but it is always empty. It seems like webhook doesn't launch at all. My Nginx default.conf file looks like the following: upstream django { server gunicorn:8000; } server { listen 80; server_name example.com www.example.com; return 301 https://$server_name$request_uri; } server { listen 443 ssl; ssl on; server_name example.com www.example.com; ssl_certificate fullchain.pem; ssl_certificate_key privkey.pem; access_log /var/log/nginx/nginx.vhost.access.log; error_log /var/log/nginx/nginx.vhost.error.log; location /TELEGRAM_TOKEN { proxy_pass http://0.0.0.0:5000/TELEGRAM_TOKEN/; } location /static/ { alias /static/; } location / { proxy_pass http://example.com:8000; } } And my telegram client code: updater = Updater(api_token) updater.dispatcher.add_handler(CommandHandler('start', start)) updater.dispatcher.add_handler(CallbackQueryHandler(button)) updater.dispatcher.add_handler(MessageHandler(Filters.text & ~Filters.command, custom_command)) jq = updater.job_queue job_minute = jq.run_repeating(callback_minute, interval=5) #updater.start_polling() updater.start_webhook(listen="0.0.0.0", port=5000, url_path=api_token, webhook_url=f'https://example.com/{api_token}') updater.idle() I also have Django options for the Nginx server but I've never seen any tutorial or documentation on how to tune the webhook with Django and it can be the reason for my problems. Have anyone any idea about solving … -
Django admin users timein and timeout of the user
Hi I am new in Django framework, I just want to know if is it possible to capture the timein and timeout of the user, I have this model that if the employee1 login on django-admin it will add automatic record and if the user click logout it will update the time-out. What I want is for every time the employee login in django admin it will add record and it will update the record once the employee logout, just like daily attendance record on company. class UserLogs(models.Model): user = models.OneToOneField(User, related_name="profile", on_delete=models.CASCADE) time_in = models.DateTimeField(default=now) time_out = models.DateTimeField(null=True, blank=True)