Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
psycopg2.errors.InvalidTextRepresentation: invalid input syntax for type double precision: "max"
I changed the data type of a field "max" in my model from text to float and I got this error when I run python3 manage.py migrate after makemigrations. What's the solution please? Running migrations: psycopg2.errors.InvalidTextRepresentation: invalid input syntax for type double precision: "max". The above exception was the direct cause of the following exception: django.db.utils.DataError: invalid input syntax for type double precision: "max my original model: class calculation(models.Model): fullname = models.TextField(blank=True, null=True) min = models.TextField(blank=True, null=True) max = models.TextField(blank=True, null=True) unit = models.TextField(blank=True, null=True) my model after the change:: class calculation(models.Model): fullname = models.TextField(blank=True, null=True) min = models.FloatField(blank=True, null=True) max = models.FloatField(blank=True, null=True) unit = models.TextField(blank=True, null=True) -
Django channels websockets. How send notification specific user
Now everything works like this: the sender of the notification goes into the profile of the one to whom the notification will be sent. A button is pressed, a websocket connection is started, a name is obtained from the button or URL, and based on this, a notification is created in the database, after which this notification should be displayed to the one to whom the notification was sent. But I have a problem, the notification is displayed for everyone. I don't understand how to add a recipient to a group. I will be glad to help! consumers.py @database_sync_to_async def get_user(username): try: return User.objects.get(username=username) except: return AnonymousUser() @database_sync_to_async def create_notification(receiver, sender, typeof="task_created", status="unread"): notification_to_create = Notifications.objects.create(user_revoker=receiver, user_sender=sender, type_of_notification=typeof) print('Уведомление создано') return notification_to_create.user_revoker.username, notification_to_create.type_of_notification @database_sync_to_async def create_or_get_group(user_receiver): Group.objects.get_or_create(name='notifications') my_group = Group.objects.get(name='notifications') my_group.user_set.add(user_receiver) class NotificationConsumer(AsyncWebsocketConsumer): async def websocket_connect(self, event): # self.group_name = f'notifications_for_{self.scope["user"].username}' self.group_name = 'notifications' await self.channel_layer.group_add(self.group_name, self.channel_name) await self.accept() # @database_sync_to_async async def websocket_receive(self, event): data_to_get = json.loads(event['text']) user_receiver = await get_user(data_to_get['receiver_username']) user_sender = await get_user(data_to_get['sender_username']) get_of = await create_notification(user_receiver, user_sender) channel_layer = get_channel_layer() await create_or_get_group(user_receiver) await self.channel_layer.group_add( self.group_name, self.channel_name, ) await (channel_layer.group_send)( self.group_name, { "type": "send_notification", "value": get_of[0], } ) async def send_notification(self, event): await self.send(json.dumps({ "type": "notifications", "data": … -
Phaser & Django: Place canvas inside div
I'm trying to embed a Phaser game into a Django application, but struggling with the most basic of operations to get started: Making sure the canvas is placed inside a particular div as to center it on the middle of the page. From what I could gather, for this to work, I should simply specify the parent div. However, whenever I specify the parent div, the canvas is nowhere to be found. When I leave out the line again, it reappears, but outside the layout. {% extends "app/layout.html" %} {% block content %} <h2>{{ title }}.</h2> <h3>{{ message }}</h3> <div id='phaser-canvas'></div> {% endblock %} <script> var config = { type: Phaser.AUTO, width: 800, height: 600, parent: 'phaser-canvas', scene: { preload: preload, create: create, update: update } }; var game = new Phaser.Game(config); function preload() { } function create() { } function update() { } </script> What am I not understanding? -
How to display values in multiple lines by indentation in Django Admin?
I put \n between obj.first_name and obj.last_name as shown below to display first name and last name separately in 2 lines by indentation: # "admin.py" from django.contrib import admin from .models import Person @admin.register(Person) class PersonAdmin(admin.ModelAdmin): list_display = ('person',) def person(self, obj): # ↓↓ Here return obj.first_name + "\n" + obj.last_name But, first name and last name were displayed in one line without indentation as shown below: John Smith # One line So, how can I display first name and last name separately in 2 lines by indentation as shown below: John # 1st line Smith # 2nd line -
Django-tables2 with SingleTableMixin fails to retrieve table or queryset
Receiving error "Expected table or queryset, not str" Trying to display queryset as table. But unable to. Views.py class EntriesTableView(LoginRequiredMixin, SingleTableMixin): table_class = entryTable table_data = Entries.objects.annotate(row_number=models.Window( expression=RowNumber(), order_by=[models.F('id').desc()], )).order_by('row_number') # model = Entries context_table_name = "table" paginate_by = 15 def get_template_names(self): if self.request.htmx: template_name = "partials/entries_list.html" else: template_name = "entries.html" return template_name relative tables.py class entryTable(tables.Table): class Meta: model = Entries template_name = 'django_tables2/bootstrap.html' template(entries.html) ............... {% include "partials/accomodations_list.html" %} ............ template (partials/entries_list.html) Error is highlighted in the below template on line 2. {% load render_table from django_tables2 %} {% render_table table %} Django version - 4.1.3 Django-tables2 version - 2.5.1 And the model Entries do have data. -
django.db.utils.DataError: invalid input syntax for type double precision: “max”
I changed the data type of a field "max" in my model from string to float and I got this error when I run python3 manage.py migrate after makemigrations. What's the solution please? django.db.utils.DataError: invalid input syntax for type double precision: "max -
Django translation doesn't create or compile new .po files
I am creating REST API with Django Rest-FrameWork. While working with translation, the command compilemessages doesn't work as docs, it does not create .po files from my local folder, even though I have tried the command makemessages. When I open the locale folders which conatian .po files, the translation does not appear there. But even though after changing local (incorrect folder name) directory in setting.py, it does not hurt the two commands above. And addition how can I find where the actual problem? -
Why does import in Django not work when online. It is highlighted with white, not green, as locally, like it is not recognized
In my urls.py: from . import views The dot and views are white(grey) like it is not recognized. The same problem is in views.py: from .forms import PostForm from .forms import ServiceForm from .forms import BlogForm from .forms import CategoryForm from .models import Post from .models import Service from .models import Blog from .models import Image from .models import Category They are all white/grey, but must be green, when recognized. The forms.py, models.py, views.py and urls.py are located in the same folder. It is an app folder. It has started to be after I uploaded it online. Please let me know what do I do wrong? Thanks. -
How do I check if Django is ruuning with subprocess?
I want to run Django server with subprocess. Here is my code: import subprocess import os def run_BackServer(): current_dir = os.getcwd() target_dir = os.path.join(current_dir, 'marketBack/BackServer') os.chdir(target_dir) process = subprocess.Popen(['python', 'manage.py', 'runserver'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) output, error = process.stdout.read(), process.stderr.read() print(output, error) run_BackServer() I think the Django server is running well. However, when I want to check it, I can't seem to get the output because the process has not finished technically. Is there any way I can check if the server is running? -
Reverse for 'profile/{{user.username}}' not found. 'profile/{{user.username}}' is not a valid view function or pattern name
{% if user.is_authenticated %} <li><a href="{% url 'home' %}">Home</a></li> <li><a href="{% url 'profile/{{user.username}}' %}">Profile</a></li> <li><a href="{% url 'settings' %}">Settings</a></li> <li><a href="{% url 'logout' %}">Logout</a></li> {% endif %} <li><a href="{% url 'profile/{{user.username}}' %}">Profile</a></li> Here I can't use this Django format to redirect at user's profile page but if do it like <li><a href='/profile/{{user.username}}'>Profile</a></li> I can use this way. Why I am not able to use Django url? urlpatterns = [ path('', views.index, name='index'), path('home', views.home, name='home'), path('likes', views.likes, name='likes'), path('login', views.login, name='login'), path('follow', views.follow, name='follow'), path('search', views.search, name='search'), path('about', views.aboutus, name='about'), path('signup', views.signup, name='signup'), path('upload', views.upload, name='upload'), path('logout', views.logout, name='logout'), path('settings', views.settings, name='settings'), path('profile/<str:pf>', views.profile, name='profile'), ] here is my url patterns. -
how to link m3u8 file to HTML
I wonder how to link a m3u8 file I downloaded and opened in VLC (its live broadcast). it looks like HTML cannot read this type of files,, its not a link its a file when I opens it it shows a live broadcast for a football match for example... please if anyone can help me just to show the video on html page, aim using a Django framework. I tried to link the video file by {% load static %} from the header then i put the video file inside static/img folders, then i linked the video folder by doing this: -
How can i show error message for the user when using Email already exists
I'm using the Django framework. And I'm attempting to show an error message when the user registers and uses the username and/or email that already exists on a website. But the problem is when a user registers a new username and email, the system is not registered in a database. How can solve this problem? forms.py : class RegisterUserForms(UserCreationForm): class Meta: model = User fields = ['username','email','password1','password2'] widgets = { 'email':forms.EmailInput(attrs = { 'required' : True, 'placeholder' : 'Email@example.com', 'autofocus' : True, 'name':'email', }), 'username':forms.TextInput(attrs = { 'required' : True, }) } def __init__(self, *args, **kwargs): super(RegisterUserForms, self).__init__(*args, **kwargs) self.fields['password1'].widget.attrs={'placeholder': 'Password from numbers and letters of the Latin alphabet'} self.fields['password2'].widget.attrs={'placeholder': 'Password confirmation'} def clean_username(self): username_input = self.cleaned_data.get('username') if User.objects.filter(username=username_input ).exists(): raise forms.ValidationError("username already exists!") def clean_email(self): email_input = self.cleaned_data.get('email') if User.objects.filter(email=email_input).exists(): raise forms.ValidationError("email already exists!") views.py: def registerpage(request): form = RegisterUserForms() if request.method == 'POST': try: form = RegisterUserForms(request.POST) if form .is_valid(): user = form.save() login(request, user) return redirect('login') except Exception as e: print(e) raise context = { # dictionary 'form': form } return render(request, r'user\register.html', context) register.html : <body> <div class="page register-page form" style="text-align: right;" > <h2 class="title">register</h2> <form method="POST" class="register-form"> {% csrf_token %} <div class="fieldWraber"> <label for="{{form.email.id_for_label}}"> Email … -
Django allauth overriding DefaultSocialAdapter
Project's backend and frontend are separate and trying to implement provider login via google. in settings.py LOGIN_REDIRECT_URL = "http://localhost:3000" SOCIALACCOUNT_ADAPTER = "users.adapter.CustomOAuth2Adapter" in adapter.py class CustomOAuth2Adapter(DefaultSocialAccountAdapter): def save_user(self, request, sociallogin, form): user = sociallogin.user user.is_active = True user.save() token = Token.objects.create(user=user) response = HttpResponseRedirect(settings.LOGIN_REDIRECT_URL) response.set_cookie('auth_token', token) return response def pre_social_login(self, request, sociallogin): try: user = User.objects.get(email=sociallogin.user.email) user.is_active = True user.save() request.set_cookie('auth_token', request.user.auth_token.key, domain=settings.LOGIN_REDIRECT_URL) # sociallogin.connect(request, user) # return response except: pass there is one main problem here. when login or save has success trying to redirect from backend to frontend. It's using LOGIN_REDIRECT_URL and works. but when it's redirecting I try to set token into cookie. but it doesn't set. # this part of code is not working correctly. request.set_cookie('auth_token', request.user.auth_token.key, domain=settings.LOGIN_REDIRECT_URL) Additionally I tried to set cookie like below. def pre_social_login(self, request, sociallogin): try: user = User.objects.get(email=sociallogin.user.email) user.is_active = True user.save() # sociallogin.connect(request, user) response = HttpResponseRedirect(settings.LOGIN_REDIRECT_URL) response.set_cookie('auth_token', request.user.auth_token.key, domain=settings.LOGIN_REDIRECT_URL) return response except: pass but this doesn't worked either. when backend and frontend are separate how to send token with redirection. -
How to list categories in base.html template in Django?
I'm working on my Django blog. I want to add list of categories in the footer and the footer is in the base.py. this is views.py def category_list(request): categories = Category.objects.all() context = {'categories': categories} return render (request, 'base.html', context) this is base.html <ul class="list-inline font-small"> {% for category in categories %} <li class="list-inline-item"><a href="{{ category.get_absolute_url }}">{{ category.category_name }}</a></li> {% endfor %} </ul> If I put this in category detail, and I can see list of categories when I'm on category page, but not on other pages like home or post-page. Any idea how to make this work? Thanks in advance! -
django with mongoDB model designing
Could you please help me to create the DB design/Model for this below json data. { "myCart": { "dev": { "dev-1": { "version": "pi-2", "test": "pravil-nov-2022", "test2": "1.x.bi-9", "test3": "dev", }, "dev-2": { "version": "pi-1", "pravil": "pravil-nov-2021", "test2": "1.x.bi-8", "test3": "dev", } }, "stage": { "stage-1": { "version": "pi-2", "test": "pravil-nov-2021", "test2": "1.x.bi-1", "test3": "stage", }, "stage-2": { "version": "pi-4", "test": "pravil-nov-2021", "test2": "1.x.bi-5", "test3": "stage", } }, "prod": { "Prod-1": { "version": "pi-6", "test": "pravil-nov-2021", "test2": "1.x.bi-2", "test3": "Prod", } } } i have tried to create DB design for this data and im strugling to create it because of this random key(dev, staging, prod) -
How to deploy Django Application with Celery + Reddis on Google Cloud Run (docker-compose)
I have a docker-compose.prod.yaml containing 7 services which I'd like to deploy to Google Cloud Run. I like the benefits of a serverless solution, to my understanding the two other options are: Google App Engine, however this answer suggest multiple containers isn't possible GKE is a good fit but we're a small team without a dedicated DevOps engineer or internal Kubernetes expertise which is what would be required Is deploying such application possible on Google Cloud Run or even desirable? Some guidance on how to achieve this would be greatly appreciated. I'm favouring simplicity and cost efficiency. Some potential issues I'm foreseeing: Setting up networking between containers Instances are destroyed within 15 minutes Connecting all the volumes together Deploying 7 containers individually potentially tedious I do acknowledge that Google offers Cloud Tasks however, that would tie us to GCP and we'd miss the extensive functionality of Celery. One of the changes made to the docker-compose.prod.yaml will be switching the db container for a Cloud SQL managed instance. version: '3.8' services: nginx: build: ./compose/production/nginx volumes: - staticfiles:/app/staticfiles - mediafiles:/app/mediafiles ports: - 80:80 - 5555:5555 - 15672:15672 depends_on: - web - flower web: build: context: . dockerfile: ./compose/production/django/Dockerfile command: /start volumes: - … -
How to store directory, sub directory and file paths in a Python Dictionary?
I am developing a software which analyze excel files stored in Years directories which contains months directories and each month directory consist of excel files. Structure as shown below. In order to achieve my goal, I have used the code below os.walk("..\..\..\..\ema_monthly_reports") the above code shows all the directories, sub directories and files ('..\..\..\..\ema_monthly_reports', ['2022', '2023'], [])('..\..\..\..\ema_monthly_reports\2022', ['1', '10', '11', '12', '2', '3', '4', '5', '6', '7', '8', '9'], []) ('..\..\..\..\ema_monthly_reports\2022\1', [], ['Basic Facilities.csv'])('..\..\..\..\ema_monthly_reports\2022\10', [], ['Basic Facilities.csv'])('..\..\..\..\ema_monthly_reports\2022\11', [], ['Basic Facilities.csv'])('..\..\..\..\ema_monthly_reports\2022\12', [], ['Basic Facilities.csv'])('..\..\..\..\ema_monthly_reports\2022\2', [], ['Basic Facilities.csv'])('..\..\..\..\ema_monthly_reports\2022\3', [], ['Basic Facilities.csv'])('..\..\..\..\ema_monthly_reports\2022\4', [], ['Basic Facilities.csv'])('..\..\..\..\ema_monthly_reports\2022\5', [], ['Basic Facilities.csv'])('..\..\..\..\ema_monthly_reports\2022\6', [], ['Basic Facilities.csv'])('..\..\..\..\ema_monthly_reports\2022\7', [], ['Basic Facilities.csv'])('..\..\..\..\ema_monthly_reports\2022\8', [], ['Basic Facilities.csv'])('..\..\..\..\ema_monthly_reports\2022\9', [], ['Basic Facilities.csv'])('..\..\..\..\ema_monthly_reports\2023', ['1'], [])('..\..\..\..\ema_monthly_reports\2023\1', [], ['Basic Facilities.xlsx']) but I don't know how to properly manage years, months and files names in dictionary format. -
I am trying to get UserProfile using Django Simple JWT, but however I get error "Invalid data. Expected a dictionary, but got User."
I wanted to use email instead of username to login the user, so I obtained below code from the django documentation from custom authorization section. class UserManager(BaseUserManager): def create_user(self, email, name, password=None, password2=None): """ Creates and saves a User with the given email, date of birth and password. """ if not email: raise ValueError('User must have an Email Address') user = self.model( email=self.normalize_email(email), name = name ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, name, password=None): """ Creates and saves a superuser with the given email, date of birth and password. """ user = self.create_user( email, name=name, password=password ) user.is_admin = True user.save(using=self._db) return user class User(AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) name = models.CharField(max_length=255) created_on = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now=True) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name'] def __str__(self): return self.email def has_perm(self, perm, obj=None): "Does the user have a specific permission?" # Simplest possible answer: Yes, always return self.is_admin def has_module_perms(self, app_label): "Does the user have permissions to view the app `app_label`?" # Simplest possible answer: Yes, always return True @property def is_staff(self): "Is the user a member of staff?" # Simplest possible answer: All admins are … -
how to can run mindee doctr with python file
The tutorial is for Jupiter or google Collab How can I achieve that import os os.environ['USEA-TF'] ='1' from doctr.io import DocumentFile from doctr.models import ocr_predictor model = ocr_predictor(pretrained=True) document = DocumentFile.from_images('IM.jpg') result = model(document) result.show(document) json_response = result.export() print(json_response) I want to run the doctr in python file -
How to come back to DJANGO project
I'm pretty new in DJANGO. I was creating and editing my page I Sublime, but I accidentally closed my terminal where the DJANGO link was working. now when I tried to generate a new one this error comes out. It is possible to find a working link in files I used to editing? Probably gonna be a simple mistake I'm doing. Thanks guys. photo of the error The error I'm sure you know what to do. -
Github Actions - ImportError: Couldn't import Django
I am trying github actions on our project but it seems it cant find the django module even when it gets installed via the requirements.txt Any feedback would be greatly appreciated ` name: Eccounting tests on: push: branches: [ "main", "development", "features", "amazon", "shopify", "front_end", "wallmart"] pull_request: branches: [ "main", "development", "features", "amazon", "shopify", "front_end", "wallmart"] jobs: build: runs-on: ubuntu-latest strategy: max-parallel: 4 matrix: python-version: [3.9] steps: - uses: actions/checkout@v3 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v3 with: python-version: ${{ matrix.python-version }} - name: Validate version run: python --version - name: Run simple python code run: python -c 'import math; print(math.factorial(5))' - name: Install Dependencies run: | python3 -m pip install --upgrade pip python3 -m venv .venv source .venv/bin/activate python3 -m pip install -r requirements.txt - name: Start Redis uses: supercharge/redis-github-action@1.4.0 - name: Run Tests env: DJANGO_SETTINGS_MODULE: ${{ secrets.DJANGO_SETTINGS_MODULE }} SECRET_KEY: ${{ secrets.SECRET_KEY }} DEBUG: ${{ secrets.DEBUG }} SP_API_REFRESH_TOKEN: ${{ secrets.SP_API_REFRESH_TOKEN }} LWA_APP_ID: ${{ secrets.LWA_APP_ID }} LWA_CLIENT_SECRET: ${{ secrets.LWA_CLIENT_SECRET }} SP_API_ACCESS_KEY: ${{ secrets.SP_API_ACCESS_KEY }} SP_API_SECRET_KEY: ${{ secrets.SP_API_SECRET_KEY }} SP_API_ROLE_ARN: ${{ secrets.SP_API_ROLE_ARN }} SP_APPLICATION_ID: ${{ secrets.SP_APPLICATION_ID }} SHOPIFY_API_KEY: ${{ secrets.SHOPIFY_API_KEY }} SHOPIFY_API_SECRET_KEY: ${{ secrets.SHOPIFY_API_SECRET_KEY }} SHOPIFY_API_SCOPES: ${{ secrets.SHOPIFY_API_SCOPES }} CELERY_BROKER_URL: ${{ secrets.CELERY_BROKER_URL }} REDIS_BACKEND: ${{ secrets.REDIS_BACKEND }} APP_URL: … -
Django - on_rollback using transaction.atomic
What exactly I want to do On rollback, I want to run a do_something function. Is it possible to do so? Right now, transaction.atomic does its job perfectly, but it only takes care of database. On rollback, I want to take care of a few other things using that do_something function I mentioned before. My use cases for transaction.atomic are pretty simple and there's not much to say about, I just use it on typical views which are creating and updating objects. -
Remote Access Database
I would like to connect to a remote database to continue the development of my application, say in another city, so we are not local but the two machines with the databases have access to the internet ; I use Sql server, how to have access to the other database? . I want to connect two remote databases via internet -
Migrate development PostgreSQL data to Railway
I've been using PostgreSQL in development and populating the database with some data. I deployed the whole app to Railway following these steps. When I create a new database in the railway production server it will always be a blank database. How can I migrate the data of my development database to Railway production's? The code I have in my Django's settings.py file is this: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'basededatos1', 'USER': 'db_admin', 'PASSWORD': 'mYWZQy65viXG50wohppK.Z%uauhghs.CuB#k}nE45A=nK}Qe1*_g=sJF~*0}nQ^!aMuCL#]1i+i-hvs1N8:0Q9fGCdC1gNGc5g~T', 'HOST': 'localhost', 'PORT': '5432', } } And added this code while following the deployment tutorial: import dj_database_url db_from_env = dj_database_url.config(conn_max_age=500) DATABASES['default'].update(db_from_env) The newly created PostgreSQL database in the Railway production dashboard is a blank, new database with different parameters to the one I had, but can't edit them. What is the way to go for using my development database's data into production? -
How do I integrate video calling with django (simple)?
I have a django backend setup, and I want to integrate video calling for people on the same url (only 2 people will be in the call per page and it has url patterns so they will be on independent urls). Whats an easy way of implementing this?