Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
No Django settings specified. Unknown command: 'createsuperuser' Type 'manage.py help' for usage
I am trying to create a superuser through createsuperuser command in manage.py console is throwing an error "No Django settings specified. Also tried in python console by runninf python manage.py createsuperuser Unknown command: 'createsuperuser' Type 'manage.py help' for usage." I AM USING PYCHARM settings.py """ Django settings for MovieFlix project. Generated by 'django-admin startproject' using Django 4.0.2. For more information on this file, see https://docs.djangoproject.com/en/4.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.0/ref/settings/ """ import os from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-#*8cdy*ul906(s4ei#g7h17)vv%)#0s5b##weupzn-&ct@ylez' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['192.168.2.12', '127.0.0.1'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'Core.apps.CoreConfig', 'movie.apps.MovieConfig', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', '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', ] ROOT_URLCONF = 'MovieFlix.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'Core/templates')] , 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'MovieFlix.wsgi.application' # Database # https://docs.djangoproject.com/en/4.0/ref/settings/#databases DATABASES … -
File C:\ProjectName\Scripts\Activate.ps1 cannot be loaded because running scripts is disabled on this system
Allow Windows PowerShell to Execute ScriptsPermalink. Type the following command in the PowerShell admin window to change the execution policy: set-executionpolicy remotesigned then enter "Y" or "A". Now you can activate your Django project. -
Getting top 3 most enrolled course by students
I am building a website where an instructor can create courses and students can enroll the courses. I wanted to display top 3 most enrolled courses/popular courses. I tried to filter the courses that the instructor has, find the number of students that has enrolled to the courses and ordered them by descending which means it will display from highest to lowest number of enrolled students per course. It will then display only the top 3 most enrolled courses. However, my code does not work. Please help T.T models.py class Enrollment(models.Model): student = models.ForeignKey(User, on_delete=models.CASCADE) course = models.ForeignKey(Course, on_delete=models.CASCADE) enrollment_date = models.DateField(auto_now_add=True, null = True) class Course(models.Model): user = models.ForeignKey(Users, on_delete = models.CASCADE) media = models.ImageField(upload_to = 'media/course') title = models.CharField(max_length=300, null = False) subtitle = models.CharField(max_length=500, null = False) description = models.TextField(max_length=5000, null = False) language = models.CharField(max_length=20, null = False, choices=LANGUAGE) level = models.CharField(max_length=20, null = False, choices=LEVEL) category = models.CharField(max_length=30, null = False, choices=CATEGORY) subcategory = models.CharField(max_length=20, null = False) price = models.FloatField(null = True) roles_responsibilities = models.TextField(max_length=2500, null = False) timeline_budget = models.TextField(max_length=250, null = False) req_prerequisite = models.TextField(max_length=2500, null = False) certificate = models.CharField(max_length=5, null = False, choices=CERTIFICATE) slug = AutoSlugField(populate_from='title', max_length=500, unique=True, null=True) views.py … -
In Django have written a clear code everything good but still the css does not display on the webscreen and i am using python 3.10 and django 4
Am using Python 3.10 And django 4.0.3 I tried to change my base dir but still did not work Firstly it was STATIC_URL = ' /static/' STATICFILES_DIR=[os.path.join(BASE_DIR),] Then secondly i tries this STATIC_URL = ' /static/' STATICFILES_DIR = [os.path.join(BASE_DIR),] STATIC_ROOT = os.path.join (os.path.dirname (BASE_DIR),"static") -
Formatting Django test output
I would like to format the output of test output in my Django app because I have a lot of tests and at this point there is so much output that it is unreadable. I have read Django docs on logging and I understand that I would need to configure LOGGING dict in my settings and use Loggers, Handlers, and Formatters, along with Python's native logging lib doing majority of heavy lifting. The problem is that I don't know where to begin. Here is what I would like to achieve in terms of output: TOTAL tests run: 123 Failed: 4 Skipped: 5 Passed: 114 APP2 tests run: 34 Failed: 0 Skipped: 1 Passed: 114 APP3 tests run: 67 Failed: 5 Skipped: 0 Passed: 62 According to Django docs logging is fairly customizable with something like this (taken from official docs, closer to the bottom of the page): LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '{levelname} {asctime} {module} {process:d} {thread:d} {message}', 'style': '{', }, 'simple': { 'format': '{levelname} {message}', 'style': '{', }, }, 'filters': { 'special': { '()': 'project.logging.SpecialFilter', 'foo': 'bar', }, 'require_debug_true': { '()': 'django.utils.log.RequireDebugTrue', }, }, 'handlers': { 'console': { 'level': 'INFO', 'filters': ['require_debug_true'], … -
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 …