Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to split a model field's value into the multiple model fields in django migration?
I want to write a new migration file to change old bad data to the better one. For example, the old model was like this: from django.db import models class Person(models.Model): fullname = models.CharField(max_length=250, null=True) information = models.CharField(max_length=350, null=True) and the value of fullname is sth like: first_name:George;last_name:Adam Pince Green which first_name and last_name are always in the same order. The value of information is like: id_code:0021678913;born_in:Canada;birth_year:1975 or birth_year:1990;born_in:Portugal;id_code:0219206431 which are not ordered. now I need to write a migration file that split this fullname and information values to the new model like: from django.db import models class Person(models.Model): first_name = models.CharField(max_length=30, null=True) last_name = models.CharField(max_length=50, null=True) id_code = models.CharField(max_length=10, null=True) born_in = models.CharField(max_length=30, null=True) birth_year = models.PositiveSmallIntegerField(null=True) -
How to get values from Django "Choices" and send them as an Axios request to React frontend via a drop down element?
DJANGO : Models.py class Meditation(models.Model): # CHOICES BENEFIT_CHOICES = ( ('happiness', 'Happiness'), ('acceptance', 'Acceptance'), ('resilience', 'Resilience'), ('relaxation', 'Relaxation'), ('letting go', 'Letting Go'), ('depression', 'Depression'), ('anxiety', 'Anxiety'), ('stress', 'Stress'), ('grief', 'Grief'), ('healing', 'Healing'), ('workplace', 'Workplace'), ('sleep', 'Sleep'), ('gratitude', 'Gratitude'), ('body scan', 'Body Scan') ) MEDITATION_TYPE_CHOICES = ( ('guided', 'Guided'), ('unguided', 'Unguided'), ) # RELATIONSHIP user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="user_meditation") # DATABASE FIELDS name = models.CharField(max_length=100, verbose_name="Meditation Name") benefit = models.CharField(max_length=200, verbose_name="Benefit", choices=BENEFIT_CHOICES) length = models.DurationField(verbose_name="Meditation Length") type_of_meditation = models.CharField(max_length=200, verbose_name="Type of Meditation", choices=MEDITATION_TYPE_CHOICES) meditation_link = models.URLField(max_length=500, verbose_name="Meditation URL") # META class Meta: verbose_name = "User's Meditation" verbose_name_plural = "User Meditations" # TO STRING METHOD def __str__(self): return "User's Meditation " + str(self.id) + " - " + self.name DJANGO : Views.py class MoodList(generics.ListCreateAPIView): queryset = Mood.objects.all() serializer_class = MoodSerializer class MoodDetail(generics.RetrieveUpdateDestroyAPIView): queryset = Mood.objects.all() serializer_class = MoodSerializer DJANGO : Urls.py urlpatterns = [ # view paths: # MOODS path('moods/', views.MoodList.as_view(), name='mood_list'), path('moods/<int:pk>', views.MoodDetail.as_view(), name='mood_details') REACT : MoodPrompt.jsx export default function MoodPrompt() { const [mood, setMood] = useState({ happy: "", comfortable: "", sad: "", }); const handleMood = async (event) => { event.preventDefault(); try { const response = await dataAPI.post("/data/moods/", { happy: mood.happy, comfortable: mood.comfortable, sad: mood.sad, }); return console.log(response); } catch … -
Having trouble registering custom user for 'Apps' directory structure
I have a Django project, but instead of having the django project and all of the apps within the same directory, I have created a directory called 'Apps' where I put all of my apps. For example the structure might look like this: django_project -settings.py ....... - wsgi.py apps - app1 - admin.py ...... - views.py - login_app - admin.py ...... - views.py I want to add a custom user to the login_app. However I am getting a problem when I change AUTH_USER_MODEL in the django_project to the following: AUTH_USER_MODEL = 'login_app.User' AUTH_USER_MODEL refers to model 'login_app.User' that has not been installed I have tried changing it to 'apps.login_app.User' but this raises an error. How do I register a 'User' when the directory structure is apps/login_app ? -
Passing in a list through AJAX in Django
On the backend, I have a request that needs to get updated when ajax is called. options = request.GET.getlist('Options') By, default it is an empty list [], but when I send data through ajax it is returning a stringed array within an array. data: {'Options':JSON.serialize(["Fruit"])} On the backend, it returns --> [ ' [ "Fruit" ] ' ] If, I pass in a string, like 'Fruit' data: {'Options': "Fruit")} then I get my expected result on the backend --> [ 'Fruit' ] This is okay, but not for multiple values, how can I work around this? -
django filter and add result field into new datafield
I have a canvas field which helps user draw and save drawings and load back their drawings. I am able to load the drawing based on single id But i need to filter drawing based on a certain filed and the i need to make a coordinates of resulted queryset My model is as follows class Drawing(models.Model): drawingJSONText = models.TextField(null=True) project = models.CharField(max_length=250) Sample data in drawingJSONText {"points":[{"x":109,"y":286,"r":1,"color":"black"},{"x":108,"y":285,"r":1,"color":"black"},{"x":106,"y":282,"r":1,"color":"black"},{"x":103,"y":276,"r":1,"color":"black"},],"lines":[{"x1":109,"y1":286,"x2":108,"y2":285,"strokeWidth":"2","strokeColor":"black"},{"x1":108,"y1":285,"x2":106,"y2":282,"strokeWidth":"2","strokeColor":"black"},{"x1":106,"y1":282,"x2":103,"y2":276,"strokeWidth":"2","strokeColor":"black"}]} My view.py file def load(request): """ Function to load the drawing with drawingID if it exists.""" try: filterdata = Drawing.objects.filter(project=1).count() drawingJSONData = Drawing.objects.get(id=filterdata).drawingJSONText #drawingJSONData["points"]=filterdata["points"] #drawingJSONData["lines"] = filterdata["lines"] # Sending context with appropriate information context = { "loadIntoJavascript": True, "JSONData": drawingJSONData } # Editing response headers and returning the same response = modifiedResponseHeaders(render(request, 'MainCanvas/index.html', context)) return response I need to iterate through all the points and add them to the new data Adding two data points def load(request): """ Function to load the drawing with drawingID if it exists.""" try: drawingJSONData1 = json.loads(Drawing.objects.get(id=1).drawingJSONText) drawingJSONData2 = json.loads(Drawing.objects.get(id=3).drawingJSONText) drawingJSONData = dict() drawingJSONData["points"] = drawingJSONData1["points"] + drawingJSONData1["points"] drawingJSONData["lines"] = drawingJSONData1["lines"] + drawingJSONData2["lines"] drawingJSONData = json.dumps(drawingJSONData) drawingJSONData["points"]=filterdata["points"] drawingJSONData["lines"] = filterdata["lines"] # Sending context with appropriate information context = { "loadIntoJavascript": True, "JSONData": drawingJSONData } # Editing response … -
Css linked but doesn't work in my django website
Everything goes normal , I didn't find any kind of error message . But my website can't load css file . In the settings , debug is True . But I didn't find any error . Please help me to find out the error. base.html <!DOCTYPE html> {% load static %} <html lang="en"> <head> <link href="{% static 'vendor/bootstrap/css/bootstrap.min.css' %}" rel="stylesheet"> <link rel="stylesheet" href="{% static 'assets/css/fontawesome.css' %}"> <link rel="stylesheet" href="{% static 'assets/css/tooplate-main.css' %}"> <link rel="stylesheet" href="{% static 'assets/css/owl.css' %}"> </head> <body> <!-- Navigation --> <nav class="navbar navbar-expand-lg navbar-dark bg-dark static-top"> <div class="container"> <a class="navbar-brand" href="#"><img src="{% static 'assets/images/header-logo.png' %}" alt=""></a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarResponsive"> <ul class="navbar-nav ml-auto"> <li class="nav-item active"> <a class="nav-link" href="index.html">Home <span class="sr-only">(current)</span> </a> </li> <li class="nav-item"> <a class="nav-link" href="products.html">Products</a> </li> <li class="nav-item"> <a class="nav-link" href="about.html">About Us</a> </li> <li class="nav-item"> <a class="nav-link" href="contact.html">Contact Us</a> </li> </ul> </div> </div> </nav> {% block content %} {% endblock %} <script src="{% static 'vendor/jquery/jquery.min.js' %}"></script> <script src="{% static 'vendor/bootstrap/js/bootstrap.bundle.min.js' %}"></script> <script src="{% static 'assets/js/custom.js' %}"></script> <script src="{% static 'assets/js/owl.js' %}"></script> </body> </html> home.html {% extends 'base.html' %} {% load static %} {% block content %} {% endblock %} Thanks in advance -
Django Favicon issue
what ever i try to do i can't get the favicon to show up, when i look it up in the view source tab it loads up but won't appear in the tab icon position. i'm importing it in the html like so: {% load static %} <link rel="stylesheet" href="{% static "css/index.css" %}"/> <link rel="Favicon" type="image/png" href="{% static 'images/icon.png' %}"/> i set the django staticfile_dirs like so: STATICFILES_DIRS = [ os.path.join('static'), os.path.join('static/images'), ] -
apache - How can I load django app on apache startup before first request?
I've got two Django apps running under Apache using mod_wsgi. I'm trying to make the apps load on apache startup before the first request but it's not working. I already tried adding WSGIImportScript and specifying application-group process-group with WSGIScriptAlias but it didn't work. Config: <VirtualHost *:80> ServerAdmin webmaster@localhost DocumentRoot /var/www/html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /prod/static /home/aeke/chatk_prod/CBW/static <Directory /home/aeke/chatk_prod/CBW/static> Require all granted </Directory> <Directory /home/aeke/chatk_prod/CBW/CBW> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess prod python-path=/home/aeke/chatk_prod/CBW python-home=/home/aeke/chatk_prod/CBW/venv WSGIScriptAlias /prod /home/aeke/chatk_prod/CBW/CBW/wsgi.py process-group=prod application-group=%{GLOBAL} Alias /test/static /home/aeke/chatk/CBW/static <Directory /home/aeke/chatk/CBW/static> Require all granted </Directory> <Directory /home/aeke/chatk/CBW/CBW> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess test python-path=/home/aeke/chatk/CBW python-home=/home/aeke/chatk/CBW/venv WSGIScriptAlias /test /home/aeke/chatk/CBW/CBW/wsgi.py process-group=test application-group=%{GLOBAL} </VirtualHost> Any idea what I'm missing? -
Unable to install mysqlclient on Ubuntu 20.04 Linux SSH server for Django
I have been trying to host my django website using the Ubuntu 20.04 VPS hosting provided by DigitalOcean. I am almost done setting up, but I am having issues doing pip install mysqlclient==2.0.3 I am running this command in my virtual environment I am getting the following error What is the solution for this? Collecting mysqlclient==2.0.3 Using cached mysqlclient-2.0.3.tar.gz (88 kB) ERROR: Command errored out with exit status 1: command: /root/medovation_inc/medinc/bin/python3 -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-d0e9ntdv/mysqlclient/setup.py'"'"'; __file__='"'"'/tmp/pip-install-d0e9ntdv/mysqlclient/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /tmp/pip-install-d0e9ntdv/mysqlclient/pip-egg-info cwd: /tmp/pip-install-d0e9ntdv/mysqlclient/ Complete output (15 lines): /bin/sh: 1: mysql_config: not found /bin/sh: 1: mariadb_config: not found /bin/sh: 1: mysql_config: not found Traceback (most recent call last): File "<string>", line 1, in <module> File "/tmp/pip-install-d0e9ntdv/mysqlclient/setup.py", line 15, in <module> metadata, options = get_config() File "/tmp/pip-install-d0e9ntdv/mysqlclient/setup_posix.py", line 70, in get_config libs = mysql_config("libs") File "/tmp/pip-install-d0e9ntdv/mysqlclient/setup_posix.py", line 31, in mysql_config raise OSError("{} not found".format(_mysql_config_path)) OSError: mysql_config not found mysql_config --version mariadb_config --version mysql_config --libs ---------------------------------------- ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. I also tried running sudo apt-get install libssl-dev outside of my virtual environment, but this also didnt solve the issue. -
How to extend the Django's static template tag
Django's built in {% static %} tag automatically prepends the path to my s3 static assets . I however need to alter the path with more information before retrieving the files. Is it possible to extend the built in 'static' template tag to do this.? I am aware that I can create my own template tag and simply replace the static tag however I am working with a large code base and doing this would be very time consuming. -
Save data to two different tables from form.Form Django
Hello I want to know if i do it wrong, but i want to save data from a django form in different tables. I do this but i'm no sure what i'm doing wrong. I don´t wnat to use model.Forms because i ned to save the form data in two different tables of mi db. My model is this: from django.db import models class Usuarios_p(models.Model): nombre_s = models.CharField(max_length=100, blank=True, null=False) apellido_p = models.CharField(max_length=100, blank=True, null=False) apellido_m = models.CharField(max_length=100, blank=True, null=False) correo = models.EmailField(max_length=100, blank=True, null=False) cel = models.CharField(max_length=10, blank=True, null=False) calle_d = models.CharField(max_length=100, blank=True, null=False) num_ext_d = models.CharField(max_length=10, blank=True, null=False) num_int_d = models.CharField(max_length=10, blank=True, null=True) colonia_d = models.CharField(max_length=100, blank=True, null=False) alcaldia_d = models.CharField(max_length=100, blank=True, null=False) estado_d = models.CharField(max_length=100, blank=True, null=False) cp_d = models.CharField(max_length=5, blank=True, null=False) calle_f = models.CharField(max_length=100, blank=True, null=False) num_ext_f = models.CharField(max_length=10, blank=True, null=False) num_int_f = models.CharField(max_length=10, blank=True, null=False) colonia_f = models.CharField(max_length=100, blank=True, null=False) alcaldia_f = models.CharField(max_length=100, blank=True, null=False) estado_f = models.CharField(max_length=100, blank=True, null=False) cp_f = models.CharField(max_length=5, blank=True, null=False) nacionalidad = models.CharField(max_length=50, blank=True, null=False) pais_nacimiento = models.CharField(max_length=100, blank=True, null=False) estado_nacimiento = models.CharField(max_length=100, blank=True, null=False) fecha_nacimiento = models.DateField(blank=True, null=False) genero = models.CharField(max_length=15, blank=True, null=False) rfc = models.CharField(max_length=13, blank=True, null=False) curp = models.CharField(max_length=15, blank=True, null=False) ocupacion = models.CharField(max_length=100, blank=True, null=False) estado_civil … -
how to resolve relation "django_session" does not exist error in django app with firebase backend and deployed on heroku
I developed Django app using firebase for authentication and as a database for the app, locally I have no problem but when deployed to Heroku each time I try to login or create a new account in the app I get this error. '''relation "django_session" does not exist LINE 1: SELECT (1) AS "a" FROM "django_session" WHERE "django_sessio...''' but I have no models since am using firebase, how do i resolve this..... this is my code below settings.py ''' import os import django_heroku import dj_database_url from decouple import config from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = 'your secret key' DEBUG = False ALLOWED_HOSTS =[] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'payments.apps.PaymentsConfig', ] 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', 'whitenoise.middleware.WhiteNoiseMiddleware', ] ROOT_URLCONF = 'snailPortal.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['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 = 'snailPortal.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', #'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 'NAME': BASE_DIR / 'db.sqlite3', } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N … -
how to use m2msignal such that no of inline extra is equal to the no of options selected from many to many field django
I have 2 models in django : Offer model- class Offer(models.Model): Offer_Name=models.CharField(max_length=200,blank=False,verbose_name = "Auction Name") Vendor=models.ManyToManyField(User,limit_choices_to={'is_vendor': True},help_text = "Please select vendor valid for this offer",) Bid model: class Bid(models.Model): offer=models.ForeignKey(Offer,on_delete=models.CASCADE) Bid=models.IntegerField(blank=False,null=False,verbose_name = "Inital Bid Amount") Both these models are linked in django through nested stackedinline admin: class BidInline(nested_admin.NestedStackedInline): model = Bid extra=0 #max_num=vendorcount(Offer.Vendor.through) exclude = ('ven_id','new_bid','rank') class OfferAdmin(nested_admin.NestedModelAdmin): form =select2_modelform(Offer) inlines = [ BidInline, ] I tried using m2m signal to get the no of options selected in Vendor many to many fields and enter it to max_num field in Bidinline so that no of options selected in vendor= no of extra bid form. Here is my signal : @receiver(m2m_changed, sender=Offer.Vendor.through) def vendorcount(sender, **kwargs): instance = kwargs.pop('instance', None) pk_set = kwargs.pop('pk_set', None) action = kwargs.pop('action', None) if action == "pre_add": for i in pk_set: instance.save() print(len(pk_set)) return len(pk_set) Through this signal i got the length but after i click the save button. How can i get it the moment i selected options in many to many field so that max_num can be updated? Please help. -
Django Search near by shop based on zip code
I am trying to build a location based app. I have added model like this one reproducible. class Teacher(models.Model): city = models.CharField() postalcode = models.CharField() I will save all the teach location with their postal code. and when i search by zip code, it will search all the teacher of certain radius of the zip? How can i do it? is it possible with django? by the way, i am using postgresql Can anyone suggest me the best thing? -
Django Cassandra Engine connect to multiple DB configuration
I am using django cassandra engine to connect django app to cassandra. How to connect to different cassandra configurations in API views when querying cassandra models. DB router is not working with cassandra. My settings.py file contains multiple configurations as follows: 'db1': { 'ENGINE': 'django_cassandra_engine', 'NAME': 'keyspace1', 'HOST': 'host1', 'PORT': port1, 'OPTIONS': { 'replication': { 'strategy_class': 'SimpleStrategy', 'replication_factor': 'factor1' } } } 'db2': { 'ENGINE': 'django_cassandra_engine', 'NAME': 'keyspace2', 'HOST': 'host2', 'PORT': port2, 'OPTIONS': { 'replication': { 'strategy_class': 'SimpleStrategy', 'replication_factor': 'factor2' } } } } ...and so on``` -
Displaying POST request data in Django View (Celery, Redis)
I'm creating a simple Django site with the following operation: Third party site sends POST request to my Django site Site receives POST request on e.g. http://mysite/post_message_in/ Site displays basic POST message details in an authenticated view e.g. http://mysite/dashboard/. A large scrollable text area is fine. Processes POST message contents asynchronously using Celery worker. Displays status of Celery worker during POST message processing in same scrollable text area as point 3 without manual page refresh required. Clears scrollable text area and repeats steps 2-5 when new POST request received - infrequent. I understand that I can use javascript to poll the status of the Celery task to update the contents of the dashboard view, but only if the javascript knows the celeray task.id. I am trying to understand how I pass the celery task.id between different views and javascript in order to achieve the operation described above? So far I have a fully functioning django site with authenticated dashboard, and test async tasks running on Celery with a Redis broker. I need help figuring out the rest. Any insight much appreciated. Thanks. -
Static files - Django Azure
I am hosting a website on Microsoft Azure. I have updated all the configurations within Azure and my settings.py file looks as below - DEFAULT_FILE_STORAGE = 'storages.backends.azure_storage.AzureStorage' STATICFILES_STORAGE = 'custom_storage.custom_azure.AzureStaticStorage' AZURE_ACCOUNT_NAME = os.environ.get('AZURE_ACCOUNT_NAME') AZURE_STORAGE_KEY = os.environ.get('AZURE_STORAGE_KEY', False) AZURE_MEDIA_CONTAINER = os.environ.get('AZURE_MEDIA_CONTAINER', 'media') AZURE_STATIC_CONTAINER = os.environ.get('AZURE_STATIC_CONTAINER', 'static') AZURE_CUSTOM_DOMAIN = f'{AZURE_ACCOUNT_NAME}.blob.core.windows.net/' STATIC_URL = f'https://{AZURE_CUSTOM_DOMAIN}/{AZURE_STATIC_CONTAINER}/' MEDIA_URL = f'https://{AZURE_CUSTOM_DOMAIN}/{AZURE_MEDIA_CONTAINER}/' STATIC_ROOT = f'https://{AZURE_CUSTOM_DOMAIN}/{AZURE_STATIC_CONTAINER}/' I have a custom_storage folder with a custom_azure.py file with following - from django.conf import settings from storages.backends.azure_storage import AzureStorage class AzureMediaStorage(AzureStorage): account_name = settings.AZURE_ACCOUNT_NAME # Must be replaced by your <storage_account_name> account_key = settings.AZURE_STORAGE_KEY # Must be replaced by your <storage_account_key> azure_container = settings.AZURE_MEDIA_CONTAINER expiration_secs = None class AzureStaticStorage(AzureStorage): account_name = settings.AZURE_ACCOUNT_NAME account_key = settings.AZURE_STORAGE_KEY azure_container = settings.AZURE_STATIC_CONTAINER expiration_secs = None However I am now pulling a static admin file and not the static project file containing css, scss and js files.. -
Django: get a specific instance from reverse many to many
As get doesn't seem to be supported for reverse many to many, is there a more elegant way to getting a specific instance of the through class than what I am doing now? I have something like this: class Game (models.Model): players = models.ManyToManyField(User, through='Player') And to get a specific player from the user id, I'm using the following: game.player_set.filter(id=1)[0] This seems really stupid, but I can't seem to find a better way. I would think something like the following exists (without getting the first item of a queryset that will always contain just 1 item): game.player_set.get(id=1) (In other words, just like you do with a one-to-one relationship.) -
Django / Heroku ModuleNotFoundError: No module named 'MyProject.apps'
I've got a django app that works fine when I run it locally with "python manage.py runserver". However, Heroku is struggling to get the site up and running. I commit changes to git, which triggers an automatic build on Heroku. The build succeeds, but then fails when trying to start the process with the gunicorn command. I've pasted the full Heroku log below, but the relevant bit seems to be "ModuleNotFoundError: No module named 'FromThePath.apps'", which seems to be referring to the INSTALLED_APPS in settings.py. I've tried changing the INSTALLED_APPS to be prefixed with an extra "FromThePath." (which is what resolved an error in wsgi.py), but that causes a failure during build at the collectstatic command with "ModuleNotFoundError: No module named 'FromThePath.FromThePath'" Not sure where to go from here. My Google-fu is clearly inadequate. Thanks in advance for your help! Full heroku log: 2021-03-09T17:01:30.000000+00:00 app[api]: Build succeeded 2021-03-09T17:01:40.327614+00:00 heroku[web.1]: Starting process with command `gunicorn FromThePath.FromThePath.wsgi` 2021-03-09T17:01:44.495636+00:00 app[web.1]: [2021-03-09 17:01:44 +0000] [4] [INFO] Starting gunicorn 20.0.4 2021-03-09T17:01:44.497096+00:00 app[web.1]: [2021-03-09 17:01:44 +0000] [4] [INFO] Listening at: http://0.0.0.0:49607 (4) 2021-03-09T17:01:44.497258+00:00 app[web.1]: [2021-03-09 17:01:44 +0000] [4] [INFO] Using worker: sync 2021-03-09T17:01:44.510099+00:00 app[web.1]: [2021-03-09 17:01:44 +0000] [9] [INFO] Booting worker with pid: 9 2021-03-09T17:01:44.547692+00:00 app[web.1]: … -
Django choice from db
I'm newbie with django and I'm trying to make a MultipleChoiceField that recive some choices from a model. # function that get n querysets and allow to put as option def gen_choices(null_option=False, *querysets): out = [] if null_option: out = out + [(None, '---------')] for queryset in querysets: for element in queryset: out = out + [(element.__str__(), element.__str__())] print(out) return out # FORM class MyFormHere(forms.ModelForm): # CHOICES MY_CHOICE = gen_choices(True, Model1.objects.all(), Model2.objects.all()) Can I do this better and safer? I don't if this is the best way to do what i want to do. -
ProgrammingError: function lower(bigint) does not exist (Django, AWS RDS, PostgreSQL)
In my Django Rest Framework project, I have a custom filter_backends that allows filtering by case insensitively: class CaseInsensitiveOrderingFilter(OrderingFilter): def filter_queryset(self, request, queryset, view): ordering = self.get_ordering(request, queryset, view) if ordering: new_ordering = [] for field in ordering: # field = str(field) print(Lower(field)) if field.startswith('-'): new_ordering.append(Lower(field[1:]).desc()) else: new_ordering.append(Lower(field).asc()) return queryset.order_by(*new_ordering) return queryset This works fine in development. Now I hosted the django app on elastic beanstalk and I configured a postgresql database via amazon relational database service (RDS). When I try now to call the API, I get this error: ProgrammingError at /api/profile_list/ function lower(bigint) does not exist LINE 1: ..."."author_id") GROUP BY "user_user"."id" ORDER BY LOWER(COUN... HINT: No function matches the given name and argument types. You might need to add explicit type casts. This error appears only in the RDS deployment. I tried to type cast the fields in django with: field = str(field) But this is not working. Is there any way to allow caseinsensitive ordering without the lower function, or how can I conditionally check if it is a number (and cast then?) or a text abd -
django filter data (coordinates of canvas) and combine to form a new data coordinate
I have a canvas which lets user lets draw on it and save it (it saves the coordinates in the database as points and lines) , and the user can retrieve the drawing they saved. My model class Drawing(models.Model): drawingJSONText = models.TextField(null=True)# coordinates saved project = models.CharField(max_length=250) My sample data - drawingJSONText field {"points":[{"x":109,"y":286,"r":1,"color":"black"},{"x":108,"y":285,"r":1,"color":"black"},{"x":106,"y":282,"r":1,"color":"black"},{"x":103,"y":276,"r":1,"color":"black"},],"lines":[{"x1":109,"y1":286,"x2":108,"y2":285,"strokeWidth":"2","strokeColor":"black"},{"x1":108,"y1":285,"x2":106,"y2":282,"strokeWidth":"2","strokeColor":"black"},{"x1":106,"y1":282,"x2":103,"y2":276,"strokeWidth":"2","strokeColor":"black"}]} I am able to retrieve the drawing , but i am trying to filter the data based on project field and i need to add all coordinates of the queryset and plot it onto canvas def load(request): """ Function to load the drawing with drawingID if it exists.""" try: #drawingJSONData1 = json.loads(Drawing.objects.get(id=1).drawingJSONText) #drawingJSONData2 = json.loads(Drawing.objects.get(id=3).drawingJSONText) #drawingJSONData = dict() #drawingJSONData["points"] = drawingJSONData1["points"] + drawingJSONData1["points"] #drawingJSONData["lines"] = drawingJSONData1["lines"] + drawingJSONData2["lines"] #drawingJSONData = json.dumps(drawingJSONData) #drawingJSONData = Drawing.objects.get(id=3).drawingJSONText filterdata = Drawing.objects.filter(project=1) drawingJSONData = filterdata.drawingJSONText # Sending context with appropriate information context = { "loadIntoJavascript": True, "JSONData": drawingJSONData } # Editing response headers and returning the same response = modifiedResponseHeaders(render(request, 'MainCanvas/index.html', context)) return response -
How to integrate a python file onto a Django project?
I am trying to include a machine learning component in my Django project. I have the method written in python. How do I get to make it work on the website using Django. Can I simply drag the ".py" file into the file structure and call it from an HTML page? I am new to Django any help would be greatly appreciated. -
ValueError at /jobs/approve/1 Cannot query "client1": Must be "Application" instance
Models: class Application(models.Model): job = models.ForeignKey(Job, related_name='applications', on_delete=models.CASCADE) scope_of_work = models.TextField(max_length=250, null=True, blank=False) fee = models.CharField(max_length=250, null=True, blank=False) examples = models.ImageField(default='examples.jpg', upload_to='profile_pics', blank=True) external_link = models.URLField(null=True, blank=True) created_by = models.ForeignKey(User, related_name='applications', on_delete=models.CASCADE) created_at = models.DateField(auto_now_add=True) def __str__(self): return str(self.created_by) class ApproveJob(models.Model): PENDING = 'pending' ACTIVE = 'approve' CHOICES_STATUS = ( (PENDING, 'Pending'), (ACTIVE, 'Approve'), ) approve = models.ForeignKey(Application, related_name='approved_job'on_delete=models.CASCADE) status = models.CharField(max_length=20, choices=CHOICES_STATUS, default=PENDING) def __str__(self): return self.approve Views: def approve_job(request, application_id): approve = get_object_or_404(ApproveJob, pk=application_id, approve=request.user) if request.method == 'POST': form = ApproveForm(request.POST, instance=approve) if form.is_valid(): approve = form.save(commit=False) approve.status = request.POST.get('status') approve.save() return redirect('dashboard') else: form = ApproveForm(instance=approve) return render(request, 'job/approve_job.html',{'form':form, 'approve':approve}) -
Reverse django custom admin site URL
I'm trying to get reverse for my custom admin which is using proxy model, but I cann't find out how to reverse to sub page. In my panel admin, model Advertisement has few pages and I want to reverse to one of them. I've already tried: reverse("admin:app_list", args['advertisement', 'deactivatedadvertisements']) class DeactivatedAdvertisements(Advertisement): class Meta: proxy = True class DeactivatedAdvertisementsAdmin(admin.ModelAdmin): """Panel for listing deactivated advertisements allowing to activate them.""" ordering = ["-deactivated_at"] list_display = [ "advertisement_title", "user", "root_category", "activate", "deactivated_at", ] I want to get url admin/advertisement/deactivatedadvertisement/ How can I reach it?