Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to display chord images on hover in a Django Rest Framework and React website?
I am building a Django Rest Framework and React website where I have a song view component that displays song lyrics with embedded chord spans. I also have a folder in my React project containing chord images for different guitar chords. The website i am making is a copy of this website Pesmarica I want to implement the same feature Pesmarica has which is upon hovering over a chord span in the lyrics, the corresponding chord image is displayed as a small card(the letters in blue). For example, when hovering over the chord "Hm", the image "Hm.png" should be shown. In my django project i have scraped the Pesmarica website and added the songs to my models. For example when the react frontend requests for the same song as the one i linked above, my django backend will responde with this: { "url": "http://127.0.0.1:8000/api/songs/957/", "id": 957, "created_at": "2023-07-04", "title": " Hladne noci", "album": "", "artist": { "id": 650, "name": "Mirko Popov" }, "genre": "", "year": 2023, "lyrics": "<span class=\"chords\">Hm</span> <span class=\"chords\">Em</span>\r\nKo si ti, da fališ mi\r\n<span class=\"chords\">A</span> <span class=\"chords\">D</span> <span class=\"chords\">F#</span>\nČak i po danu donese te vetar\r\n <span class=\"chords\">Hm</span> <span class=\"chords\">Em</span>\r\nPa miris tvoj, ja osetim\r\n<span class=\"chords\">F# </span> <span class=\"chords\">Hm</span>\r\nNa lepe … -
PostgreSQL connection settings got error in Django
I read the new version in django document, I am follow this post , but doesn't work: **conn = _connect(dsn, connection_factory=connection_factory, **kwasync)** django.db.utils.OperationalError: definition of service "Servers" not found here is my processing: 1.I create the file ".pg_service.conf" in %APPDATA%, and I wrote database information, like this: [Servers] host=localhost user=wingto dbname=HyCloud port=5432 2.create passfile in nearby my django project, manage.py enter image description here localhost:5432:HyCloud:wingto:***** 3.Setting.py in django DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql", "OPTIONS": { "service": "Servers", "passfile": "passfile", }, } } -
Trouble installing psycopg2 on Mac
I'm pretty new to developing and have found some errors while trying to deploy my django project on heroku. I'm trying to download the django-heroku package with pip but keep running into this error: ld: warning: directory not found for option '-L/usr/local/opt/openssl/lib' ld: library not found for -lssl clang: error: linker command failed with exit code 1 (use -v to see invocation) error: command '/usr/bin/clang' failed with exit code 1 [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. ERROR: Failed building wheel for psycopg2 Failed to build psycopg2 ERROR: Could not build wheels for psycopg2, which is required to install pyproject.toml-based projects I've tried so many things, exhausted chatGBT, and have read so many articles. I've tried reinstalling openssl and using these commands: export LDFLAGS="-L/usr/local/opt/openssl/lib" export CPPFLAGS="-I/usr/local/opt/openssl/include" I've also tried installing psycopg2-binary which worked, only to find that installing django-heroku requires psycog2. I tried installing django-heroku with no dependencies, but it still requires pspycopg2. I've tried upgrading home-brew, pip, the pip setup, and so much more. All the articles on this are pretty old so some fresh eyes would help! I'm using macOS Ventura 13.4.1. Thanks in advance! -
Access to fetch at https://api-test-license.onrender.com/licenses'from origin https://license-frontend.onrender.com has been blocked by CORS policy
I'm using render to make a simply fullstack app the back end is coded with python and django framework, i've deployed the back end and front end using render but i'm still getting the same result which is Access to fetch at 'https://api-test-license.onrender.com/licenses' from origin 'https://license-frontend.onrender.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request. this is my JS code const url = 'https://api-test-license.onrender.com/licenses' export const nuevaLicencia = async license => { try { await fetch(url, { method: 'POST', body: JSON.stringify(license), headers: { 'Content-Type':'application/json' } }); window.location.href = 'index.html'; } catch (error) { console.log(error); } } export const obtenerLicencias = async () => { try { const resultado = await fetch(url); const licencias = await resultado.json(); return licencias; } catch (error) { console.log(error); } } export const eliminarLicencia = async id => { try { await fetch(`${url}/${id}`, { method: 'DELETE' }) } catch (error) { console.log(error); } } export const obtenerLicencia = async id => { try { const resultado = await fetch(`${url}/${id}`); const licencia = await resultado.json(); return licencia; } catch (error) { console.log(error); } } export const actualizarLicencia = async licencia => { try … -
context data is not passed from django TemplateView to Template
I have two models: Address and AddressHistory , with one to many relationship. I have created a form to allow user to Add address history, where I am using an inlineformset for Address, but when template is rendered, AddressHistory form is displayed for inline AddressForm. Here is my view class: I have two models: Address and AddressHistory , with one to many relationship. I have created a form to allow user to Add address history, where I am using an inlineformset for Address, but when I render the template, AddressHistory form is displayed for inline AddressForm. Here is my view class: class AddHistoryView(generic.TemplateView): template_name = "history/add_history.html" def get_context_data(self, **kwargs: Any) -> Dict[str, Any]: context = super().get_context_data(**kwargs) AddressHistoryFormset = formset_factory(forms.AddressHistoryForm, extra=1) AddressFormset = inlineformset_factory( Address, AddressHistory, fields=("__all__"), extra=1 ) if self.request.method == "POST": address_history_formset = AddressHistoryFormset( self.request.POST, prefix="addresshistory" ) address_formset = AddressFormset(self.request.POST, prefix="address") if ( address_history_formset.is_valid() and address_formset.is_valid() ): address_history_formset.save() address_formset.save() else: address_history_formset = AddressHistoryFormset(prefix="addresshistory") address_formset = AddressFormset(prefix="address") context["address_history_formset"] = address_history_formset context["address_formset"] = address_formset return context class AddressHistoryForm(forms.ModelForm): class Meta: model = models.AddressHistory fields = [ "from_day", "to_day", "address", "person", "arriving_entry", "departing_entry", ] class AddressForm(forms.ModelForm): class Meta: model = models.Address fields = [ "address_id", "line1", "line2", "city", "state", "country", "zipcode", "address_type", … -
how to make Nginx load staticfiles from a Django site
I deployed my django site with nginx, but my staticfiles such as css,js or media files are not being loaded, therefore I need help configurating it my site where the static files are not being loaded In web console i'm getting this error: 16Refused to apply style from '<URL>' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. my settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } STATIC_URL = '/static/' STATIC_ROOT = 'deploystatic' STATICFILES_DIRS = [BASE_DIR / 'static'] MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR / 'media' # Default primary key field type # https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' my configuration in nano /etc/nginx/sites-available/myproject server { listen 80; server_name ecommerce.jamelaumn.com; return 301 https://$server_name$request_uri; } server { listen 443 ssl; server_name ecommerce.jamelaumn.com; ssl_certificate something/fullchain.pem; ssl_certificate_key somethingblablabla/privkey.pem; location / { proxy_pass http://127.0.0.1:8000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } } my nginx.conf probably everything there is default configuration -
model related to User model by foreign key problem
I'm learning django and have a totally newbie question. When someone logs in the system it should be able to register it's football team for instance... here's my model: from django.db import models from django.contrib.auth.models import User class Equipo(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) # new Fname = models.CharField(max_length=50) RUT = models.TextField() here's my view: from django.shortcuts import render, redirect from django.urls import reverse from .forms import CrearFT def dashboard (request): crear_ft = CrearFT() if request.method == 'POST': crear_ft = CrearFT(data=request.POST) if crear_ft.is_valid(): crear_ft.save() return redirect(reverse('dashboard')+'?ok') else: return redirect(reverse('dashboard')+'?error') return render(request, 'vets/dashboard.html', {'form':crear_ft}) here's my form: from django import forms from django.forms import ModelForm from .models import Equipo class CrearFT(ModelForm): class Meta: model = Equipo fields = "__all__" The thing is that when I make the form in the view and run it, I can select the more than 1 user, I can see all users. Is there a way so the user is implicit? enter image description here Also a logged in user might have more than one football team, so I should be able to register more than one... I really appreciate your help. Thanks! -
Media not found when using language prefixes (i18n_patterns)
My images in my website work perfectly when I don't use the language prefix. http://example.com/ displays my images correctly but http://example.com/en/ doesn't display my media because the urls for my media automatically become 'en/media/image.jpg' instead of 'media/image.jpg' where the media actually lives. Is there a way tell django to not append the language prefix to my media urls? -
Django, the page does not display. must be called with either an object pk or a slug in the URLconf
In a django project, when creating a contact page, I can't display the page using the DetailView class. Debug info shows that slug or pk is missing here is my view: class MyContactsView(DetailView): model = Contacts template_name = 'contacts/contact.html' def get_context_data(self, **kwargs: Any) -> Dict[str, Any]: """Generate the data to be displayed on the page.""" context = super().get_context_data(**kwargs) main_banner = MainBanner.objects.order_by('-id').last() context['main_banner'] = main_banner contacts = Contacts.objects.order_by('-id').last() context['contacts'] = contacts return context URL urlpatterns = [ path('', views.MyContactsView.as_view(), name='contacts'), # path('', views.contact_page, name='contacts'), ] Although in the url routes I did not specify additional parameters. error message: Generic detail view MyContactsView must be called with either an object pk or a slug in the URLconf. -
how to set default value for textarea in form in django?
I am making an app, and I need to set the default value of a textarea in a form as a field inside a model. This is what my form looks like: class SaveNotes(forms.Form): notes = forms.CharField(widget=forms.Textarea(attrs={ 'class' : 'textarea has-fixed-size', 'style' : 'height: 50%; margin-bottom: 1%', 'placeholder' : 'might start limiting my spending...', })) and here is the view for the webpage: def spaceDashboard(request, id): template = "spaces/dashboard.html" accessDeniedTemplate = "errors/403.html" space = get_object_or_404(Space, pk=id) recordsFormClass = RecordForm bardRequestsFormClass = BardRequests saveNotesFormClass = SaveNotes deleteUrl = "delete/%s" % space.id recordsUrl = "%s/records" % space.id if request.method == "POST": recordsForm = recordsFormClass(request.POST) bardRequests = bardRequestsFormClass(request.POST) saveNotesForm = saveNotesFormClass(request.POST) if saveNotesForm.is_valid(): notes = saveNotesForm.cleaned_data["notes"] space["notes"] = notes space.save() if recordsForm.is_valid(): data = recordsForm.cleaned_data new = Record(amount=data["amount"], memo=data["memo"]) new.save() space.records.add(new) space.balance = space.calculateBalance() print(space.balance) messages.info(request, "Record has been added successfully.") if bardRequests.is_valid(): data = bardRequests.cleaned_data response = bard_requests.askQuestion(data["request"]) return HttpResponse(response) if request.user.is_authenticated: if request.user.username == space.owner.username or space.owner == None: return render(request, template, context={ "space" : space, "goalPercentage" : (space.calculateBalance()/(space.goal/100)), "recordsForm" : recordsFormClass, "bardRequestsForm" : bardRequestsFormClass, "saveNotesForm" : saveNotesFormClass, "recordsCount" : len(space.records.all()), "deleteUrl" : deleteUrl, "recordsUrl" : recordsUrl, }) else: return render(request, accessDeniedTemplate) else: return redirect("/login") Is there a way to pass … -
django admin panel date timedelta filtering
I'm using this filter: late_borrowings = Borrowing.objects.filter(returned=False).filter( borrow_date__lte=datetime.now().date() - timedelta(days=15)) How can I do it in django admin panel? -
Ajax, JavaScipt with Django, update data on page
I want to make an asynchronous update of the data on the page. There is a table that loads data from the database. Outputs via Django template engine, data in the table is added/updated from the side. And so that I can see them in the table, I need to refresh the page itself. But I need the table to be updated without updating the page itself. I reviewed a lot of options and examples on the Internet, but I did not understand. There are no simple examples. Please help, I think many people are interested in this question :slight_smile: view.py def test(request): last_3 = New_tables.objects.filter(active=0).order_by('-id')[:3] last_new_table = reversed(last_3) return render(request, 'main/test.html', {"last_new_table":last_new_table}) test.html That’s how I tried to output via Javascript, but unfortunately it doesn’t work either. Updates the data on the page only after the page is refreshed… {% extends 'main/base.html' %} {%block content%} {% load static %} <script src="https://snipp.ru/cdn/jquery/2.1.1/jquery.min.js"></script> <table class="table table-hover table-dark"> <thead> <tr> <th class="text-white-50 bg-dark" style="font-size: 0.9em;" scope="col">Table</th> <th class="text-white-50 bg-dark text-center " style="font-size: 0.9em;" scope="col">N</th> <th class="text-white-50 bg-dark text-center " style="font-size: 0.9em;" scope="col">Type</th> <th class="text-white-50 bg-dark text-center " style="font-size: 0.9em;" scope="col">Quote</th> <th class="text-white-50 bg-dark text-center " style="font-size: 0.9em;" scope="col">Start</th> </tr> </thead> <tbody class="tbody"> … -
Step by step procedure to develope a portfolio website [closed]
I want to develop a portfolio website.... please guide I had tried google-sites but it has very limited options I havent had any experience of doing such thing in past, keeping in mind please suggest some links on web where i got ample support in building me website. -
How to solve page not found in django
im having a problem with page not found. Page not found error In that pic you can see there is only the admin page, but not the calc page im looking for. Project name is sharedlibrary. Here is the urls.py under sharedlibrary from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('calc/', include('calc.urls')), ] here is the urls.py under folder called calc from django.urls import path from . import views urlpatterns = [ path('home/', views.home) ] here is the views.py file from django.shortcuts import render from django.http import HttpResponse def home(request): return HttpResponse("hello world") i wanted to get a primitive hello world program. instead the calc/home/ page isnt showing, like if i wouldnt write it. i tried: restarting visual studio restarting the terminal restarting my pc changing this code in the urls.py from: urlpatterns = [ path('admin/', admin.site.urls), path('calc/', include('calc.urls')), ] to this: urlpatterns = [ path('admin/', admin.site.urls), path('calc/', views.home, name="home"), ] -
Can't get Apache web server to show my django app
On the server I can run python manage.py runserver 0.0.0.0:8000 on the server and it renders my app fine. When I try via Apache, I get the infinite load and nothing renders. Spent too much time trying to troubleshoot and can't figure it out. Any help is appreciated! Here's my configs. <VirtualHost *:80> # The ServerName directive sets the request scheme, hostname and port that # the server uses to identify itself. This is used when creating # redirection URLs. In the context of virtual hosts, the ServerName # specifies what hostname must appear in the request's Host: header to # match this virtual host. For the default virtual host (this file) this # value is not decisive as it is used as a last resort host regardless. # However, you must set it for any further virtual host explicitly. #ServerName www.example.com ServerAdmin webmaster@localhost DocumentRoot /var/www/html # Available loglevels: trace8, ..., trace1, debug, info, notice, warn, # error, crit, alert, emerg. # It is also possible to configure the loglevel for particular # modules, e.g. #LogLevel info ssl:warn ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined # For most configuration files from conf-available/, which are # enabled or disabled at a global level, … -
RelatedObjectDoesNotExist error occurs in Django
IM NEW TO PYTHON I HAVE DOWNLOADED THIS PYTHON FROM GITHUB AND I GET THIS ERROR WHEN I RUN IT ERROR SCREENSHOT IT SAYS RelatedObjectDoesNotExist users has no faculty can some one solve the problem and post the correct code to execute the program I am still new to the language please solve the error as soon as possible model.py code from django.db import models from django.contrib.auth.models import User from django.core.exceptions import ObjectDoesNotExist def user_directory_path(instance, filename): name, ext = filename.split(".") name = instance.firstname + instance.lastname filename = name +'.'+ ext return 'Faculty_Images/{}'.format(filename) class Faculty(models.Model): user = models.OneToOneField(User, null = True, blank = True, on_delete= models.CASCADE) firstname = models.CharField(max_length=200, null=True, blank=True) lastname = models.CharField(max_length=200, null=True, blank=True) phone = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) profile_pic = models.ImageField(upload_to=user_directory_path ,null=True, blank=True) def __str__(self): return str(self.firstname + " " + self.lastname) def student_directory_path(instance, filename): name, ext = filename.split(".") name = instance.registration_id # + "_" + instance.branch + "_" + instance.year + "_" + instance.section filename = name +'.'+ ext return 'Student_Images/{}/{}/{}/{}'.format(instance.branch,instance.year,instance.section,filename) class Student(models.Model): BRANCH = ( ('CSE','CSE'), ('IT','IT'), ('ECE','ECE'), ('CHEM','CHEM'), ('MECH','MECH'), ('EEE','EEE'), ) YEAR = ( ('1','1'), ('2','2'), ('3','3'), ('4','4'), ) SECTION = ( ('A','A'), ('B','B'), ('C','C'), ) firstname = models.CharField(max_length=200, null=True, blank=True) lastname … -
ImportError: Couldn't import Django. Dockerfile multi stage build
I have made an app with the backend on django and react based frontend but inside a new separate django app. So I have to write a multi stage Dockerfile. [My project structure](https://i.stack.imgur.com/5wqV9.png) Dockerfile: FROM python:3.10.6 as backend ENV PYTHONUNBUFFERED 1 WORKDIR /app COPY requirements.txt ./requirements.txt RUN pip install -r requirements.txt COPY . . FROM node:18-alpine as frontend WORKDIR /app/frontend COPY frontend/package.json ./package.json COPY frontend/package-lock.json ./package-lock.json RUN npm install COPY frontend . RUN npm run build FROM python:3.10.6 WORKDIR /app COPY --from=backend /app . # RUN pip install -r requirements.txt COPY --from=frontend /app/frontend ./frontend CMD python3 manage.py runserver 0.0.0.0:8000 Docker Compose: version: "3.8" services: backend: build: context: . dockerfile: Dockerfile ports: - "8000:8000" volumes: - .:/app depends_on: - db db: image: postgres:15.3-alpine restart: always environment: - POSTGRES_PASSWORD=postgres - POSTGRES_USER=postgres - POSTGRES_DB=postgres ports: - "3000:5432" volumes: - ./data/db:/var/lib/postgresql/data/ Error: Traceback (most recent call last): dental_clinic_app-backend-1 | File "/app/manage.py", line 11, in main dental_clinic_app-backend-1 | from django.core.management import execute_from_command_line dental_clinic_app-backend-1 | ModuleNotFoundError: No module named 'django' I have the virtual environment activated.I dont know enough about docker but i suspect its overwriting files in the third stage but i just cant figure out why. Or maybe it is something entirely unrelated? NOTE: … -
Email verification fails everytime in django project
I am making a project in Django in which I need the users to go through an email verification. The email verification link is being generated and sent to the user on the email provided on signup. However when the confirm_email function(provided below) is called to check, it always results in failure(failure.html is shown everytime). def confirm_email(request, uidb64, otp): try: uid = force_bytes(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) print(user, uid, otp) except (TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user and default_token_generator.check_token(user, otp): user.is_active = True user.save() return render(request, 'path to email_confirmation_success.html') else: return render(request, 'path to email_confirmation_failure.html') What can be the issue here? I have printed the token generated in signup_page function and it is the same as the one being generated in the link sent to user singup_page function: def signup_page(req): if req.method == 'POST': form = CustomUserCreationForm(req.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False user.save() #Generating otp otp = generate_otp(user) print(otp) #Building email confirmation URL cur_site = get_current_site(req) # uid = urlsafe_base64_encode(user.pk) # otp_encoded = urlsafe_base64_decode(force_bytes(otp)) confirm_url = f"http://{cur_site.domain}/confirm-email/{(user.pk)}/{otp}/" # Load and render the HTML template template = loader.get_template('path to confirm-email.html') context = {'user': user, 'confirm_url': confirm_url} message = template.render(context) #Email to be sent subject = "Confirm … -
To create a user input form in Django that asks for name, ID, and Aadhaar num, and then encrypts the Aadhaar num when viewed from the admin database
How to achieve this by using cryptography or pycryptodome by using public and private keys? i tried different ways with public key or with cryptography fields but i can still see the data from admin panel followed many tutorials and github from Crypto.Cipher import AES from Crypto.Random import get_random_bytes from base64 import b64encode, b64decode class Candidate(models.Model): name = models.CharField(max_length=100) phone_number = models.CharField(max_length=20) adhar_number_encrypted = models.TextField(blank=True) pan_number = models.CharField(max_length=20) passport_number = models.CharField(max_length=20) def __str__(self): return self.name def encrypt_adhar_number(self, adhar_number): key = get_random_bytes(16) iv = get_random_bytes(AES.block_size) cipher = AES.new(key, AES.MODE_CBC, iv) ciphertext = cipher.encrypt(adhar_number.encode()) encrypted_value = b64encode(ciphertext).decode() return key, iv, encrypted_value def save(self, *args, **kwargs): if self.adhar_number and not self.adhar_number_encrypted: key, iv, encrypted_adhar = self.encrypt_adhar_number(self.adhar_number) self.adhar_number_encrypted = encrypted_adhar super().save(*args, **kwargs) @property def decrypted_adhar_number(self): if self.adhar_number_encrypted: key, iv, encrypted_adhar = self.encrypt_adhar_number(self.adhar_number_encrypted) cipher = AES.new(key, AES.MODE_CBC, iv) decrypted_adhar = cipher.decrypt(b64decode(encrypted_adhar)).decode().strip() return decrypted_adhar return None -
Error : No module found, about a function in an other file, on a django app using eslatic search database, dockerize with docker-compose
I am triying to defin a view to a list of all text for one patient but I have "ModuleNotFoundError: No module named 'fake_date'" My script populate_index.py works fine, I did use it to generate a list of document in the elastic search database. But now I want to this note in my django app..I don't understand I did import NoteDocument on my view. views.py : from django.shortcuts import render from usersapp.models import Patient from utils.populate_index import NoteDocument def patient_texts(request, patient_id): # Récupérer le patient en fonction de l'ID fourni try: patient = Patient.objects.get(id=patient_id) except Patient.DoesNotExist: return render(request, 'error.html', {'message': 'Patient not found'}) # Récupérer tous les documents de notes liés au patient notes = NoteDocument.search().filter('term', patient_username=patient.username).execute() context = { 'patient': patient, 'notes': notes } return render(request, 'patient_texts.html', context) populate_index.py : import os import sys import django # Ajoutez le chemin du répertoire racine de votre projet Django BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.append(BASE_DIR) os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'emotiontracking.settings') django.setup() from usersapp.models import CustomUser import csv from django.utils import timezone import random from elasticsearch_dsl import connections, Document, Text, Date, Keyword, Integer import pickle from fake_date import generate_fake_date_between import psycopg2 # Établir une connexion à Elasticsearch connections.create_connection(hosts=['192.168.1.31:9200']) # Charger le pipeline pré-entraîné with open('model/nlp-pipeline-linearsvc.pkl', 'rb') as … -
Safari not setting cookie coming in post request
Hi I am using django as server side, I am setting cookie with redirect request but it didnt work I tried to send a request only but the cookie still didnt work. response = HttpResponse('ok') expires = datetime.datetime.now() + expires_in response.set_cookie(key='session_cookie', value=session_cookie, expires=expires, samesite='Lax',httponly=True, secure=True) return response **here is the http response ** HTTP/1.1 200 OK Content-Type: text/html; charset=utf-8 X-Content-Type-Options: nosniff Set-Cookie: session_cookie=eyJhbGciOiJSUzI1NiIsImtpZCI6InRCME0yQSJ9.eyJpc3MiOiJodHRwczovL3Nlc3Npb24uZmlyZWJhc2UuZ29vZ2xlLmNvbS9tYW5pYWt1dyIsImFkbWluIjp0cnVlLCJhdWQiOiJtYW5pYWt1dyIsImF1dGhfdGltZSI6MTY4ODkxNDY5NiwidXNlcl9pZCI6InJXZkRRMk1vS0VidDkyRDhrdERsYVh4NVJUSDMiLCJzdWIiOiJyV2ZEUTJNb0tFYnQ5MkQ4a3REbGFYeDVSVEgzIiwiaWF0IjoxNjg4OTE0NzAyLCJleHAiOjE2ODkzNDY3MDIsImVtYWlsIjoib3NhbWF0YW1lcjM5MEBnbWFpbC5jb20iLCJlbWFpbF92ZXJpZmllZCI6ZmFsc2UsImZpcmViYXNlIjp7ImlkZW50aXRpZXMiOnsiZW1haWwiOlsib3NhbWF0YW1lcjM5MEBnbWFpbC5jb20iXX0sInNpZ25faW5fcHJvdmlkZXIiOiJwYXNzd29yZCJ9fQ.lUqDQBuRlJ2I8i7Da0zaDUQ8Bcih8Rr1oBzANINyi2Sde9yIZWE7VPx3ZSCizQHAnKRhjziSJBNN54dBIhdJk5Ps2yfHvUQaiaW7BhSmCu-K20Uvy3xv7HHoHaAKradSJXGM9Cs8a7t3PsAqQLroCbjFwmSsr31FpVxyrSueuAmrYedPkX0jz2XB3uanvl1FBYy1wx1Wrc_WbVs8DJCtpv1zTndOjDBxJvu0r2qIi7nc90EtPqfr0N6mKtPXn5pEJTdQ16f_O4-diuJbUsS7ivtWe9IFQPGWur9KaG6FpOngpWGpoJuDm0k2ReOaVQfQVLeJ46dTc6MzB7kEnLh4hg; expires=Fri, 14 Jul 2023 14:58:22 GMT; HttpOnly; Max-Age=432000; Path=/; SameSite=Lax; Secure, sessionid=tcbhtb1kfxu2p939j1g00ewsssyr0zx8; expires=Sun, 23 Jul 2023 14:58:22 GMT; HttpOnly; Max-Age=1209600; Path=/; SameSite=Lax; Secure Date: Sun, 09 Jul 2023 14:58:22 GMT X-Frame-Options: SAMEORIGIN Cross-Origin-Opener-Policy: same-origin Content-Length: 2 Referrer-Policy: same-origin Vary: origin, Cookie Server: WSGIServer/0.2 CPython/3.9.6 Every thing works correctly in chrome. I tried playing with cookie settings changed the samesite played with response object nothing worked. -
Better way to get second level foreign key data
I am using the following templatetag but I feel like there has got to be a better way. I am trying to get a list of skills that a provider has while cycling through all providers. Eventually, I plan to a filter for which providers to use. #skills.py from django import template from ..models import ProviderProfile, Skill register = template.Library() @register.inclusion_tag('util/li.html') def get_skills(user): provider = ProviderProfile.objects.get(user=user) skills = provider.skills.all() print(f"skills are {skills}") skills_list = skills.values_list("skill_id", flat=True) skill_list = Skill.objects.filter(id__in = skills_list) context = {'list': skill_list,} return context and the models are class Skill(models.Model): name = models.CharField(max_length=50,blank=False, null=True,) is_active = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True) update_at = models.DateTimeField(auto_now=True) class Meta: ordering = ('name',) def __str__(self): return f"{self.name}" class ProviderProfile(models.Model): user = models.OneToOneField( User,on_delete=models.CASCADE, blank=True, primary_key=True, ) pitch = models.TextField(blank=True) radius = models.SmallIntegerField(default=30, blank=True, null=True, help_text='Work radius in miles') notes = GenericRelation(Note) def __str__(self): return f"{self.user}" class ProviderSkill(models.Model): provider = models.ForeignKey(ProviderProfile, on_delete=models.CASCADE, related_name="skills") skill = models.ForeignKey(Skill, on_delete=models.CASCADE, related_name="std_skills") created_at = models.DateTimeField(auto_now_add=True) update_at = models.DateTimeField(auto_now=True) class Meta: unique_together = ["provider", "skill"] def __str__(self): return f"{self.provider} - {self.skill}" with the following view @login_required def clientProviderListView(request): providers = ProviderProfile.objects.all() context = {'providers': providers,} return render(request,'accounts/client_provider_list.html', context) and the main template {% extends 'core/base.html' %} {% block … -
No profile page member found matching the query: Profile page of all users (except admin) does not render)
I am continuing my Django journey and again turn to this forum for guidance. Problem definition Whenever I sign in into the website (I've successfully implemented CVB user authentication) with none-admin users, the encounter this error: What I have done I've made sure that the database is not empty; there are plenty of objects to query. I've tried to read the Django documentation on CBV and tried to understand all the different methods of the CB-DetailView and query the database. Project setup: In my project, I have several apps such as a main app for general functions, authentication app, profilepage app, settings app etc. The issue that I have concerns the profile_app I believe. My question How do I render the profile page of a specific user? I not familiar with how dynamic filtering using slug/Pk works when using CBV. I believe that DetailView is the right generic view that I'm using. What changes do I have to do solve this error described above? Model 1 - From app: main_app class Member(PermissionsMixin, AbstractBaseUser): # Fields for sign up page username = models.CharField( _("Användarnamn"), max_length=50, unique=True, default='') email = models.EmailField( _("Mail"), max_length=100, unique=True, default='') age = models.PositiveIntegerField(_("Ålder"), null=True, blank=False) country = … -
Can't able to update latest migrations in CICD using GITHUB actions
I'm created a simple Python Django REST API application, created a docker i,mage and automated the integration process using GitHub actions CICD pipeline. I have created the pipeline but whenever I make changes in the application, newly committed changes are not reflecting on the docker running container. For example, when I make changes in Django models fields, even though I make migrations before building the docker image, that migrated changes not reflecting in running container, I want to fix this then only can able to deploy in AWS. This is my first time working on server side, someone please do help me. Dockerfile: FROM python:3.9 ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 WORKDIR /app COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt COPY . . EXPOSE 8000 VOLUME /app CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"] docker-compose.yml: version: '3.8' services: web: build: context: . dockerfile: Dockerfile ports: - '8000:8000' volumes: - app_volume:/app environment: - DOCKER_HUB_USERNAME=my_username - DOCKER_HUB_TOKEN=my_token volumes: app_volume: Workflow: name: Deploy on: push: branches: [ "dev" ] jobs: deploy: runs-on: ubuntu-latest steps: - name: Checkout code uses: actions/checkout@v2 - name: Setup Python uses: actions/setup-python@v2 with: python-version: 3.9 - name: Install dependencies run: pip install -r requirements.txt - name: Build Docker image … -
Django: Select objects that have a duplicate value when related to same secondary object
I want to find objects with duplicate values for a specific field, but only if they are related to the same secondary object. For example, with the following models: class Blog(models.Model): name = models.CharField(max_length=100) ... class Entry(models.Model): blog = models.ForeignKey(Blog, on_delete=models.CASCADE) headline = models.CharField(max_length=255) pub_date = models.DateField() ... How do I select all Entry objects that have the same headline IF they are published in the same Blog. So headlines shared between blogs should not be included. (Bonus: An extra filter that extracts only duplicate headlines with the same publication date, still within the same blog). The closest solution I have is based on this answer: https://stackoverflow.com/a/8989348/20488494 The first part, obtaining duplicate values, is successful: dupe_entries_vals = ( Entry.objects .values('blog', 'date') .order_by() .annotate(count=Count('date')) .filter(count__gt=1) ) But then I can't use the second part because it loses related object filtering. The PKs are also lost due to taking values (necessarily, otherwise the duplicate filtering fails), so I can't use those either. # No longer restricted to related blog dupe_entries = Entry.objects.filter(headline__in=[e['headline'] for e in dupe_entries_vals]) # KeyError (id not in `dupe_entries_cals`) dupe_entries = Entry.objects.filter(pk__in=[e['id'] for e in dupe_entries_vals]) So is there a nice solution for this?