Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
LookupError: No installed app with label 'admin'/ File "/code/bookstore/urls.py", line 21, in <module>
I'm reading "Django for professionals" and practicing it. I was shown to make "docker-compose down" and up it again and I did. But after this nothing is working. It's complaining to root urls.py file where its importing admin file -
How to update Gunicorn with new datbase settings?
I'm trying to set up a website using EC2 and Django/Nginx/Gunicorn but I'm getting the following error: FATAL: database "db-name" does not exist The issue is that the database that I currently have configured is a different name "testdb", and the files in the EC2 instance are already pointing towards the different database, yet Gunicorn seems to keep trying to look for the wrong database name. I've tried restarting Gunicorn with sudo systemctl restart gunicorn and sudo systemctl daemon-reload but it still tries to look for "db-name" instead of "testdb". My wsgi.py and settings files should be correct so I don't think those are the issue. So how can I get Gunicorn to look for the right database? gunicorn.service [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=ubuntu Group=www-data WorkingDirectory=/opt/code/shop ExecStart=/opt/code/shop/venv/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ core.wsgi:application Restart=always RestartSec=3 wsgi.py os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core.settings') application = get_wsgi_application() core/settings.py DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql_psycopg2", "NAME": "testdb", "USER": env("DB_USER"), "PASSWORD": env("DB_PASSWORD"), "HOST": env("DB_HOST"), "PORT": env("DB_PORT"), } } -
How can I get Django Rest Framework to work with Django Tenants and React?
Here is my setup: settings.py SHARED_APPS = ( 'django_tenants', 'main', other apps... ) TENANT_APPS = ( 'rest_framework', 'company', ) MIDDLEWARE = [ 'django_tenants.middleware.main.TenantMainMiddleware', other middleware... ] DATABASE_ROUTERS = ( 'django_tenants.routers.TenantSyncRouter', ) urls.py from django.urls import include, path from rest_framework import routers # other imports from main.api.v1 import projects router = routers.DefaultRouter() router.register(r'api/v1/project', projects.ProjectViewSet) urlpatterns = [ -- other paths -- path('', include(router.urls)), ] api/v1/project.py # other imports from company.models import Project from rest_framework import serializers from rest_framework import viewsets from rest_framework import permissions class ProjectSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Project fields = ['url', 'name', 'keycode'] class ProjectViewSet(viewsets.ModelViewSet): queryset = Project.objects.all().order_by('id') serializer_class = ProjectSerializer permission_classes = [permissions.AllowAny] main.models.py from django.contrib.auth.models import User as AuthUser from django_tenants.models import TenantMixin, DomainMixin # note, definition of custom "User" model which has an AuthUser 1 to 1 relationship class Company(TenantMixin): name = models.CharField(max_length=100) subdomain = models.CharField(max_length=32) employees = models.ManyToManyField(User, related_name='companies') migration_id = models.IntegerField(null=True) class Domain(DomainMixin): pass company.models.py from django.db import models class Project(models.Model): name = models.CharField(max_length=100) keycode = models.CharField(max_length=8) And the final detail is that I am not using a Django frontend but rather one created in React. The request which is going to the backend is just a standard request however it is coming … -
Can't access variable from with a function
I have this script to create google maps with markers template inside my Django project: <script> function initMap() { const shop = { lat: 45.0203018, lng: -88.318316 }; const map = new google.maps.Map( document.getElementById("map"), { zoom: 10, center: shop, }); const vehicles = {{ vehicles|safe }}; for(i = 0; i < vehicles.length; i++){ const pos = new google.maps.LatLng(vehicles[i]['lat'],vehicles[i]['lon']); const marker = new google.maps.Marker({ position: pos, map: map, label: vehicles[i]['number'], }); const id = vehicles[i]['truck'] marker.addListener("click", () => { window.location = "{% url 'invent:truck' id %}"; }); }; }; window.initMap = initMap; </script> But it doesn't see variable id inside the addListener function. And if I put the variable inside the function it doesn't see the vehicles variable. What am I doing wrong? -
How to setup front end and back end on one server and on one port number?
The frontend and backend of the site are on the same server, on different ports: frontend in on 443, and the backend on 8443. A request is sent from the frontend to create a file from the backend (in the form of GET-requests). These requests go regularly until the file is created. But for some people, these requests are not returned. The following error appears in the console: Гипотеза заключается в том, что возможно файервол не разрешает отправлять запросы на порт 8443. Trying to just enter the web address with this port number (https://app.website.com:8443/) to the browser by these people should return the standard Django screen, but returns: Here is how the servers are configured. I additionally, just in case, made sure that any cache was deleted. This is the front end server setup: server { listen 80; server_name website.com; return 301 https://website.com; } server { listen 443 ssl default_server; listen [::]:443 ssl default_server; ssl_certificate /etc/ssl/app.website.com_ssl_certificate.cer; ssl_certificate_key /etc/ssl/app.website.com_private_key.key; root /home/website/dist; index index.html index.htm index.nginx-debian.html; server_name app.website.com; index index.html; location / { try_files $uri $uri/ /index.html; # kill cache add_header Last-Modified $date_gmt; add_header Cache-Control 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0'; if_modified_since off; expires off; etag off; } } This is backend server … -
django channels - possible for "write-only" channel group?
Hopefully this is gonna make sense. I am building an app using django-channels that works a little bit like a quiz - there is a host, and multiple players. When something goes wrong in the player side of the house I want the specific player consumer to send a message to the host group - which is easy enough. Unfortunately, because all player consumers need to be attached to the host group to send messages, they also receive those and send them to their connected clients. Thus if an issue occurs with player 1's consumer, it ultimately gets broadcast to player 2, player 3, etc, when all I want to do is alert the host. I've thought about doing this with a 'no-handle' flag in such messages, but is there a cleaner method of doing what I want? -
Django sign up first name not valid
I'm 100% sure this thing worked before but now every time I try to sign up Django says "First name not valid.". This happens during the form.is_valid() check, everything about the sign up view is Django default so I did not implement anything on my own. The only constraint on first_name in the DB is that it must not be NULL or greater than 150 characters. This is the function in myapp.views: def register(request): if request.user.is_authenticated: return redirect('/') if request.method != 'POST': form = RegisterForm() else: form = RegisterForm(request.POST) if form.is_valid(): form.save() return redirect('login') This is the form: -
I would like to embed a pdf, which i get from a api, in an iframe
The pdf is created in the backend of my React/Django application and i would like to display it in the frontend. Is there a way to prevent this error? Can i allow the application to open stuff from diffrent sources? Here's the code for the frontend: const PDFViewer = () => { return ( <div> <Navbar /> <Login /> <div id="PDF"> <iframe src="/api/pdf"/> </div> </div> ); } -
Is it possible to reorder django fields with rest api (getting the new order with requests)?
I have a Django model like this (hypothetical): class Person(models.Model): name = models.CharField() last_name = models.CharField() age = models.IntegerField() I access this with an API call so I get the json {name: "John", last_name: "Doe", age: 20} and show this as an ordered list like this John Doe 20 I want to reorder this list by dragging the elements (that's easy with this) but once saved and reloaded the data returns to original order because the order isn't saved. Is there a way to achieve this? The best I can think of is getting a new field fields_order that keeps the fields names with the specified order but I think that should be a better approach. -
How to fix TypeError('Object of type ExternalUnifiedEvent is not JSON serializable)?
I am retrieving a list of objects from an external API that I need to send as the payload to a webhook using post request in python. The structure of the data returned from get_data() looks like this [{"eventId": 1, "eventType": "test", "properties": { "property1": "value1", "property2": "value2", "property3": "value3", }}, {"eventId": 2, "eventType": "test", "properties": { "property1": "value1", "property2": "value2", "property3": "value3", }}, {"eventId": 3, "eventType": "test", "properties": { "property1": "value1", "property2": "value2", "property3": "value3", }}] headers = {"Content-Type": "application/json",} payload = get_data() response = requests.post(webhook_url, headers=headers, data=json.dumps(payload)) it raises a TypeError('Object of type ExternalUnifiedEvent is not JSON serializable); if i remove the json.dumps() and just pass in the payload as the data, I'm getting TypeError('cannot unpack non-iterable ExternalUnifiedEvent object') -
SQLAlchemy Postgresql database django
I am new to Django and have a question in regards to whether or not I have to re-enter data or can use existing data from a postgres database and apologize if this has been asked before. I have a Postgres database in which I created with SQLAlchemy ORM. I use this database for data analysis and want to create a web app for the data presentation. I know that Django has its own modeling system and ORM, do I have to recreate the database from scratch since I created this with SQLAlchemy's ORM? Thank you in advance. -
django-redis persisting json data
I have a small django site which controls an anstronomy dome and house automation. On start up the project loads 3 json files: relays, conditions and homeautomation. To avoid constant reading and writing to the Pi4's ssd I load the json files into REDIS (on start up in apps, see below). I already have REDIS running in a docker as the project uses celery. My problem is that within a few minutes of loading the json into REDIS it clears the data out of cache. I load the json file in the form of a dictionary (dict) in apps cache.set("REDIS_ashtreeautomation_dict", dict, timeout=None) and set CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://redis:6379", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", "SERIALIZER": "django_redis.serializers.json.JSONSerializer", "TIMEOUT": None } } } I don't need the data to persist if the dockers go down and I don't need db functions. Caching these files is ideal but I need them to 'stay alive' for the lifetime of the server. Thank you. -
using serializer methodfield to access FK informations
I use DRF writable nested serializer to create multiple object at once : class NestedDocumentLocationSerializer(WritableNestedModelSerializer): # organisme_name = serializers.SerializerMethodField(source='organisme.nom') nda = DocumentSerializer(allow_null=True, required=False) kbis = DocumentSerializer(allow_null=True, required=False) qualiopi = DocumentSerializer(allow_null=True, required=False) rib = DocumentSerializer(allow_null=True, required=False) contrat = DocumentSerializer(allow_null=True, required=False) class Meta: model = DocumentLocation fields = ['location', 'nda', 'kbis', 'qualiopi', 'rib', 'contrat'] # extra_kwargs = { # 'organisme_name': {'read_only': True} # } # def get_organisme_name(self, obj): # return obj.location.organisme.nom The creation part works perfectly But when it comes to my Location, only the ID is showing : { "location": 2, "nda": { "id": 136, "nom": "ça fonctionne ?", "description": "ça fonctionne ?", "chemin": "ça fonctionne ?", "stockage_interne": false }, "kbis": { "id": 137, "nom": "ça fonctionne ?", "description": "ça fonctionne ?", "chemin": "ça fonctionne ?", "stockage_interne": false }, "qualiopi": { "id": 138, "nom": "ça fonctionne ?", "description": "ça fonctionne ?", "chemin": "ça fonctionne ?", "stockage_interne": false }, "rib": { "id": 139, "nom": "ça fonctionne ?", "description": "ça fonctionne ?", "chemin": "ça fonctionne ?", "stockage_interne": false }, "contrat": { "id": 140, "nom": "ça fonctionne ?", "description": "ça fonctionne ?", "chemin": "ça fonctionne ?", "stockage_interne": false } } So i wanted to use SerializerMethodfield to get the informations i want, my organisme … -
POST request forbidden
I am using django-rest-framework. I have a few APIs which I use to GET data. When I am testing a new API to post information, I am getting a 403 forbidden while making the request as vanilla xhr object, as well as using jQuery. The same API is working properly from Postman and django-rest-framework API interface as well. What can be the reason for this? -
Delete and edit comment django
i been trying multiple ways to add a edit/delete function to my django comment section but cant seem to figure it out anyone can help me how to code this or give me some tips? I been trying for some time and searching alot but cant figure it out. Been looking at documentation and other stackoverflow posts and youtube videos but cant figure it out. product_detail.html {% extends "base.html" %} {% load static %} {% block page_header %} <div class="container header-container"> <div class="row"> <div class="col"></div> </div> </div> {% endblock %} {% block content %} <div class="overlay"></div> <div class="container-fluid"> <div class="row"> <div class="col-12 col-md-6 col-lg-4 offset-lg-2"> <div class="image-container my-5"> {% if product.image %} <a href="{{ product.image.url }}" target="_blank"> <img class="card-img-top img-fluid" src="{{ product.image.url }}" alt="{{ product.name }}"> </a> {% else %} <a href=""> <img class="card-img-top img-fluid" src="{{ MEDIA_URL }}noimage.png" alt="{{ product.name }}"> </a> {% endif %} </div> </div> <div class="col-12 col-md-6 col-lg-4"> <div class="product-details-container mb-5 mt-md-5"> <p class="mb-0">{{ product.name }}</p> <p class="lead mb-0 text-left font-weight-bold">${{ product.price }}</p> {% if product.category %} <p class="small mt-1 mb-0"> <a class="text-muted" href="{% url 'products' %}?category={{ product.category.name }}"> <i class="fas fa-tag mr-1"></i>{{ product.category.friendly_name }} </a> </p> {% endif %} {% if product.get_rating > 0 %} <small … -
getting DisallowedHost at / error on python anywhere
I am trying to deply my blog application to python anywhere. I added 'codewizblog.pythonanywhere.com' to ALLOWED_HOSTS in my settings file but I keep getting the disallowed host error. Any help would be much appreciated. -
Google OAuth2.0 error while authenticating, while being deployed on heroku
I have created an application which accesses sheets api using django. I am successfully able to authenticate using OAuth2.0, locally. But when I deployed my django code onto heroku, i am unable to authenticate. I am getting this can’t establish a connection to the server at localhost:8080. -
How to create an endpoint (GET) with disabled authentication where I just want to visualize the data in map?
May be an basic question about a creation of a new endpoint in DRF. I'm newbie in DRF and got stuck in a creation of an new endpoint that unauthenticated users could just GET the data, visualize. My django project is organized in three apps: core, user, and markers. The "user" app performing POST, GET, PUT, PATCH, and POST. The app "markers" enable the user to create (POST) geolocations and other information associated to the coordinates (name, coordinates, images...). My challenge now is to create a new endpoint where anonymous user/unauthenticated could visualize the data (in a map), created by the users data. I've created the map, inside markers folder and didn't have success in data visualization because of the authentication. Any clue or example how to enable the visualization? Thanks github repo [https://github.com/silveiratcl/sun_coral_report_app][1] user model models.py: class UserManager(BaseUserManager): def create_user(self, email, password=None, **extra_fields): """Creates and saves a new User""" if not email: raise ValueError('User must have an email address') user = self.model(email=self.normalize_email(email), **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password): """Creates and saves a new super user""" user = self.create_user(email, password) user.is_staff = True user.is_superuser = True user.save(using=self._db) return user marker model models.py: class Marker(models.Model): """A marker object.""" … -
django model date form validation
hello I am a newbie django user and I created a model form I am using 2 fields one is a DateField and another is a TimeField since separating them instead of using DateTimeField seemed better for my particular model, and I want to make sure that the user can't select a date in the past and a they can only select a time between 10am-11pm, to be more specific this is a restaurant reservation model, I found similar questions when I was looking for a solution on google but I couldn't understand them and apply them to my project, my model - https://gyazo.com/7947589283f52925d85608957cc6a7e4 my view - https://gyazo.com/1b0f6cd1b8af52960c7f197476bdd5b3 my form.py - https://gyazo.com/78e8617e1a6332fc53b91900aa46e017 as I said I found similar questions, on stackoverflow and links to django documentation but I couldn't apply them to my project, so any help would be appreciated -
Struggling with reoccuring checklist functionality (Django)
Here's my current setup, simplified class projects(models.Model): fk_user = models.ForeignKey(User, default='1', on_delete=models.CASCADE) title = models.CharField(max_length=150) class projects_checklistItems(models.Model): fk_project = models.ForeignKey(projects, on_delete=models.CASCADE) b_task1 = models.BooleanField(defaut=False) b_task2 = models.BooleanField(defaut=False) b_task3 = models.BooleanField(defaut=False) The problem is, I want users to be able to add their own checklist items to each project, as they will have their own dependencies and conditions. As a result, I could do this instead: class projects(models.Model): fk_user = models.ForeignKey(User, default='1', on_delete=models.CASCADE) title = models.CharField(max_length=150) fkj_checklistItems = models.ManyToManyField(checklistItems, through="j_projects_checklistItems") class checklistItems(models.Model): name = models.CharField(max_length=150) class j_projects_checklistItems(models.Model): fk_project = models.ForeignKey(projects, on_delete=models.CASCADE) fk_checklistItem = models.CharField(checklistItems, on_delete=models.CASCADE) b_completed = models.BooleanField(default=False) However I want there to be a default / starting selection of checklist items (i.e. tasks) that are shared for each project. So once a project is created, it is automatically assigned a collection of 20, 30, maybe 50 checklist items" From there, the user can deselect those that are irrelevant and add new ones. Perhaps by ammending the junction model as such: class j_projects_checklistItems(models.Model): fk_project = models.ForeignKey(projects, on_delete=models.CASCADE) fk_checklistItem = models.CharField(checklistItems, on_delete=models.CASCADE) b_completed = models.BooleanField(default=False) * b_active = models.BooleanField(default=True) But I'm unsure how to set these default items that all projects should share. -
Mypy library and Django exclude app directories
I have several apps in my Django project, but I wanted to exclude directories or apps, how can this be done. Below is my mypy.ini file, but it doesn't work : [mypy] ignore_missing_imports = True exclude = customers As you can see above customers is one of my django apps (directory), what could be the best solution here? -
Condition on avg in a queryset in django
I have two models class A(models.Model): field1 = models.CharField(max_length=100) class B(models.Model): a_field = models.FoereignKey(A,on_delet=models.SET_NULL,related_name='bs') datetimefield = models.DateTimeField(auto_now_add=True) amountfield = models.FloatField() I want to count the number of elements of A per month where Avg(amountfield)=0 Here's how I did it but it doesn't work: B.objects.values('datetimefield__month').annotate(Count('a_field',filter=Q(amountfield__avg=0))) How can I solve this problem? Thanks in advance. -
return the values only if it exists in python
I want to return the values only if the particular row exist but I couldn't able to achieve it.Here, what I tried def CurrentRunning(UserId): cursor = connection.cursor() cursor.execute('EXEC [dbo].[sp_GetCurrentRunningActivity] @UserId=%s', (UserId,)) result_set = cursor.fetchall() data= [] data.append({ 'TaskId':row[0], 'Value1':row[1], 'Value2' :row[2], 'SelectedTeam':0 if row[3] is exists else row[3], 'Level1':'0' if row[4] is exists else row[4], 'Level2':'0' if row[5] is exists else row[5], 'Level3':'0' if row[6] is exists else row[6], 'Level4':'0' if row[7] is exists else row[7], 'TotalVolume':'0' if row[8] is exists else row[8], 'ReturnDate':'0' if row[9] is exists else row[9], }) print('Activity') return Response(data) -
DRF Nested serializer, creating object and select instance from a model on the same request
Here is my problem : i'm using the lib drf-writable-nested to create multiple object on the same request. This part is working perfectly: class DocumentLocationSerializer(WritableNestedModelSerializer): nda = DocumentSerializer(allow_null=True, required=False) kbis = DocumentSerializer(allow_null=True, required=False) qualiopi = DocumentSerializer(allow_null=True, required=False) rib = DocumentSerializer(allow_null=True, required=False) contrat = DocumentSerializer(allow_null=True, required=False) class Meta: model = DocumentLocation fields = '__all__' But with the same Serialier i would like to have the choice to select instance from another model created before, So i can create my documents and select the instance from a model. I tried to add this : location = LocationSerializer(allow_null=True, required=False, read_only=True) so i can select my location but with the readonly option set to True i can't even choose a location, and if i set it to False, i have to create a new location object. Thanks and sorry for my english. -
Passing data from bootstrap modal form to main form
I'm having a problem that I don't really know how to execute, I have this two forms one is on my parent page and shows the sales history of products and then have a form to input the quantity of products for the next months. Main page table Then I have a modal that follows the model of the main page but instead of individual products it tracks the quantity of products by product type. I want to pass the data that is in the modal form to the form fields in the parent page table input fields. Modal table (Note that both include roughtly the same fields product/product type name, quantities from past months up to last, then already paid this month, sold but not paid this month, avg from last 3 and 6 months, sum of paid+not paid this month, form of expeted quantities from this month until this month+6) But how do I do this? The in my context I have the list of products that I use to generate my parent page table with the form and the product type list that I use to generate the modal table. In the product list they have data …