Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
clean some json objects from google autocomplete api
I am currently working at a project which require to clean the data fetched from google autocomplete API. Most of you may have seen json response from that like below: [ "jarvis", [ "jarvis full form", "jarvis song", "jarvis ai", "jarvis meaning", "jarvis iron man", "jarvis in python", "jarvis technology", "jarvis meaning in hindi" ], [ "", "", "", "", "", "", "", "" ], [], { "google:clientdata": { "bpc": false, "tlw": false }, "google:suggestrelevance": [ 601, 600, 555, 554, 553, 552, 551, 550 ], "google:suggestsubtypes": [ [ 512, 433 ], [ 512 ], [ 512 ], [ 512, 433 ], [ 512, 433 ], [ 512 ], [ 512 ], [ 512 ] ], "google:suggesttype": [ "QUERY", "QUERY", "QUERY", "QUERY", "QUERY", "QUERY", "QUERY", "QUERY" ], "google:verbatimrelevance": 1300 } ] now what I need to do is to clear those google litters , [ "", "", "", "", "", "", "", "" ], [], { "google:clientdata": { "bpc": false, "tlw": false }, "google:suggestrelevance": [ 601, 600, 555, 554, 553, 552, 551, 550 ], "google:suggestsubtypes": [ [ 512, 433 ], [ 512 ], [ 512 ], [ 512, 433 ], [ 512, 433 ], [ 512 ], [ 512 ], [ … -
How do you print the Django SQL query for an aggregation?
If I have a django queryset print(queryset.query) shows me the SQL statement so I can validate it. But with aggregations they never return a queryset. How do you print those queries out. I guess I can turn on debug logging for the ORM and find them that way but it seems like I should be able to get it right before the execution engine sends it off to postgres..... -
The term 'mkvirtualenv' is not recognized as the name of a cmdlet, function, script file,or operable program
Below step by step answer: To install virtual environment using use below pip command: *py -m pip install --user virtualenv* Then create new environment: *py -m venv projectName* Then you have to activate your virtual environment: *.\projectName\Scripts\activate* Once done with activating virtual environment, You’ll see “(myproject)” next to the command prompt. -
running multiple django processes concurrently
I am using a package to send request needed to the front end, but I discovered that the package was blocking all other operations taking place in the server even the loading of a new page, so the server does not respond to any request until the package is through. Please how can I get the server to run multiple processes while the package is running. This is my code from django_eventstream import send_event#this is the package send_event('test', 'message', "Time spent processing the data "+ x+" mins"))// No other operation responds while this one is running -
How i can check boolean field in Javascript during the submitting of the form in a Django project
I want to check the char fields of my form if they are filled otherwise a msg will displayed, in same way I want to check 2 BooleanField exist in the same form, if both of them is false a message labeled will be displayed also, The issue that the first condition it works normally and show me the msg "Form incomplete. Please, fill out every field!" but the "second condition(if('#a_model1' === false && '#a_model2' === false )) it doesn't give me a result where i want to check both of the BooleanField if they are false. Here is my code: javascript code: <script language="JavaScript"> function mySubmitFunction(e) { var profession = $("#id_profession").val(); var taille = $("#id_taille").val(); let myVars = [profession, taille] if (myVars.includes("") || myVars.includes("Empty")) { document.getElementById('submit_label').innerHTML = 'Form incomplete. Please, fill out every field!'; e.preventDefault(); someBug(); return false; if('#a_model1' == false && '#a_model2' == false ){ document.getElementById('submit_label2').innerHTML = 'Check one of the model please in Models Section!'; e.preventDefault(); someBug(); return false; } } else { return true; } } </script> the boolean fields in the template.html: <span id="a_model1" >{{ form.model1}} </span> <span id="a_model2" >{{ form.model2}}</span> in models.py: model1 = models.BooleanField(verbose_name=" model1") model2 = models.BooleanField(verbose_name=" model2") so i want to … -
How to use row_factory with a non-default Sqlite database in Django
In the simple Sqlite3 code below, in order to use row_factory, I understand I need a connection object. However, when using a non-default database ("sqlite3_db" set up in DATABASES in settings.py), I can't figure out how this is done. def index_sqlite(request): from django.db import connections import sqlite3 cursor = connections["sqlite3_db"].cursor() #connection.row_factory = sqlite3.Row ==> how to access the connection object?? sql = "SELECT title, rating FROM book_outlet_book ORDER BY title" cursor.execute(sql) book_list = [item for item in cursor.fetchall()] return render(request, "book_outlet/index.html", { "title": "Some title", "books": book_list }) This code produces a list of tuples as expected, but I am after a "dictionary cursor" so I can do things like reference book_list[3].title (without using a model). -
How to discard and rebuild a postgres container using docker compose
So I have a docker-compose file that has 2 services app and db version: '3.9' services: app: build: context: . command: > sh -c "python manage.py wait_for_db && python manage.py makemigrations && python manage.py migrate && python manage.py collectstatic --noinput && python manage.py runserver 0.0.0.0:8000" ports: - 8000:8000 volumes: - .:/app - ./data/web:/vol/web environment: - SECRET_KEY=devsecretkey - DEBUG=1 - DB_HOST=db - DB_NAME=devdb - DB_USER=devuser - DB_PASS=changeme depends_on: - db db: image: postgres:13-alpine environment: - POSTGRES_DB=devdb - POSTGRES_USER=devuser - POSTGRES_PASSWORD=changeme I changed the Django model, deleted the old migration files (which I shouldn't have done) and then did a 'manage.py migrate --fake zero' and now on migrating I get an obvious error that the table already exists in the Postgres container. app_1 | File "/py/lib/python3.9/site-packages/django/db/backends/utils.py", line 99, in execute app_1 | return super().execute(sql, params) app_1 | File "/py/lib/python3.9/site-packages/django/db/backends/utils.py", line 67, in execute app_1 | return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) app_1 | File "/py/lib/python3.9/site-packages/django/db/backends/utils.py", line 76, in _execute_with_wrappers app_1 | return executor(sql, params, many, context) app_1 | File "/py/lib/python3.9/site-packages/django/db/backends/utils.py", line 85, in _execute app_1 | return self.cursor.execute(sql, params) app_1 | File "/py/lib/python3.9/site-packages/django/db/utils.py", line 90, in __exit__ app_1 | raise dj_exc_value.with_traceback(traceback) from exc_value app_1 | File "/py/lib/python3.9/site-packages/django/db/backends/utils.py", line 83, in _execute app_1 | … -
no module named contact error Python Django
https://github.com/MetsxxFan01/Python-Django that website should have all the code. modulenotfounderror: no module named 'contact' -
How to run the qcluster process in production (Django-q)?
I have a Django webapp. The app has some scheduled tasks, for this I'm using django-q. In local development you need to run manage.py qcluster to be able to run the scheduled tasks. How can I automatically run the qcluster process in production? I'm deploying to a Digital Ocean droplet, using ubuntu, nginx and gunicorn. -
Bad Request creating Automation Account in Azure Python SDK
I'm trying to create a new AutomationAccount using Python SDK. There's no problem if I get, list, update or delete any account, but I'm getting a BadRequest error when I try to create a new one. Documentation is pretty easy: AutomationAccountOperations Class > create_or_update() #!/usr/bin/env python3 # -*- coding: utf-8 -*- import os from azure.identity import AzureCliCredential from azure.mgmt.automation import AutomationClient credential = AzureCliCredential() automation_client = AutomationClient(credential, "xxxxx") result = automation_client.automation_account.create_or_update("existing_rg", 'my_automation_account', {"location": "westeurope"}) print(f'Automation account {result.name} created') This tiny script is throwing me this error: Traceback (most recent call last): File ".\deploy.py", line 10 result = automation_client.automation_account.create_or_update("*****", 'my_automation_account', {"location": "westeurope"}) File "C:\Users\Dave\.virtualenvs\new-azure-account-EfYek8IT\lib\site-packages\azure\mgmt\automation\operations\_automation_account_operations.py", line 174, in create_or_update raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) azure.core.exceptions.HttpResponseError: (BadRequest) {"Message":"The request body on Account must be present, and must specify, at a minimum, the required fields set to valid values."} Code: BadRequest Message: {"Message":"The request body on Account must be present, and must specify, at a minimum, the required fields set to valid values."} I've tried to use this method (create_or_update) on a different sdk like powershell using same parameters and it worked. Some thoughts? -
Django Rest Framework + S3: ImageField View Count
I use DRF for a frontend client and use S3 for hosting my images. Is there any reliably good way to fetch the total times an image has been viewed? Sort of like a hit-counter or YouTube style "view count" for the image? Ideally, if S3 could return some sort of times an image has been fetched that would be the best way to increment the counter, but I don't see a reliable way to do that. I could also make a network request every time an image on my client is "expanded", marking a view but that seems clunky. Any good ideas for incrementing image view count w/ DRF? -
Redirect django view to bokeh server startet with subprocess on webserver
I have a Django web server deployed on an AWS machine. I don't want to build a Django bokeh app. All I want to do is to display my dashboard which runs on the bokeh server in an HTML file which I can reach through an URL of my website. In my views.py I start the bokeh server with: import os print("debug1") os.system("panel serve /opt/bitnami/projects/blog/EnviAI/scripts/visz_pn_ssm_1.py") print("debug2") script = server_document("http://localhost:5006/visz_pn_ssm_1") return render(request, 'ssm_results.html', {'script' : script}) In my console, I can see that the server is started successfully. The debug1 print is also printed. The problem I have is the code stops here and do nothing until I cancel the bokeh server. The debug2 statement is printed as I cancel the bokeh server. The problem is that the code will never get to the point that the return redirect to the actual bokeh server because I have to kill them?! What can I do? -
icontains and query with Umlaut
My Product database mostly consists of a number and a json field: class Product(models.Model): data = models.JSONField() number = models.PositiveIntegerField() The data attribute looks like: data = {"name": "Würfel", "price": 20, "name": "truffels", "price": 1.20, } Now the query: products = Product.objects.all() r = products.filter(Q(data__icontains = "ürf")) results in an empty query, while r = products.filter(Q(data__icontains = "fel")) gives back results - this happens for all Umlaute. How can I address this? -
Sort objects by the date they were added to the ManyToManyfield field - Django
I save the products in ManyToMany field that the user has favored in my web application. class LikedProductPackage(models.Model): owner = models.ForeignKey(CustomUser, on_delete=models.CASCADE, blank=True, null=True) products = models.ManyToManyField(Product) I display my favorite products in the template user like this: {% for obj in liked_product_package_instance.products.all %} [...] {% endfor %} Is there any option to sort products by the date they were added to the LikedProductPackage.products field in the template or view without changing the of this function too much? -
Got AttributeError when attempting to get a value for field '' on serializer ''
I would like to be able to see the customers accounts. As you can see Accounts has foreign key to Customer. The idea is to be able to see the customer info with nested accounts objects, but it gives me a error Got AttributeError when attempting to get a value for field `accounts_items` on serializer `CustomerSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `Customer` instance. Original exception text was: 'Customer' object has no attribute 'Account'. so like this example where songs in the the artist object: ####MODELS#### class Account(models.Model): amount = models.FloatField(null=True) name = models.CharField(max_length=40) account_type = models.CharField(max_length=11, choices = ACCOUNT_TYPES) customer_id = models.ForeignKey(Customer, on_delete = models.CASCADE, default = None) bank_id = models.ForeignKey(Bank, on_delete = models.CASCADE, default = None) def __str__(self): return '{} {} {} {} {}'.format(self.amount, self.name, self.account_type, self.customer_id, self.bank_id) class Customer(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=40) phone = models.CharField(max_length=40) email = models.EmailField(max_length = 100) rank = models.CharField(max_length=11, choices = RANK_TYPES) bank_id = models.ForeignKey(Bank, on_delete = models.CASCADE, default = None) def __str__(self): return '{} {} {} {} {} {} {}'.format(self.id, self.first_name, self.last_name, self.phone, self.email, self.rank, self.bank_id) ###VIEW### class customer_page(generics.RetrieveUpdateDestroyAPIView): queryset = Customer.objects.all() serializer_class = CustomerSerializer … -
/entrypoint.sh: line 8: syntax error: unexpected end of file
Docker project was created on Linux machine, I'm running windows and I can't get docker-compose up to work. I've read through Stackoverflow's answers and so far I've tried the following (none have worked): Using Visual Studio Code I saved as "LF" instead of CRLF Deleted the file entirely, created a new one using Visual Studio Code, typed the words Cut the entire file, pasted it in Notepad so that formatting gets cleared, copied and pasted back Added various forms of #!/bin/bash to the start of the entrypoint.sh At this point I'm not sure what else to try. Any ideas? -
Django Query Foreign Key and Many to many field
Struggling with Django query, need some help. So I would like to get data for 5 different variables, accounts_data = (only username), user_account_data = (name), country_data = (iso_code), category_data = (choice), permisisons_data = (permissions). All data of the models is connected with UserAccount table, so need to get data from other tables only for existing user_accounts Example of models: class Account(models.Model): username = models.CharField(max_length=30) password = models.CharField(max_length=50) status = models.CharField(max_length=60) class UserAccount(models.Model): name= models.CharField(max_length=100) surname = models.CharField(max_length=100) category= models.ManyToManyField(Category) account = models.ForeignKey(Account) country = models.ForeignKey(Country) permissions = models.ForeignKey(Permissions) class Country(models.Model): iso_code = models.CharField(max_length=6) zip_code = models.CharField(max_length=10) class Category(models.Model): choice = models.CharField(max_length=12) connected_category = models.CharField(max_length=12) class Permissions(models.Model): permission = models.CharField(max_length=50) restriction = models.CharField(max_length=30) -
how to use javascript to make an animation on hover
Hey so I have a div which I want to animate when its being hovered over. at the moment it says 'logged in as username' but I want to make it so that when I hover over it (im using animate.style) the text fades to the right and a button saying sign out comes in its location where the person can click to sign out but if they hover out of the div for things to go back to the way they were with the same animation. but I get lots of bugs like, the text constantly changing and bugging out when moving mouse close to it. function loggedInHover() { let signin = document.getElementById("signin"); signin.classList.add("animate__animated", "animate__fadeOutRight"); setTimeout(function() { signin.style.display = "none"; signin.innerHTML = "Sign Out"; signin.style.display = "block"; signin.classList.remove("animate__fadeOutRight"); signin.classList.add("animate__animated", "animate__fadeInLeft"); }, 1000); } function loggedInOut() { let signin = document.getElementById("signin"); signin.classList.add("animate__animated", "animate__fadeOutRight"); signin.style.display = "none"; signin.innerHTML = "logged in as <strong class=\"h3\">{{ user.username }}</strong>"; signin.style.display = "block"; signin.classList.remove("animate__fadeOutRight"); signin.classList.add("animate__animated", "animate__fadeInLeft"); } -
Django - User model is not presented in Django AUTHENTICATION AND AUTHORIZATION, only Groups are presented
I have created ACCOUNTS app with 2 models in there. In admin.py i wrote @admin.register(Profile) class AccountsAdmin(admin.ModelAdmin): def username(self, obj): return obj.user.username @admin.register(User) class CategoryAdmin(admin.ModelAdmin): list_display = ('username', 'is_staff', 'is_superuser') def username(self, obj): return obj.user.username When i visit http://127.0.0.1:8000/admin/ i see ACCOUNTS with Profile and Users and AUTHENTICATION AND AUTHORIZATION where only Groups is presented. The real problem is that i cannot assign groups/permissions to my USERS Could you please help me to move my USER from ACCOUNTS administration to AUTHENTICATION AND AUTHORIZATION I expect to be able to assign groups and permissions to my users. When i create a Group it is assigned to ALL users in my DataBase. When i open a single user i see all User Permissions but i cannot assign anything to it. Thank you in advance. -
How to rename submitted file before upload to S3
I'm trying to create a website with Django where people can create recipes with a picture upload field. I have set the pictures to be uploaded to my S3 Bucket upon submission of the recipe creation form. However, right now, the picture gets uploaded to AWS with the its original file name. I want it to be renamed in the format recipe_id.extension before it is uploaded to AWS. I have a function in models.py (see below) that does the renaming operation for me. I just dont know how to process the filename through that function before uploading. In Models.py class Recipe(models.Model): # fields def rename_file(self, filename): upload_to = 'media/' ext = filename.split('.')[-1] if self.pk: filename = '{}.{}'.format(self.pk, ext) return os.path.join(upload_to, filename) def get_pk(self): return self.pk recipe_title = models.CharField(max_length=200) likes = models.PositiveIntegerField(default=0) pub_date = models.DateTimeField('date published') instructions = models.TextField(blank=True) author = models.CharField(max_length=200) picture = models.FileField(rename_file) in Views.py def new_recipe(request): r = Recipe(recipe_title=request.POST['title'], likes=0, pub_date=timezone.now(), instructions=request.POST['instructions'], author=request.user.username, picture=request.FILES['filename']) r.save() return render(request, 'wordofmouth/new_recipe.html', {'recipe': r}) in recipe creation template: {% load socialaccount %} <html> <body> {% include "navbar.html" %} <div style="text-align:center; margin-top: 8%;"> {% if user.is_authenticated %} <h1>Welcome Back <span style="color: #73bcf8">{{ user.username }}</span>!</h1> <p>The is the experiments page</p> <p>{{ "Submit a new … -
Translate Django group name
I am creating a Django application where users will have different possible groups to manage their permissions. I would like this application to be translatable in the future, but the group names are not translatable by default. How can I make this possible? I have thought about a few possible solutions, but I can't decide which one is best. Replace the template where the groups are displayed and translate the group names. Replace the group templates and change the __str__ method. Can you think of another solution? Which one do you think is the best? -
django-crontab works manually but not automatically
I hope i could get some help I have installed the django-crontab and created a cron task like the following inside of my cron.py inside my_django_app in django: import redis def hello(): redis.set("hello", "world") the above code works perfectly when I run python manage.py crontab run (cron hash)* and the key set successfully inside redis but the task doesn't run automatically have you had any similar experience? Note: I am using linux and python version 3.9 and django 3.2.3 -
NameError: name 'p' is not defined Python(Django)
I want to put the parameters from the database into a formula and it shows me an error like this. I want to solve it without global variables. Is this possible? How can I combine a parameter entered in the above function into the following function? BOT.PY ... ...; float_pattern = r'^\d{1,7}\.\d{1,2}$' ... ... def p_first(message): if message.text.isdigit() or re.match(float_pattern, message.text): chat_id = message.chat.id uid, _ = Profile.objects.get_or_create( external_id=message.chat.id, defaults={ 'name': message.chat.username } ) Message( profile=uid, param1=message.text ).save() p = Message.param1 print('Parameter (p) from:', chat_id) bot.send_message(message.chat.id, "Ajoyib, perimetr qabul qilindi!") msg = bot.send_message(message.chat.id, "<b>2. "Now secondside: "</b>", parse_mode="html") bot.register_next_step_handler(msg, height) return p else: msg = bot.send_message(message.chat.id, "Nice!") bot.register_next_step_handler(msg, p_first) def height(message): if message.text.isdigit() or re.match(float_pattern, message.text): chat_id = message.chat.id uid, _ = Profile.objects.get_or_create( external_id=message.chat.id, defaults={ 'name': message.chat.username } ) Message( profile=uid, param2=message.text ).save() h = Message.param2 print('Parameter (h) from:', chat_id) bot.send_message(message.chat.id, "Nice!" +f'{eval(str(p * h))} + ' is answer' else: msg = bot.send_message(message.chat.id, "Only number") bot.register_next_step_handler(msg, height) As a result: :( NameError: name 'p' is not defined MODELS.PY from django.db import models class Profile(models.Model): external_id = models.PositiveIntegerField( verbose_name='User ID', unique=True, ) name = models.TextField( verbose_name='User name', null=True, ) def str(self): return f'ID: {self.external_id} | Username: {self.name}' class Meta: verbose_name = … -
Moving object id parameter to consumers.py Django-Channels
I have a problem. The point is that I am making application with Django backend and React frontend. I wanted to make a websocket which allows to write in live-chat rooms. The problem is that I have no idea how to load dynamic a Room id. Ill try to explain. The point is that connect method from ChatConsumer class will load messages realted to room and send it by json to frontend. Ths is how it looks. class ChatConsumer(WebsocketConsumer): def connect(self): self.room_group_name = 'test' async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) messages = Message.objects.filter(room=[HERE I NEED TO PUT ID OF ROOM]) data_ready_for_json =list( messages.values('room','body','user')) self.accept() self.send(text_data=json.dumps({ 'type':'chat', 'message': data_ready_for_json })) Iam trying to send this id from my views, where I have RoomRetrieveView built by generics.RetrieveAPIView. Here it is: class RoomRetrieveView(generics.RetrieveAPIView): queryset = Room.objects.all() permission_classes = (AllowAny,) serializer_class = RoomSerializer def get_serializer_context(self): context = super(RoomRetrieveView,self).get_serializer_context() context.update({'id' : self.get_object().id}) roomId = context['id'] return roomId I was trying to move this roomId variable from get_serializer_context to my consumers.py file but it wants me to put "self" attribute but I have no idea how to figure it out. I also tried to use get_object method but it also not working. I have no idea. I also … -
There is a way to manipulate queryset from model after fetching from data base?
I’m a new in Python Django and I’m trying to encrypt and decrypt specific data before inserting to database and after fetching. My motivation is to do this blind, Meaning that I want to do that automatically. My tables include foreign key. class person(BaseModel): bank_account = models.ForeignKey(BankAccount) For insert to database i override save method in BaseModel: class BaseModel(Model): def save(self, *args, **kwargs): if self.__name__ is "BankAccount": encrypt_model(self, encrypt) # save the model super(BaseModel, self).save(*args, **kwargs) and this is work fine. this save method call for each model inside the Person Model, i mean that if inside BankAcount model there is another Model with ForeignKey and this model should be also encrypted and i save Person model "save" method will call for each model inside so i can check if this modle should be encrypted. my problem is in the fetching data from data base, i tried to create Manager and override get_queryset method: class newManager(PolymorphicManager): def get_queryset(self): queryset = super().get_queryset() if self.__name__ is "BankAccount": decrypt_data(queryset) return queryset the problem with this approach is that this method "get_queryset" called only one time for model, for example: Peson.newManager.filter(id=6) get_queryset called only one time and self.__name__ not equal to BankAcount. i can …