Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Allauth SocialConnectView django rest framework
can someone help please, the access token retrieved from Facebook is not being stored in the socialaccount_token table after a successful social login. This prevents my application from using the token later for data retrieval. this is my code from dj_rest_auth.registration.views import SocialConnectView from allauth.socialaccount.providers.facebook.views import FacebookOAuth2Adapter import facebook from allauth.socialaccount.providers.oauth2.client import OAuth2Client class FacebookConnect(SocialConnectView): adapter_class = FacebookOAuth2Adapter client_class = OAuth2Client the data is stored in socialaccount_socialaccount table by default , but nothing stored in socialaccount_socialtoken -
Handle multiple clients in a browser terminal that is created by xtermjs
My browser terminal application runs without problem while it is used by a single client but when another client connects to it and tries to use the same terminal is shown to the new client. Also when i open it in another tab it shows the same terminal too. Defining seperate terminals in xtermjs like termA and termB is not viable since number of clients is not certain. The application runs with django in backend. Xtermjs is only used for visualization and getting user input. A pseudo terminal and bash process handles terminal logic in the django. My first approach was to implement multiprocessing in the django but i failed to achieve it. I am open to different approaches to solve this issue. views.py: import os from django.shortcuts import render import socketio import pty import select import subprocess import struct import fcntl import termios import signal import eventlet async_mode = "eventlet" sio = socketio.Server(async_mode=async_mode) fd = None child_pid = None def index(request): return render(request, "index.html") def set_winsize(fd, row, col, xpix=0, ypix=0): winsize = struct.pack("HHHH", row, col, xpix, ypix) fcntl.ioctl(fd, termios.TIOCSWINSZ, winsize) def read_and_forward_pty_output(): global fd max_read_bytes = 1024 * 20 while True: sio.sleep(0.01) if fd: timeout_sec = 0 (data_ready, _, … -
Rounding off decimals in Django not working as expected?
I am using Django version 3.2.16. In Django I am using below code. Here for example income__ownership is 2500 and the value of amount_field is 14826.So when multiplying 14826 by.25 it gives value as 37.715 and I want the rounded result as 35.72 but Django Round gives result as 36. How to achieve desired result? amount_annotation = ExpressionWrapper( # Use Django's Round function to round the base value to 2 decimal places Round( F(amount_field) * (Cast(F('income__ownership'), FloatField()) / 10000), precision=2, # Round to 2 decimal places output_field=FloatField() ) * 100, # Multiply the rounded value by 100 output_field=IntegerField() ) -
What are the best practises to develope a django project with adminLTE frontend admin pannel and DRF as backend
Please stay away who has no experiance to development of real life projects !! i would like to ask that what is best practices to develop a project is admin pannel.I mean that i'm developing a project in python technology and i have little bit knowladge of python technology and Django framework and DRF. what shoud be the folder structure , should i develop both in just single project like following structure or develope saparate projects. i'm following below structure sholud i continue with same or not? . ├── authentication │ ├── admin.py │ ├── api │ │ └── v1 │ │ ├── backend.py │ │ ├── pagination.py │ │ ├── permissions.py │ │ ├── __pycache__ │ │ ├── serializers.py │ │ ├── urls.py │ │ ├── validations.py │ │ └── views.py │ ├── apps.py │ ├── __init__.py │ ├── migrations`your text` │ ├── models.py │ ├── __pycache__ │ ├── services.py │ ├── templates │ │ ├── base.html │ │ ├── change_password.html │ │ ├── edit_role.html │ │ ├── email_message.html │ │ ├── forgot_password.html │ │ ├── login.html │ │ ├── new_role.html │ │ ├── permission.html │ │ ├── role_list.html │ │ └── subadmin_list.html │ ├── tests.py │ ├── urls.py … -
DisallowedHost at / | Invalid HTTP_HOST header
For no apparent reason that I can think of, I am getting the: Invalid HTTP_HOST header: '13.60.32.132:8000'. You may need to add '13.60.32.132' to ALLOWED_HOSTS. The IP address been correctly added to my settings.py file. I am using Ubuntu 22.04.4 LTS (GNU/Linux 6.5.0-1014-aws x86_64) with the latest version of Django, which is Django 5.0.4 As per SO's requirements, these are the fully reproduceable steps I took which brought me to this issue: I created an Amazon EC2 Instance (free tier). The Outbound NSG settings are as follows: Port Range: 8000 Protocol: TCP Source: 0.0.0.0/0 Port Range: 80 Protocol: TCP Source: 0.0.0.0/0 Port Range: 443 Protocol: TCP Source: 0.0.0.0/0 The Inbound NSG Settings are as follows: Port Range: 443 Protocol: TCP Source: 0.0.0.0/0 I connected to my Ubuntu EC2 Server and successfully cloned my GitHub repository via the ssh methodology. I ran the following commands: sudo apt update sudo apt upgrade sudo apt install git sudo apt install python3 python3-pip sudo apt install python3-venv I then continued to ensure that pip was installed to the latest version, before installing my venv and dependencies, by running the following commands: pip install --upgrade pip cd .ssh/<repository-name> python3 -m venv venv source venv/bin/activate pip … -
TinyMCE renders an extra widget
I use django-tinymce to render TinyMCE widgets in my forms. If updated to the latest version 6.8.3 (2024-02-08), I have two widgets on the same form field instead of one. This is the Django template: {% extends "layout.html" %} {% load i18n %}{% load static %} {% block title %} ... {% endblock %} {% block head %}{{ form.media }}{% endblock %} {% block content %} {% if user.is_authenticated %} <div id="create"> <form id="cascade" class="mt-3" method="post" action="." enctype="multipart/form-data"> {% csrf_token %} {{ form.non_field_errors }} {% for field in form %} {% if field.is_hidden %}{{ field }}{% else %} <div class="mb-3"> <label for="{{ field.id_for_label }}" class="form-label">{{ field.label }}:</label> {{ field }} {% if field.help_text %} <div class="form-text">{{ field.help_text|safe }}</div> {% endif %} <div id="{{ field.auto_id }}" class="invalid-feedback">{{ field.errors }}</div> </div> {% endif %}{% endfor %} <button class="btn btn-primary" type="submit" name="action">{% translate "Submit" %}</button> </form> </div> {% endif %} {% endblock %} This is how the form field content using TinyMCE is actually rendered: <div class="mb-3"> <label for="id_content" class="form-label">Содержимое:</label> <textarea class="form-control tinymce" cols="40" data-mce-conf="{&quot;theme&quot;: &quot;silver&quot;, &quot;height&quot;: 500, &quot;menubar&quot;: false, &quot;plugins&quot;: &quot;autolink,lists,link,image,charmap,preview,hr,searchreplace,code,media,table,paste,help,wordcount&quot;, &quot;contextmenu&quot;: &quot;paste | link image table&quot;, &quot;toolbar&quot;: &quot;bold italic underline strikethrough | bullist numlist | blockquote hr charmap | table | … -
Is there a hook to modify field value in Django?
On any type of Django Field, validators is available where I can hook my own custom validator. I understand I cannot change the value in the validator, it must either return None or django.core.exceptions.ValidationError. What I want to do is I want to change the value of the field itself, before it gets saved. For example, I want to store ISO 3166 Numeric Code as a column: def digit_only(value): if not value.isdigit(): raise ValidationError( _("%(value)s contains a non-digit"), params={"value": value}, ) class Country(models.Model): # ... iso3166_numeric = models.CharField(max_length=3, validators=[digit_only]) # ... So far, so good. Now, if the value input is '1', I want to convert it to '001' before the value is stored on the table. Without creating a new Field type and then writing custom Field.to_python(), can I achieve the same, as simply as using validators? I am still learning, and I have not reached as far as Forms yet, but I am trying to achieve the above when seeding from a CSV through Djano command. Yes, I could modify the value immediately on reading from CSV, but I am trying to find out if there is one single place where I can do this so that I … -
Authentication and Security in Django/QT Application
I'm currently working on an application that utilizes Django for the backend and QT/C++/QML for the frontend. One of the key aspects I'm focusing on is authentication and ensuring the security of the application. Here's a brief overview of how it works: When a user logs in, the frontend sends a request to the API, and if the credentials are valid, the user receives a TOKEN, which is then stored in a class variable. Subsequently, this token is sent with each subsequent request to the API. Now, my question is: Is this approach secure? Where should such a token be stored? Is using a class variable acceptable in this scenario? It's worth mentioning that this application doesn't handle sensitive data, but I still want to ensure proper security measures are in place. I'd appreciate any insights or recommendations on best practices for authentication and security in this context. Thank you! I was tried to store the data in variable inside the CPP class. -
I can't use wagtail command after pip install
Firstly, I attempted to install wagtail from source the usual way : pip install -e ."[testing,docs]" -U But it always returned TypeError : excepted string or bytes. I then tried to reinstall python and pip altogether. Through many researches on stackoverflow, I found to try install with sudo. Then It worked. But when I do wagtail command, it returns : Traceback (most recent call last): File "/usr/local/bin/wagtail", line 33, in <module> sys.exit(load_entry_point('wagtail', 'console_scripts', 'wagtail')()) File "/usr/local/bin/wagtail", line 25, in importlib_load_entry_point return next(matches).load() StopIteration I desperate with Wagtail application for more than one month. I'm hoping for your kind help please. Thanks community. -
Make Python async queue based on two dynamic Django ORM requests
I need to make chat offers to the agents. Both are taken from Django ORM dynamically, agents have limits of maximum active chats. One agent must have one offer at a time. Chat should be offered to different agents sequentially. Here is example of try showing the expected logic but it offers only one chat at time. async def offerer(): while True: await asyncio.sleep(0.1) async for chat in Chat.objects.filter(Q(status = 'initiated') | Q(status = 'queued')).order_by('last_init')[:5]: chatid = chat.chatid dobreak = False account = chat.chatacc_id async for agent in Agent.objects.filter(status = 'ready', accounts = account, number_active__lt = maxchats).order_by('number_active'): data = {"type": "chat_initiated", "chatid": chat.chatid} await channel_layer.group_send(f'agent_{agent.agentid}', data) await asyncio.sleep(5) # check if chat was accepted chat_updated = await Chat.objects.aget(chatid = chatid) if 'active' in chat_updated.status: dobreak = True break else: await channel_layer.group_send(f'agent_{agent.agentid}', {"type": "cancel", "value": chat.chatid}) if dobreak: break async def main(): asyncio.create_task(offerer()) loop = asyncio.new_event_loop() loop.create_task(main()) loop.run_forever() What is the correct way to do that? -
Can custome page Admin in Django?
I'm building a clinic system. I'm logged in as an admin as a doctor and this page doesn't have any permissions. How can I customize this page or should create url and overriding admin? Thank you. I have tried creating new URLs, creating a page identical to the admin page and want to override the properties and display of the admin page but still don't know how. -
I am trying to deploy a Django webapp on pythonanywhere but it shows up the error "TemplateDoesNotExist at / generator/signin.html"
TemplateDoesNotExist at / generator/signin.html Request Method: GET Request URL: https://atharvasukale.pythonanywhere.com/ Django Version: 4.0.6 Exception Type: TemplateDoesNotExist Exception Value: generator/signin.html Exception Location: /usr/local/lib/python3.10/site-packages/django/template/loader.py, line 19, in get_template Python Executable: /usr/local/bin/uwsgi Python Version: 3.10.5 Python Path: \['/home/atharvasukale/Django-Certificate_Generator-main', '/var/www', '.', '', '/var/www', '/usr/local/lib/python310.zip', '/usr/local/lib/python3.10', '/usr/local/lib/python3.10/lib-dynload', '/usr/local/lib/python3.10/site-packages'\] Server time: Mon, 15 Apr 2024 08:01:54 +0000 I have made all the necessary changes required, but when deployed using pythonanywhere it shows this error. -
Using UserCreationForm
I am learning django. I would like to understand below code. class RegisterPage(FormView): template_name = 'base/register.html' form_class = UserCreationForm redirect_authenticated_user = True success_url = reverse_lazy('tasks') def form_valid( self, form ): user = form.save() if user is not None: login( self.request, user ) return super( RegisterPage, self ).form_valid( form ) def get( self, *args, **kwargs ): if self.request.user.is_authenticated: return redirect('tasks') return super(RegisterPage, self).get(*args, **kwargs) Can I use def register( self, form ): instead of def form_valid( self, form ): ? How self and form are passing here ? Can I use def save( self, *args, **kwargs ): instead of def get( self, *args, **kwargs ): ? -
Django dropdown menu with logout, change password
` {% csrf_token %} ` I want to make the logout page in a drop down list, but I can't do this. The logout page only works with the above code. The path is: path("logout/", LogoutView.as_view(next_page="login"), name="logout"). How can I solve this? -
I am not able to understand the problem in this error
enter image description here I stuck in reportmissingmodule in vscode django. I read all types of documentation regarding to this not able to get any anwser at all . django is a framework in python language which is used to do backend stuff for web developlments etc. please help me regarding it. -
I want to ban admin for edit or delete user fields
class BandAdmin(admin.ModelAdmin): readonly_fields = ('user',) class AlbumAdmin(admin.ModelAdmin): readonly_fields = ('user',) class SongAdmin(admin.ModelAdmin): readonly_fields = ('user',) I write this code on admin.py but admin can edit user data. How can I do in order to not allow him to edit user fields? -
How do I create a hidden field in Django 4/5?
I am using this simple example just for discussion: class User(models.Model): first_name = models.CharField(...) last_name = models.CharField(...) full_name = first_name + ' ' + last_name I want only full_name to be accessible to be created, saved, retrieved. It is a combination of first_name and last_name. When the full_name needs to be saved, it will be split by spaces, and first split goes to first_name and rest goes to last_name. I don't want first_name and last_name to be directly accessible from forms or even Django commands that may directly use User instantantiation, ModelModel manager create or User save methods. Do I have to hack into the Metaclass (like here: https://github.com/vitaly-efremov/django-private-field/blob/master/private_field_meta.py, 7 years old code), or is there something simpler in Django 4/5? -
TemplateSyntaxError at / 'custom_tags' is not a registered tag library
i trying to give permission to my mode user to delete all the posts.when i try to run it iam getting this error message : 'custom_tags' is not a registered tag library. Must be one of: admin_list admin_modify admin_urls cache crispy_forms_field crispy_forms_filters crispy_forms_tags crispy_forms_utils i18n l10n log static tz this is my custom_tags.py file: from django import template register = template.Library() @register.filter def has_delete_permission(user): return user.has_perm("main.delete_post") this is my .html file: {% extends "main/base.html" %} {% load custom_tags %} {% block content %} {% for post in posts %} <div class="card mt-5"> <div class="card-header"><strong>@{{post.auther.username}}</strong></div> <div class="card-body d-flex flex-row justify-content-between"> <div> <h5 class="card-title">{{post.title}}</h5> <p>{{post.description}}</p> </div> {% if user == post.author or user|has_delete_permission %} <form method="post"> {% csrf_token %} <a class="btn btn-info" href="{% url 'updatepost' post.id %}">Edit</a> <button type="submit" class="btn btn-danger" value={{post.id}} name="post_id">Delete</button> </form> {% endif %} </div> <div class="card-footer text-muted">{{post.created_at}}</div> </div> {% empty %} <p> No Post Yet :-: <p> {% endfor %} {% endblock %} the error comes in my .html file say: {% load custom_tags %} i also try to restard the server but it did nothing -
Celery with Django memory leak problem. Just can't figure out what is happening
`Celery is behaving weird. It is using 5.5 gb which is around 90% of ram during execution on server and it is slowing down server performance. Debug is set to False. Also, I set max_tasks_per_child to 2, but it is releasing memory after completing the task. I want to make it to use less memory, and it is executing about 600 seconds to complete the task. celery==5.1.2 Django==3.2.4 here is my task that I have tried:` def check_sites2(url): session = get_session() headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36' } try: response = session.head(url.url, headers=headers, timeout=21) except requests.exceptions.SSLError as e: response = session.head(url.url, verify=False, headers=headers, timeout=21) except Exception as e: print("Something went wrong {e}") def download_all_sites(sites): with concurrent.futures.ThreadPoolExecutor() as executor: executor.map(check_sites2, sites) @shared_task def api_checker_stats(): api_list = URL.objects.filter(active=True) # about 500 url objects download_all_sites(api_list)` return 1 -
NoReverseMatch at / .Reverse for ‘login’ not found. ‘login’ is not a valid view function or pattern name
I'm currently building a website using Django and have some issues, can someone please help me with this. Here is my urls.py file: from django.urls import path, include from . import views import sys app_name = "myapp" urlpatterns = [ path('', views.index, name='index'), path('register', views.register, name='register'), path('login', views.login, name='login'), path('logout', views.logout, name='logout'), path('wordsearch', views.wordsearch, name='wordsearch'), path('generate', views.generate, name="generate") ] and my views.py: from django.shortcuts import render, redirect # redirect: chuyen huong user toi page khac from django.contrib.auth.models import User, auth from django.contrib import messages from django.http import HttpResponse from .models import Feature from myproject.main import * from django.contrib.auth.forms import UserCreationForm, AuthenticationForm # Create your views here. # gửi request tới thư mục templates để tìm file index.html def index(request): # dictionary return render(request, 'login.html') # log in and sign up function def register(request): # check if the page is rendered with a post method if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() # log the user in return redirect('login') else: form = UserCreationForm() return render(request, 'register.html', {'form': form}) def login(request): if request.method == "POST": form = AuthenticationForm(data = request.POST) if form.is_valid(): return redirect('wordsearch') else: form = AuthenticationForm() return render(request, 'login.html', {'form': form}) # log out def logout(request): auth.logout(request) … -
Desperate for help: Django sessions failing intermittently
I’m in desperate need of some Django help. I wrote an app last year for a community event I run, called Nashville Tabletop Day. The app allows people to scan QR codes to interact with games they can play during the day. Locally it runs great. However when I push it to Fly.io it runs, but reliably drops sessions. By that I mean I can log in, browse to a page or two, and then the session just vanishes. It even happens if I stay on the same page and just reload a few times. It doesn’t happen immediately, or I’d think perhaps the database was the issue. But after 15-30 seconds, or a few page loads—poof. The event is this coming Saturday and this app has to be ready go. I’m tempted to think it could be a config issue, but this app ran last year, almost flawlessly and I’ve only made a few small updates this year. Django 4.1.7 Python 3.8.18 Database is SQLite INSTALLED_APPS = [ 'ntd.apps.NtdConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'whitenoise.runserver_nostatic', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'ntd.middleware.request_logger.RequestLoggerMiddleware', ] Some debugging I’ve done: I added a simple logging … -
created a templete folder that includes a nav bar.html but it is not showing up on the browser. i keep getting templete does not exist
nav bar is not showing and giving this error TemplateDoesNotExist at /navbar/ in the browser. i have created a folder and put in the nav bar as shown in the screenshot provided. if anyone can tell me the error. Is it because of the layout of my folders? wanted the nav bar to show up -
Djano form no populating with user instance
I'm very new to Django, and I am working on my very first project. I am trying get a model form to populate with the user instance. I have been struggling to find out when when I load the form it doesn't populate with the user instance. The form also doesn't update my model. Here is the model: class Income(models.Model): class Type(models.TextChoices): SALARY = 'Sal', 'Salary' VARIABLE = 'Var', 'Variable' class PayFrequency(models.TextChoices): MONTHLY = 'MON', 'Monthly' BIWEEKLY = 'BW', 'Bi-weekly' SEMIMONTHLY = 'SM', 'Semimonthly' WEEKLY = 'W', 'Weekly' ANNUAL = 'AN', 'Annually' user = models.OneToOneField( User, on_delete=models.PROTECT, primary_key=True, ) pay_amount = models.DecimalField(max_digits=6, decimal_places=2, null=True, blank=True) type = models.CharField(max_length=3, choices=Type.choices) frequency = models.CharField(max_length=3, choices=PayFrequency.choices) #Need day of the month, to calculate weekly, bi-weekly and monthly pay days pay_date_one = models.IntegerField( validators=[MaxValueValidator(31), MinValueValidator(1)] ) #Need second date to calculate semi monthly(2x a month, so need both dates) pay_date_two = models.IntegerField( validators=[MaxValueValidator(28), MinValueValidator(1)], null=True, blank=True ) def __str__(self): return f"{self.user} Income" Here is view: @login_required() def income(request): if request.method == "POST": form = IncomeForm(request.POST, instance=request.user) if form.is_valid(): form.save() else: form = IncomeForm(instance=request.user) return render(request, 'home/income.html', { "form": form }) Here is the template: {% extends "layout.html" %} {% block title %} Income {% … -
django permission using UserPassesTestMixin
I tried to use the user.has_perm() method, but it always returns False. def test_func(self): # Define your custom access control logic here user = self.request.user return user.is_authenticated and user.has_perm('CreateGroup.add_group') -
How do I override the delete() method in Django's DeleteView to send a success message?
I'm using Django 5.0.3. I have a job listings app, with a DeleteListingView. I want to override the delete() method, so that I can use messages.success() to send a message to the success url's template once a listing is deleted. However, the delete() method isn't being overridden. A listing gets deleted, and I'm redirected to the correct url, but the message isn't sent. I've even tried to add a print() statement inside delete() to see if it appears in cmd, but it doesn't. from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib import messages from django.urls import reverse_lazy from django.views.generic import ListView, DetailView from django.views.generic.edit import UpdateView, DeleteView, CreateView from .models import Listings class ListingsListView(ListView): model = Listings template_name = 'listings/listings_list.html' context_object_name = 'listings' class DeleteListingView(LoginRequiredMixin, DeleteView): model = Listings template_name = 'listings/listing_delete.html' context_object_name = 'listing' success_url = reverse_lazy('listings') def delete(self, request, *args, **kwargs): listing = self.get_object() listing_title = listing.job_title messages.success(self.request, f"Listing titled '{listing_title}' was deleted successfully.") print(f"delete() has been overridden successfully.") # To appear in cmd return super().delete(request, *args, **kwargs) and in listings_list.html template: {% for message in messages %} <p> {{ message }}</p> {% endfor %} Nothing I've tried is working, and I can't seem to find a solution anywhere. What …