Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get the profile picture of a user who is not logged in?
I made this user info page which is supposed to show the profile of the user you click on it is supposed to work even when the user is not logged in but I cannot get the username or profile picture of the user I chose I could only display the profile of the currently logged in user there what should I do?? if I need to post another page please let me know \ Thanks in advance prof.html {% extends "base.html" %} {% load static %} {% block content %} <div class="frame"> <div class="center"> <div class="profile"> <div class="image"> <div class="circle-1"></div> <div class="circle-2"></div> <div style="margin-left: -20px"> <img src="{{ user.profile.image.url }}" width="110" height="110"> </div> </div> <div style="margin-top: 30px"></div> <div class="name"> {{ user.username }} </div> <div class="job">Visual Artist</div> <div class="actions"> <button class="btn">Follow</button> <button class="btn">Message</button> </div> <div class="sociic"> <a href="{% url 'home' %}"><i class="fa fa-telegram"></i></a> <a href="#"><i class="fa fa-envelope-o"></i></a> <a href="{% url 'home' %}"><i class="fa fa-linkedin-square"></i></a> <a href="#"><i class="fa fa-github"></i></a> </div> </div> <div class="stats"> <div class="box"> <span class="value">523</span> <span class="parameter">Stories <i class="fa fa-pencil"></i></span> </div> <div class="box"> <span class="value">1387</span> <span class="parameter">Likes <i class="fa fa-heart-o"></i></span> </div> <div class="box"> <span class="value">146</span> <span class="parameter">Follower <i class="fa fa-thumbs-o-up"></i></span> </div> </div> </div> </div> <style> @import url(https://fonts.googleapis.com/css?family=Open+Sans:600,300); .frame { filter: … -
django: Refused to frame 'https://app.powerbi.com/' because an ancestor violates following Content Security Policy directive: "frame-ancestors 'self'
I am embedding a Power BI report into my django web app. The report uses RLS which I am trying to capture through my CustomUser model's "email" field. I have setup an azure app, I have added my azure principle name to the workspace, I have enabled embed token generation, and I can succesfully get an accesss token and embed token, but when I load the page on my localhost (haven't even tried prod yet), I get the error Refused to frame 'https://app.powerbi.com/' because an ancestor violates the following Content Security Policy directive: "frame-ancestors 'self'. my view: @login_required def dashboard(request): """Generate our own embed token and pass it to the template for the purpose of usable Row Level Security""" authority_url = "https://login.microsoftonline.com/" + settings.POWER_BI_TENANT_ID scopes = ['https://analysis.windows.net/powerbi/api/.default'] # get access token client = msal.PublicClientApplication(settings.POWER_BI_APP_ID, authority=authority_url) response = client.acquire_token_by_username_password(settings.POWER_BI_USERNAME, settings.POWER_BI_PASSWORD, scopes=scopes) access_token = response["access_token"] url = f"https://api.powerbi.com/v1.0/myorg/groups/{settings.POWER_BI_WORKSPACE_ID}/reports/{settings.POWER_BI_REPORT_ID}/GenerateToken" headers = {"Content-Type": "application/json", "Authorization": f"Bearer {access_token}"} data = { "accessLevel": "View", "identities": [ { "username": request.user.email, # The logged-in user's email "roles": ["teamrls"], "datasets": [settings.POWER_BI_DATASET_ID], } ], } response = requests.post(url, headers=headers, json=data) embed_token = response.json()["token"] # Pass the embed token to your template context = {"embed_token": embed_token, "report_id": settings.POWER_BI_REPORT_ID, "group_id": settings.POWER_BI_WORKSPACE_ID} return … -
Django App not accessible on host machine when deployed on microk8s environment
I have a Django app that i previously was running using docker-compose that I am trying to test on MicroK8s. I used kompose to convert the docker-compose config to kubernetes. This is the deployment definition. apiVersion: apps/v1 kind: Deployment metadata: annotations: kompose.cmd: kompose convert -f ../docker-compose.yml kompose.version: 1.31.2 (a92241f79) creationTimestamp: null labels: io.kompose.service: app name: app spec: replicas: 1 selector: matchLabels: io.kompose.service: app strategy: type: Recreate template: metadata: annotations: kompose.cmd: kompose convert -f ../docker-compose.yml kompose.version: 1.31.2 (a92241f79) creationTimestamp: null labels: io.kompose.network/bulabuy-build-default: "true" io.kompose.service: app spec: containers: - args: - sh - -c - |- python manage.py wait_for_db && python manage.py migrate && python manage.py runserver 0.0.0.0:8000 env: - name: DB_HOST value: db - name: DB_NAME value: devdb - name: DB_PASSWORD value: password - name: DB_USER value: devuser - name: SELENIUM_HOST value: selenium-custom - name: SELENIUM_PORT value: "5000" image: bulabuy-build-app imagePullPolicy: Never name: app ports: - containerPort: 8000 hostPort: 8000 protocol: TCP resources: {} volumeMounts: - mountPath: /vol/web name: dev-static-data restartPolicy: Always volumes: - name: dev-static-data persistentVolumeClaim: claimName: dev-static-data status: {} This is the service definition: apiVersion: v1 kind: Service metadata: annotations: kompose.cmd: kompose convert -f ../docker-compose.yml kompose.version: 1.31.2 (a92241f79) creationTimestamp: null labels: io.kompose.service: app name: app spec: ports: - name: … -
how to get image connected by a foreign key django
i want to get a image from the image model in the template The Model class Product(models.Model): Product_Type=models.CharField(max_length=25) Product_Name=models.CharField(max_length=25) Product_Size=models.IntegerField(null=True) Product_Price=models.FloatField() def first_image(self): #code to determeni image return self.images.first() def __str__(self): return self.Product_Name class Product_Image(models.Model): Product_name=models.ForeignKey(Product, related_name="images", on_delete=models.CASCADE) Product_Image=models.ImageField( upload_to="images/", height_field=None, width_field=None, max_length=None) def __img__(self): return self.Product_Image The view def index(request): new_products = Product.objects.all() # Retrieve the desired image associated with the product context = {'new_products': new_products} return render(request, "Genesis/home.html", context) l want to get image connected to that product, through my reading, studies and research have not fixed anything and no error has popped out some of my research include a youtube video fetching image in django and also How to get image connected by foreign key via template in django but no success {%if new_products %} {%for product in new_products%} <div class="col mb-5"> <div class="card h-100"> <!-- Product image--> <img src="{{ Product_name.first_image.images.url }}" alt="Product Image"> <!-- Product details--> <div class="card-body p-4"> <div class="text-center"> <!-- Product name--> <h5 class="fw-bolder">{{product.Product_Type}}</h5> <!-- Product price--> $40.00 - $80.00 </div> -
Django rest framework error : File field is required when using FileForm even though the file is recieved from request
I am trying to upload file on django backend . The is being received and i am to access it from request.FILES["file"] but the file form keeps giving me error about that the file field is required even though i am passing the file. This is view for uploading the file class FileViews(APIView): authentication_classes = [JWTAuthentication] permission_classes = [IsAuthenticated] def post(self,request): try: file = request.FILES.get("file") user_id = request.POST["user_id"] if not file or not user_id: return Response({"message": "Both 'file' and 'user_id' are required."}, status=rest_framework.status.HTTP_400_BAD_REQUEST) file_form = FilesForm( data = { "file_store" : file,"file_size":file.size,"user_id":user_id}) if file_form.is_valid(): file_form.save() print(file_form.cleaned_data) response = {"message" : "File is uploaded"} return Response(response , status = rest_framework.status.HTTP_201_CREATED) else: response = {"message" : file_form.errors} return Response(response , status=rest_framework.status.HTTP_400_BAD_REQUEST) except Exception as e: print(e) response = {"message" : str(e)} return Response(response , status = rest_framework.status.HTTP_500_INTERNAL_SERVER_ERROR) File form class FilesForm(forms.ModelForm): class Meta: model = Files fields = '__all__' and the file model class Files(models.Model): user_id = models.IntegerField(unique=True) file_size = models.PositiveIntegerField("file size(in Bytes)",default=0) file_store = models.FileField(upload_to=f"../uploads/{datetime.datetime.now()}") file_compressed = models.BooleanField(default = False) -
Redux State Status Stuck On Loading -Django Rest - React App
The status of redux is stuck on loading once logged in meaning that the site diary display and project display do not load. I've reset the state through the Redux Dev Tool but still experience the same issue. I believe it gets stuck on a 304 request. The request is made to a django-rest api which when queried through postman returns the correct infomation. Once a new entry is added, i want the entry to be added to the state and displayed on the page. apiSlice.js import { createSlice, createAsyncThunk, createAction } from '@reduxjs/toolkit'; import axios from 'axios'; import api, { setAuthToken } from './api/api'; import { dispatch } from 'react'; // define an inital state for the API data const initialState = { projects: [], clients: [], siteDiary: [], showDetails: false, selectedProject: null, status: 'idle', error: null, storeUloadedFiles: [], }; //Fetch Project Information with API export const fetchProjects = createAsyncThunk('projects/fetchProjects', async (arg, { getState }) => { // Get the token from your state or however you have stored it const token = getState().auth.email.access; setAuthToken(token); const response = await api.get('projects/'); return response.data; }); export const deleteProject = createAsyncThunk( 'api/deleteProject', async (projectId, { dispatch }) => { try { await … -
channel_layer.send() not sending messages to unique channel_names based on username - Django channels
I am trying to implement a way to send messages to users that are user specific. I have seen the docs where they advice to store the channel_name in the database and remove it on disconnect, but I think that will be a burden on the database as channel_name keeps on changing whenever the user connects to the consumer. So I tried the below method during accept, where I tried to assign the user's user_name as a unique channel name consumer class ChatGenericAsyncConsumer(AsyncWebsocketConsumer): """this is an async consumer""" async def connect(self): self.user = self.scope["user"] if self.user.is_authenticated: print( f"authentication successful connection accepted for {self.user.user_name}" ) self.username = f"{self.user.user_name}" self.channel_name = f"{self.user.user_name}" await self.accept() else: print("authentication unsuccessful connection closed") await self.close(code=4123) async def receive(self, text_data=None, bytes_data=None): pass async def disconnect(self, code): await self.close(code=4123) # this is the event handler of 'chat.message' async def chat_message(self, event): """ this method handles the sending of message to the group. this is same as chat.message """ # sending message to the group print(event["data"]) await self.send(text_data=event["data"]) and then tried to send a message from outside the consumer, where I try to mimic a situation that for some reason the admin wants to send a user specific message … -
Errors testing in Django with Selenium
When I pass my test in Django the result shows an output errors that looks like that: Traceback (most recent call last): File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/wsgiref/handlers.py", line 137, in run self.result = application(self.environ, self.start_response) File "/Users/bartolomeamoresvalderas/venv/django/lib/python3.9/site-packages/django/test/testcases.py", line 1723, in call return super().call(environ, start_response) File "/Users/bartolomeamoresvalderas/venv/django/lib/python3.9/site-packages/django/core/handlers/wsgi.py", line 124, in call response = self.get_response(request) File "/Users/bartolomeamoresvalderas/venv/django/lib/python3.9/site-packages/django/test/testcases.py", line 1706, in get_response return self.serve(request) File "/Users/bartolomeamoresvalderas/venv/django/lib/python3.9/site-packages/django/test/testcases.py", line 1718, in serve return serve(request, final_rel_path, document_root=self.get_base_dir()) File "/Users/bartolomeamoresvalderas/venv/django/lib/python3.9/site-packages/django/views/static.py", line 34, in serve fullpath = Path(safe_join(document_root, path)) File "/Users/bartolomeamoresvalderas/venv/django/lib/python3.9/site-packages/django/utils/_os.py", line 17, in safe_join final_path = abspath(join(base, *paths)) File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/posixpath.py", line 76, in join a = os.fspath(a) TypeError: expected str, bytes or os.PathLike object, not NoneType The code I am using for the test is: class test_incluir_elemento(LiveServerTestCase): def setUp(self): self.user = User.objects.create_user(username='testuser', password='secretpassword') self.driver = webdriver.Chrome() self.driver.implicitly_wait(10) def tearDown(self): self.driver.close() def test_incluir_elemento(self): self.driver.get(self.live_server_url) login = self.driver.find_element("id", "usuario") contrasena = self.driver.find_element("id", "contrasena") boton_login = self.driver.find_element("id", "boton-registro") login.send_keys("testuser") contrasena.send_keys("secretpassword") boton_login.click() modificar = self.driver.find_element("id", "modificar") modificar.click() The final output says that all the test are OK, so I assume that my test is working properly but these errors annoy me and I don't find information about it. -
How gunicorn nginx and supervisor are related code included
I have run my bin bash gunicorn file and yes, it boots me my 13 workers without errors but: aside from that, if I correctly understand how things work, this code (ip changed) should allow me to see my web, because gunicorn is replacing runserver gunicorn -b myweb.com:8500 estate.wsgi:application [2023-12-17 20:09:05 +0100] [15947] [INFO] Starting gunicorn 21.2.0 [2023-12-17 20:09:05 +0100] [15947] [INFO] Listening at: http://222.22.22.222:8500 (15947) but I get a bad request 400. Question: Should I be able to see my web through that command? If yes, why am I not seeing it? Then ginx simply calls that gunicorn file, so, if I haven't been able to see my web, nginx won't help at all. That means that the gunicorn despite booting workers is not doing any good? Supervisor won't help either, it is just to restart gunicorn whenever is down. for the curious, my gunicorn file is this (web address changed) NAME="boards" # Name of the application DJANGODIR=/home/boards/me # Django project directory SOCKFILE=/home/boards/run/gunicorn.sock # we will communicte using this unix socket USER=boards # the user to run as GROUP=boards # the group to run as NUM_WORKERS=13 # how many worker processes should Gunicorn spawn DJANGO_SETTINGS_MODULE=estate.settings # which settings file … -
Optimzing jsonfield filtering values of a certain index
Scenario: qs = mymodal.objects.values('foo__0__json_key').filter(foo__0__json_key__gte=numeric_value) Where we know that "json_key" is a numeric value inside the 0th index of foo. E.g. foo = [{"json_key": 12}, {"json_key": 23} {...} ... xN ] So my goal is to filter for each instance that has a the first jsonfield entry (In this case = 12) >= the provided numeric value, but it seems like my query approach has a very poor performance for running this query on e.g. 10 000 instances with foo being a field with more than 1000 entries. What are your suggestions to imrpove my query? Indexing? I really need to make things faster. Thanks in advance. -
My Django App stopped working after updating to django 5.0
My App Stopped working after upgrading to django 5.0 When I run my app I get the following message:- System check identified no issues (0 silenced). December 18, 2023 - 00:58:31 Django version 5.0, using settings 'mysite.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. [18/Dec/2023 00:58:37] "GET /admin HTTP/1.1" 200 4620 [18/Dec/2023 00:58:37] "GET /favicon.ico HTTP/1.1" 200 4620 -
RDBMS Many To Many Relationships Django
I am working on a django project and have difficulty in relating my data models. I wish to achieve the following, I have 3 models Employee, Project and ProjectRole. I wish to implement the models in such a way that User1 will have Lead (ProjectRole) in project1 but will have a Member (ProjectRole) in project2. While User2 will have Lead (ProjectRole) in project2 but Member (ProjectRole) in project1. Maybe the following table will make it clear. Employee Project ProjectRole User1 project1 Lead User1 project2 Member User2 project1 Member User2 project2 Lead I am totally confused and wish that someone explain in simple terms how relationships are to be defined within the models. So far, I have the following in my models.py, but I am sure it is incorrect, since it is not working as expected. class ProjectRole(models.Model): rolename = models.CharField(max_length=10) class Project(models.Model): projname = models.CharField(max_length=10) projrole = models.ManyToManyField(ProjectRole) class Employee(models.Model): empname = models.CharField(max_length=10) projrole = models.ManyToManyField(ProjectRole) Would love some guidance on how to achieve this seemingly complex design. -
How to render different dict into Django Views
I've been learning django recently and I am struggling when sending over 1 dictionary into a template in Django I have my embedViews.py which has multiple classes according to different sections of the page (So the views.py doesn't look a mess. And I can pass 1 of the classes into a template (html file) however, there is a page where I need to pass multiple dictionaries (lists) into the template. My logic told me to pass it in this way (see photo 1) views.py But the home/ does not render correctly, what I am doing wrong? Couldn't find the solution in the documentation. I expect to see all the lists on my html file. -
Vue app.use() doesn't accept my router as a parameter
I am making a new project using Django and Vue 3 (with pinia). I am trying to set up vue router (the lastest version) and I found these instructions in the vue router website https://router.vuejs.org/guide/ // 1. Define route components. // These can be imported from other files const Home = { template: '<div>Home</div>' } const About = { template: '<div>About</div>' } // 2. Define some routes // Each route should map to a component. // We'll talk about nested routes later. const routes = [ { path: '/', component: Home }, { path: '/about', component: About }, ] // 3. Create the router instance and pass the `routes` option // You can pass in additional options here, but let's // keep it simple for now. const router = VueRouter.createRouter({ // 4. Provide the history implementation to use. We are using the hash history for simplicity here. history: VueRouter.createWebHashHistory(), routes, // short for `routes: routes` }) // 5. Create and mount the root instance. const app = Vue.createApp({}) // Make sure to _use_ the router instance to make the // whole app router-aware. app.use(router) app.mount('#app') // Now the app has started! I did something similar: import './assets/main.css' import { createApp … -
Foreignkey dropdown list on frontend for Editview DRF
So I have this models: # -------------------------------------------------------------- Load Drivers Model class LoadDrivers(models.Model): driver = models.ForeignKey(User, default=None, null=True, blank=True, on_delete=models.DO_NOTHING, limit_choices_to={'is_driver': True}) load_key = models.ForeignKey(Loads, on_delete=models.DO_NOTHING, related_name="loaddrivers") driver_type = models.CharField(choices=DriverType.choices, max_length=2, default=None, null=True, blank=True) # -------------------------------------------------------------- Loads Model class Loads(models.Model): bill_to = models.CharField(max_length=50) price = models.DecimalField(default=None, null=True, blank=True, max_digits=15, decimal_places=2) truck = models.ForeignKey(Trucks, on_delete=models.DO_NOTHING, null=True, blank=True, related_name="loadtrucks") trailer = models.ForeignKey(Trailer, on_delete=models.DO_NOTHING, null=True, blank=True, related_name="loadtrailers") load_number = models.CharField(max_length=50, default=None, unique=True) notes = models.TextField(max_length=1000, default=None, null=True, blank=True) I'm Building DRF API. Now I'm currently making Edit view for this Loads, I created serializers, views , and everything works well, but there is only 1 problem, I really can't decide how can I get users dropdown list on front for this LoadDrivers field: driver = models.ForeignKey(User, default=None, null=True, blank=True, on_delete=models.DO_NOTHING, limit_choices_to={'is_driver': True}) For example when I go to edit view and I wanna change driver, how can I get that users dropdown list? One way to do this, I think that would be to create separate API endpoint that returns all Users and then do some stuff with Javascript. without DRF, with just forms and django templates, I would have {{ form }} and for driver field it would render with users dropdown list … -
Custom templatetags in overridden django-allauth template
I am using django-allauth with a custom signup template based on the default. Is there a way to include custom template tags in the template? using {% load custom_tags %} gives me a TemplateSyntaxError: custom_tags is not a registered tag library. Must be one of:. Here is my code: templates/account/signup.html (overrides allauth default) {% extends "account/base_entrance.html" %} {% load allauth i18n %} {% load custom_tags %} {% block head_title %} {% trans "Sign Up" %} {% endblock head_title %} {% block content %} {% element h1 %} {% trans "Sign Up" %} {% endelement %} <p> {% blocktrans %}Already have an account? Thsen please <a href="{{ login_url }}">sign in</a>.{% endblocktrans %} </p> {% url 'account_signup' as action_url %} {% element form form=form method="post" action=action_url tags="entrance,signup" %} {% slot body %} {% csrf_token %} {% element fields form=form unlabeled=True %} {% endelement %} {% if redirect_field_value %} <input type="hidden" name="{{ redirect_field_name }}" value="{{ redirect_field_value }}" /> {% endif %} {% endslot %} {% slot actions %} {% element button tags="prominent,signup" type="submit" %} {% trans "Sign Up" %} {% endelement %} {% endslot %} {% endelement %} {% if SOCIALACCOUNT_ENABLED %} {% include "socialaccount/snippets/login.html" with page_layout="entrance" %} {% endif %} {% endblock … -
Api in Django with Tastypie
I have created an API in latest version of Django using latest version of Tastypie. When I run the server of Django I get this error: cant import "datetime_safe" from "django.utils" I already have tried reinstalling the tastypie -
Django+nginx+gunicorn on Aws Lightsail unable to serve Static Files
I deployed a Django app on AWS Lightsail but am unable to serve static files in production. This is nginx/conf.d/nginx.conf: server { server_name *.*.*.* example.com www.example.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/imsrj/myproject/staticfiles; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } These are the permissions of the project: #sudo chown -R imsrj:www-data ~/myproject drwxrwxr-x 8 imsrj www-data 4096 Dec 17 21:53 myproject The /var/log/nginx/error.log is showing a "Permission denied" error: 2023/12/17 22:25:52 [error] 57788#57788: *21 open() "/home/imsrj/myproject/staticfilesimages/logo.png" failed (13: Permission denied), client: 223.188.234.183, server: 13.127.144.198, request: "GET /static/images/logo.png HTTP/1.1", host: "example.com", referrer: "https://example.com/" 2023/12/17 22:25:52 [error] 57788#57788: *22 open() "/home/imsrj/myproject/staticfilescss/main.css" failed (13: Permission denied), client: 223.188.234.183, server: 13.127.144.198, request: "GET /static/css/main.css HTTP/1.1", host: "example.com", referrer: "https://example.com/" 2023/12/17 22:25:53 [error] 57788#57788: *21 open() "/home/imsrj/myproject/staticfilesimages/favicons/favicon.ico" failed (13: Permission denied), client: 223.188.234.183, server: 13.127.144.198, request: "GET /static/images/favicons/favicon.ico HTTP/1.1", host: "example.com", referrer: "https://example.com/" Previously, I was using DigitalOcean, and everything was working fine. However, on AWS Lightsail, I am stuck here and have tried a lot, but the issue persists. Additionally, I tried the following modification in nginx.conf (as seen on Stack Overflow), changing "root" to "alias" in the static location block: location /static/ { … -
Django image is not displaying in developement environment
I'm trying add image in model with an Imagefield Folder Structure: /base /migrations /tempelates ... admin.py models.py urls.py ... /env /static /images avatar.png /styles /png /networth_tracker/ /tempelates/ db.sqlite3 manage.py pp1.jpg #image I uploaded from admin site pp2.jpg #image I uploaded from admin site pp3.jpg #image I uploaded from admin site /base/models.py class Account(models.Model): ... logo = models.ImageField(null=True,default="avatar.png") .... class Meta: ordering = ['-updated', '-created'] def __str__(self): return self.name /networth_tracker/urls.py from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('base.urls')), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIAFILES_DIRS) /networth_tracker/settings.py ... STATIC_URL = 'static/' STATICFILES_DIRS = [BASE_DIR / "static"] MEDIA_URL = '/images/' MEDIAFILES_DIRS = BASE_DIR / "static/images" ... Issue: I upload an image from admin site I tried to view the image directly in admin site and getting following error -- it searching for image in 127.0.0.1/images/pp1.jpg and returning page not found Image is uploading in / (root dir) instead of /static/images/ (media dir) I tried alternatives which is also not worked: I tried by adding upload_to="static/images" in ImageField models.py class Account(models.Model): ... logo = models.ImageField(null=True,default="avatar.png", upload_to="static/images") ... class Meta: ordering = ['-updated', '-created'] def __str__(self): return self.name It uploaded the … -
Cloudinary conflict with scss django
I'm having a Django Project and a problem setting up Cloudinary storage along with the SCSS preprocessor. First of all the preprocessor works well and compiles the files. But when I add: STATICFILES_STORAGE = 'cloudinary_storage.storage.StaticHashedCloudinaryStorage' I get the error: TypeError: MediaCloudinaryStorage.__init__() got an unexpected keyword argument 'ROOT' STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'sass_processor.finders.CssFinder', ] If I comment out STATICFILES_FINDERS, I get a different error: ValueError: Couldn't load manifest 'staticfiles.json' (version 1.0) If I'm trying to upgrade cloudinary_storage, I'm receiving: ERROR: Could not find a version that satisfies the requirement cloudinary_storage (from versions: none) ERROR: No matching distribution found for cloudinary_storage Please advise how to properly configure Cloudinary and SCSS so that they do not conflict Please advise how to properly configure Cloudinary and SCSS so that they do not conflict -
HTMX pages lose styling after page idle
I have an HTMX app styled using TailwindCSS. If I am on my site and then leave the browser (new tab or exit browser entirely) for while (more than 30 mins), when I come back the page has lost styling. Icons and text are plain HTML. I mostly need help knowing if this is an HTMX issue or an HTML issue. I am using hx-boost and which swaps the body of the new HTML page into the old one. I have a feeling that when the browser restores the page it only restores the body, rather than whole page, but I am an amateur dev so don't take what I say with a grain of salt. I read somewhere about the HTTP Expires Response Header but it is still not clear if this is my issue. -
Why did the static stop working on the server?
Static files stopped working when the project was deployed I have tried various configurations of settings, nginx and docker-compose. When inserting a direct link from the Internet to bootstrap files into the base template, the static started working, it did not stop in the admin panel settings.py STATIC_URL = '/static/' STATIC_ROOT = BASE_DIR / 'static' MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR / 'media' nginx.conf upstream coolsite_web { server coolsite_web:8080; } server { listen 80; listen [::]:80; server_name zatolokina-clinic.ru www.zatolokina-clinic.ru; server_tokens off; charset utf-8; location / { proxy_pass http://coolsite_web; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; } location /static/ { alias /coolsite/static; } location /media/ { alias /coolsite/media; } } docker-compose coolsite_web: build: context: . dockerfile: Dockerfile container_name: zatolokina expose: - "8080" volumes: - ./coolsite:/coolsite - static_volume:/coolsite/static - media_volume:/coolsite/media env_file: - .env environment: - POSTGRES_HOST=pg_db - POSTGRES_DB:${POSTGRES_DB} - POSTGRES_USER:${POSTGRES_USER} - POSTGRES_PASSWORD:${POSTGRES_PASSWORD} command: > sh -c "python manage.py collectstatic --noinput --clear && python manage.py makemigrations && python manage.py migrate && gunicorn coolsite.wsgi:application --bind 0.0.0.0:8080" depends_on: - pg_db nginx: build: context: ./nginx dockerfile: Dockerfile volumes: - static_volume:/coolsite/static - media_volume:/coolsite/media - ./nginx:/etc/nginx/conf.d ports: - "80:80" - "443:443" restart: always depends_on: - coolsite_web Project structure I also entered the ls -l /coolsite/static command and … -
Serializing ManytoMany field in Django
I am trying to get all the tags associated with a submission. It successfully return the list of the tags when I hit the endpoint to get all the submissions but when I hit a particular submission, I get null as the values. this is my model class Tag(models.Model): title = models.CharField(max_length=50,) def __str__(self): return str(self.title) class Submission(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=300, null=True, blank=True) abstract = models.TextField(null=True, blank=True) comment_for_editor = models.TextField(null=True, blank=True) completion_status = models.BooleanField(default=False) tags = models.ManyToManyField("Tag", blank=True, related_name='tags') section = models.ForeignKey("Section", on_delete=models.CASCADE, null=True, blank=True) this is my serializer class TagSerializer(serializers.ModelSerializer): class Meta: model = Tag fields = ['title'] class startSubmissionSerializer(serializers.ModelSerializer): files = SubmissionFilesSerializer(many=True, required=False) tags = TagSerializer(many=True, read_only=True) class Meta: model = Submission fields = ['section', 'title', 'abstract', 'comment_for_editor', 'completion_status', 'files','tags', 'id'] def create(self, validated_data): user = self.context['user'] files = validated_data.pop('files', []) tags = validated_data.pop('tags', None) submission = Submission.objects.create( author=user, **validated_data ) tags = str(tags['title']).split(', ') print(tags) for tag_title in tags: tag, _ = Tag.objects.get_or_create(title = tag_title) submission.tag.add(tag) submission.save() if files != []: for file in files: SubmissionFiles.objects.create( submission = submission, **file ) return submission I get back all of my submissions [ { "section": 1, "title": "New Submission 11", "abstract": "diqgduigodui", "comment_for_editor": "hodihcioshiochiohsioc", "completion_status": … -
"Set the REMOTE_MONITORING_BASE_URL environment variable" when trying to run django server
I was given a directory with Django project, and my task is to fing out hot it works. Cause I'm just statrting to study Django I face some difficulties with it. When I try to run server this error message occurs --------------------------------------------------------------------------- KeyError Traceback (most recent call last) File c:\Users\xok4ge\AppData\Local\Programs\Python\Python39\lib\site-packages\environ\environ.py:275, in Env.get_value(self, var, cast, default, parse_default) 274 try: --> 275 value = self.ENVIRON[var] 276 except KeyError: File c:\Users\xok4ge\AppData\Local\Programs\Python\Python39\lib\os.py:679, in _Environ.__getitem__(self, key) 677 except KeyError: 678 # raise KeyError with the original key value --> 679 raise KeyError(key) from None 680 return self.decodevalue(value) KeyError: 'REMOTE_MONITORING_BASE_URL' During handling of the above exception, another exception occurred: ImproperlyConfigured Traceback (most recent call last) c:\Users\xok4ge\Documents\VS Code\kycbase\backend\manage.py in line 22 18 execute_from_command_line(sys.argv) 21 if __name__ == '__main__': ---> 22 main() c:\Users\xok4ge\Documents\VS Code\kycbase\backend\manage.py in line 18, in main() 12 except ImportError as exc: 13 raise ImportError( 14 "Couldn't import Django. Are you sure it's installed and " 15 "available on your PYTHONPATH environment variable? Did you " 16 "forget to activate a virtual environment?" 17 ) from exc ---> 18 execute_from_command_line(sys.argv) File c:\Users\xok4ge\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py:442, in execute_from_command_line(argv) 440 """Run a ManagementUtility.""" 441 utility = ManagementUtility(argv) --> 442 utility.execute() File c:\Users\xok4ge\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py:436, in ManagementUtility.execute(self) 434 sys.stdout.write(self.main_help_text() + "\n") 435 else: --> … -
GeneratedField() ValueError("Cannot force an update in save() with no primary key.")
In my Employee model, I defined a field called "full_name" declared as a models.GeneratedField like so: class Employee(models.Model): first_name = models.CharField(max_length=100) mid_name = models.CharField('Middle name', max_length=75) last_name = models.CharField(max_length=75) full_name = models.GeneratedField( expression=Concat( "last_name", Value(", "), "first_name", Value(" "), "mid_name" ), output_field=models.CharField(max_length=250), db_persist=True, ) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET(get_sentinel_user)) However, when I tried to save a record in the admin page, I got ValueError("Cannot force an update in save() with no primary key."). To find out what causes the problem, I tried the following: Commented out the user field, and the system worked just fine. Re-instated back the user field, but changed to on_delete=models.SET_NULL, null=True, blank=True. Runserver and tried adding records in the admin page. Here, I observed that: If I left the user field blank, the system worked just fine. If I set the field with an existing user, this is where the system error occured. Anyone else encountered this problem? How did you fix this? Or is this some kind of a bug? django 5.0