Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
How to render two model for one form and filled the db table?
In the app accounts I created in Django, I have three models. student, Adviser and PhoneNumber. Student model: class Student(models.Model): profile_image = models.ImageField( max_length=255, upload_to=get_student_profile_img_upload_path, null=True, blank=True, default=get_student_default_profile_image, ) user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) adviser = models.ForeignKey(Adviser, on_delete=models.CASCADE, related_name='adviser') educational_stage = models.CharField(choices=get_student_educational_stage(), max_length=4) grade = models.CharField(choices=get_student_grade(), max_length=10) field = models.CharField(choices=get_student_field(), max_length=21, null=True, blank=True) birthday_date = models.DateField(null=True) phone_number = models.ForeignKey(PhoneNumber, null=True, on_delete=models.SET_NULL) province = models.CharField(choices=PROVINCE_CHOICES, max_length=100) city = models.CharField(choices=CITY_CHOICES, max_length=100) Advisor model: class Adviser(models.Model): profile_image = models.ImageField( max_length=255, upload_to=get_adviser_profile_img_upload_path, null=True, blank=True, default=get_adviser_default_profile_image, ) user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) phone_number = models.ForeignKey(PhoneNumber, null=True, on_delete=models.SET_NULL) province = models.CharField(choices=PROVINCE_CHOICES, max_length=100) city = models.CharField(choices=CITY_CHOICES, max_length=100) PhoneNumber model: class PhoneNumber(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) phone_number = PhoneNumberField(null=False, blank=False, unique=True) I plan to have the phone number in a separate table, but when I want to create a form in forms.py, I have to use the student or advisor model. While I want the phone number to be stored in the phone number table and displayed together with the fields of the student or adviser model in form. in other words, I need to receive the phone number along with the student or adviser model fields, but it must also be stored in the PhoneNumber table. What method do … -
Why is Vue not adding the base path to some pages but to others
I have a Django backend and a Vue3 front end and everything works fine but on one page and in one component Vue is not adding the base url to the image src, so the images are not being displayed. Nothing is different from the component and view and the other components and views. So here is the part that gets the user profile pic from the localstorage which I save after login <div class="topUser" v-if="store.account != undefined && store.loggedIn" > <div class="pointer" @click="toggleSub" v-if="store.loggedIn"> <img class="profilePic" v-if="store.account.user.profile.profile_picture !== null" :src=" 'http://localhost:8000' + store.account.user.profile.profile_picture " alt="Profile Image" /> <img class="profilePic" v-else src="../assets/img/user.png" alt="Default Image" /> </div> </div> The 'http://localhost:8000' + I have to put there otherwise the image will not display The data that is in the store to feed the picture is this: store.account.user.profile.profile_picture:"/storage/user_6/profiles/1/images/tumblr_1580180affd193225f45aafa4039c395_c0ff6e67_540_pkdm85S.jpg" So ultimately I want to know why is Vue not adding the base url to the component and view but it adds it to all the other components and views? There is really nothing different in how the app gets the data. It's a worry because then what prevents it from adding the base url for some users and for others not? Is there a … -
Django Formset Validation - Sum Values Of Two Columns
I'm trying to get the sum values of two columns in a formset in Django. I want to extract the sum values of the two columns and do something when the sum of both meets a certain value. View: def bokforing(request): InnslagFormSet = formset_factory(form=InnslagForm, extra=3) if request.method == 'POST': formbokforing = InnslagFormSet(request.POST) formset = InnslagFormSet(request.POST) if formset.is_valid(): for form in formset: if form.has_changed(): form.save(commit=False) total = 0 for form1 and form2 in formset: total += form1.cleaned_data["innslagDebet"] total += form2.cleaned_data["innslagKredit"] if total == 500: return HttpResponse("Valid") I have tried to get the sum of values of one column and it works fine, but when i try to introduce a second column it does not seem to work. I've tried to have to two variables in the same loop. Did not work. Tried two seperate loops. Still did not work. All help would be much appreciated. -
How to login custom user in django? (UNIQUE)
I want to login custom user, but it returns an error {'username': [ValidationError(['A user with that username already exists.'])]} . I have a model of Worker which inherits from User model, but also has some unique fields. models.py class Worker(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) fullname = models.CharField(max_length=150) branch = models.ForeignKey(Branch, on_delete=models.SET_NULL, null=True) position = models.CharField(max_length=200) manager = models.BooleanField(default=False) def __str__(self): return self.fullname views.py def loginUser(request): form = UserForm() if request.method == 'POST': form = UserForm(request.POST) fullname = request.POST.get('fullname') if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password1') try: user = User.objects.get(username=username) except: print('User does not exist') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) try: worker = Worker.objects.get(user=user, fullname=fullname) if worker.manager == False: return redirect('main') else: return redirect('manager-main') except: print('No such worker') form = UserForm() return render(request, 'supply/login.html', {'form':form}) else: print('Username or password does not exist') else: print(form.errors.as_data()) return render(request, 'supply/login.html', {'form':form}) So, I'm trying to login user, and then trying to get worker using user. After that, I check if the worker is manager. If he is, I redirect him to a page for managers. If he is not, I redirect him to his page. But if there is no such worker, I render login page … -
How to select multiple choices for a field in django?
Ihave this Actor model on the app called crew. from django.db import models # Create your models here. class Parent(models.Model): # name=models.CharField(max_length=30,unique=True,default=None) name=models.CharField(max_length=30,unique=True,default=None) about=models.TextField(max_length=2000,blank=True,null=True) class Meta: abstract = True def __str__(self): return self.name class Actor(Parent): slug=models.SlugField(max_length=50,unique=True) photo=models.ImageField(upload_to='crew/actor') i want to add this model as a foreign key into the model called Movie which is on the app movie. and also want to select multiple actors on the fiels called starring from django.db import models from django.contrib.auth.models import User from crew.models import * from review_awards.models import * # Create your models here. class Movie(models.Model): name=models.CharField(max_length=100,unique=True,blank=True) slug=models.SlugField(max_length=100,unique=True,blank=True) year=models.CharField(max_length=5,blank=True) language=models.CharField(max_length=50,blank=True) poster=models.ImageField(upload_to='movies/poster') cover=models.ImageField(upload_to='movies/cover',null=True) duration=models.CharField(max_length=50,default=None) streaming=models.ForeignKey(Streaming,on_delete=models.CASCADE,blank=True,null=True) ott=models.TextField(max_length=50,blank=True,null=True) **starring**=models.ForeignKey(Actor,on_delete=models.CASCADE,related_name='actor',blank=True,null=True) director=models.ForeignKey(Director,on_delete=models.CASCADE,blank=True,null=True) cinematographer=models.ForeignKey(Cinematographer,on_delete=models.CASCADE,null=True,blank=True) writer=models.CharField(max_length=100,blank=True) based =models.CharField(max_length=100,blank=True,null=True) genre=models.CharField(max_length=100,blank=True) awards=models.ForeignKey(Award,on_delete=models.CASCADE,null=True,blank=True) critic_reviews=models.ForeignKey(Critic_Review,on_delete=models.CASCADE,null=True,blank=True) audience_reviews=models.ForeignKey(Audience_Review,on_delete=models.CASCADE,null=True,blank=True) rating=models.CharField(max_length=20,blank=True) certification=models.ForeignKey(Certification,on_delete=models.CASCADE,null=True,blank=True) synopsis=models.TextField(max_length=1000,blank=True) trailer=models.TextField(max_length=50,blank=True) def __str__(self): return self.name How can i implement it?, currently iam able to select only one choice. -
Reverse Serializing Many to Many Relations Causes RecursionError
Following on from this answer, I've attempted to reverse serialize objects from a many to many relationship. Using a serializer method field, I've tried to populate the people that have a person type however this is causing a RecursionError from django. I can see the issue, PersonA has PersonTypeA who has PersonA etc. but I'm not sure how to 'flatten' the returned people to one level. How can I overcome the recursion error? Models: class PersonType(models.Model): name = models.CharField(max_length=128) created = models.DateTimeField(auto_now_add=True) last_updated = models.DateTimeField(auto_now_add=True) start_time = models.DateTimeField() end_time = models.DateTimeField(null=True) class Person(models.Model): title = models.CharField(max_length=16) first_name = models.CharField(max_length=128) last_name = models.CharField(max_length=128) email_address = models.CharField(max_length=256) created = models.DateTimeField(auto_now_add=True) last_updated = models.DateTimeField(auto_now_add=True) start_time = models.DateTimeField() end_time = models.DateTimeField(null=True) person_types = models.ManyToManyField(PersonType, related_name="people") Serializers: class PersonTypeSerializer(serializers.ModelSerializer): people = serializers.SerializerMethodField() class Meta: model = PersonType fields = '__all__' def get_people(self, obj): people = obj.people.all() response = PersonSerializer(people, many=True).data return response class PersonSerializer(serializers.ModelSerializer): person_types = PersonTypeSerializer(many=True) class Meta: model = Person fields = '__all__' depth = 1 -
errror 503 in host /opt/alt/python310/bin/lswsgi: No such file or directory
I uploaded my python project to the host and made the necessary database settings and things, but it still gives me a 503 error. When I look at the log file, I get the following error. Please, if anyone knows, I would appreciate it. /usr/local/lsws/fcgi-bin/lswsgi_wrapper: line 18: /opt/alt/python310/bin/lswsgi: No such file or directory install packeges mysqlclient migrate settengs database allwed_host and passenger_wsgi , I did all these things, but the site did not load -
I am not able to save comments enter by user to database and retrive it to show on templates
<head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <h1>{{hotel.name}}</h1> <p>{{hotel.address}}</p> <p>{{hotel.city}}</p> <p>{{hotel.state}}</p> <p>{{hotel.Zip_code}}</p> <h2>Comment</h2> {% for C in hotel.comment.all %} <p>{{ C.comment }}</p> {% endfor %} <form action="/hotel/{{hotel.id}}/comment/" method="POST"> {% csrf_token %} <input type="text" name="comment" placeholder="your comment"> <input type="submit" value="comment"> </form> </body> </html> above code is for hotel_details.html where user will put comment and it will save in database and user will also able to see other users comment from django.shortcuts import render from demo.models import Hotel def hotel_list(request): hotel = Hotel.objects.all() context = { 'hotel': hotel, } return render(request, 'hotel_list.html',context) def hotel_details(request,hotel_id): hotel=Hotel.objects.get(id=hotel_id) context={ 'hotel':hotel, } return render(request, 'hotel_details.html',context) # Create your views here. def comment_on_hotel(request,hotel_id): hotel=Hotel.objects.get(id=hotel_id) if request.method == 'POST': comment=request.POST['comment'] hotel.comment += f'\n{comment}' hotel.save() return render(request, 'hotel_details.html',{'hotel':hotel}) above is views.py Models .py from django.db import models # Create your models here. class Hotel(models.Model): name=models.CharField(max_length=255) address=models.CharField(max_length=255) city=models.CharField(max_length=255) state=models.CharField(max_length=255) Zip_code=models.IntegerField() comment=models.TextField() urls.py from django.contrib import admin from django.urls import path from demo import views urlpatterns = [ path('admin/', admin.site.urls), path('',views.hotel_list,name='hotel_list'), path('hotel/<int:hotel_id>/',views.hotel_details, name='hotel_details'), path('hotel/<int:hotel_id>/comment/',views.comment_on_hotel , name='comment'), ] please anyone can help why this problem is happening I want that in hotel_details.html page a user should able to enter comment for particular hotel selected by him and it should … -
Django Rest Framework custom api.html throws warnings on OPTIONS request ajax form
I'm building my custom api.html template for Django Rest Framework api project (based on the official base.html template to customize mine), but I'm facing some issues implementing the OPTIONS button. Here it is my code: {% load static %} {% load i18n %} {% load rest_framework %} <!DOCTYPE html> <html lang="en" id="myHtml"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>My project title</title> <link rel="shortcut icon" href="{% static 'assets/compass-fill.ico' %}" /> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3/dist/css/bootstrap.min.css" rel="stylesheet" /> <link id="theme-link" rel="stylesheet" href="https://bootswatch.com/5/darkly/bootstrap.min.css" type="text/css" /> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css" /> <script src="https://code.jquery.com/jquery-3.7.0.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3/dist/js/bootstrap.bundle.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.form/4.3.0/jquery.form.min.js"></script> </head> <body> <div class="container"> ... {% if options_form %} <form class="button-form" action="{{ request.get_full_path }}" data-method="OPTIONS" > <button type="submit" class="btn btn-primary" data-bs-toggle="tooltip" data-bs-title="Make an OPTIONS request on the {{ name }} resource" data-bs-custom-class="tooltip-success" > OPTIONS </button> </form> {% endif %} ... </div> ... <script type="application/json" id="drf_csrf"> { "csrfHeaderName": "{{ csrf_header_name|default:'X-CSRFToken' }}", "csrfToken": "{% if request %}{{ csrf_token }}{% endif %}" } </script> <script src="{% static 'rest_framework/js/ajax-form.js' %}"></script> <script src="{% static 'rest_framework/js/load-ajax-form.js' %}"></script> <script src="{% static 'rest_framework/js/csrf.js' %}"></script> <script> other scripts </script> </body> </html> I created the OPTIONS button like in the original template base.html and in the end of the body I loaded js functions without them the button … -
add request.user to serialized data
iam created api request for creating a entity with collected data my view is like this ` @permission_classes([IsAuthenticated]) @api_view(["POST"]) def createAppoinment(req): appoinment=CreateAppoinmentSerializer(data=req.data) if appoinment.is_valid(): appoinment.save() return Response(appoinment.data,status=status.HTTP_201_CREATED) print(appoinment.data,"this is appoinment") return Response(appoinment.errors,status=status.HTTP_404_NOT_FOUND)```` and my serializer is like this class CreateAppoinmentSerializer(serializers.ModelSerializer): class Meta: model=Appoinment fields=['applicant_name','submission_date','appoinment_date', 'care_of','phone','appoinment_time','pass_seva_username', 'pass_seva_password','office','agency','paid','net_amo my model have additional foreign key field owner and a onetoone field, transaction how can i add the owner field and transaction field to to serilizer for create new entity i want to save datas from the front end in data base but i dont know how to add user and other foreign keys to serialization -
Celery task not executing in Django project with Redis broker
I'm working on a Django project where I'm using Celery with a Redis broker to run asynchronous tasks. I have a task that is supposed to run every minute, but it's not executing as expected. The task is received by the Celery worker, but it doesn't seem to be executed. Here's the code for my task: # socials/tasks.py from celery import shared_task import logging logger = logging.getLogger(__name__) @shared_task def hello(): logger.info("Hello") print("Hello") And here's my Celery configuration in Django settings: # settings.py CELERY_BROKER_URL = 'redis://localhost:6379/0' # I'm running Redis locally CELERY_BEAT_SCHEDULE = { 'every-minute': { 'task': 'socials.tasks.hello', 'schedule': crontab(minute='*/1') }, } I'm running the Celery worker and beat services with the following commands: celery -A my_project worker --loglevel=info celery -A my_project beat --loglevel=info The worker log shows that the worker is running and the socials.tasks.hello task is registered: [tasks] . socials.tasks.hello The beat log shows that the beat service is running and connected to the Redis broker: Configuration -> . broker -> redis://localhost:6379/0 However, the hello task is not executing. There are no error messages in the logs, and the task doesn't print "Hello" or log the message "Hello". I've checked that the Redis server is running, and the worker … -
How to display images in webpage in django with multiple apps
I currently have 2 applications. When I first made the first app it was displaying the images correctly. I would upload the images in the admin console then the image would be displayed in the webpage. Feeling confident I made another app on the same project with a different purpose but recycled the code to display images and now both apps are no working. The directory crm |_crm |_settings.py |_urls.py |_wsgi.py |_*.py |_website(app1) |_*.py |_templates |_*.html |_media |_images.png |_gamot(app2) |_*.py |_templates |_*.html |_manage.py Main/Global files Settings.py STATIC_URL = 'static/' MEDIA_URL = 'media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATIC_FILES_DIRS = (os.path.join(BASE_DIR,'static'),) urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('gamot/', include('gamot.urls'),name='gamot'), path('crm/', include('website.urls'),name='crm'), ] App Files View.py from django.shortcuts import render,redirect from django.contrib.auth import authenticate, login, logout from django.contrib import messages from .forms import SignUpForm,AddRecordForm from .models import * def upload_image(request): person = Person.objects.get(id=1) return render(request,'upload.html',{'person':person}) models.py from django.db import models class Person(models.Model): image = models.ImageField(null=True,blank=False,upload_to='img/') created_at = models.DateTimeField(auto_now=True) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) Urls.py from django.urls import path from django.conf import settings from django.conf.urls.static import static from . import views urlpatterns = [ ... path('upload',views.upload_image, name='add_record'), ]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Html {% extends 'base.html'%} {% … -
How to filter the most similar object from the sql query
I have the model which contains name with max length of 100 and there are about 5 lack data. And i have to filter the list of most similar object -
Django post_save signal, executing chained tasks
When I save a model I want to create some folders, then download a few things to those folders. Folders need to be created for the downloads, obviously, downloads can happen in parallel. HEre's what I have: @receiver(post_save, sender=Game) def after_game_model_save(sender, instance, created, **kwargs): logger.info("after_game_model_save") task = None task_id = uuid4() tasks_chain = chain(create_game_folder.s(instance.id)) if created: tasks_chain |= download_game.s(instance.id, instance.download_link).set( task_id=str(task_id) ) else: if instance.tracker.has_changed("screenshots_urls"): tasks_group = group( [ download_game.s(instance.id, instance.download_link).set( task_id=str(task_id) ), download_screenshots.s(instance.id), ] ) if instance.tracker.has_changed("download_link"): tasks_group = group( [ download_game_update.s(instance.id, instance.download_link).set( task_id=str(task_id) ), download_screenshots.s(instance.id), ] ) tasks_chain |= tasks_group tasks_chain.delay() try: task_obj = Task.objects.get(game=instance) task_obj.task_id = str(task_id) task_obj.save() except Task.DoesNotExist: Task.objects.create(game=instance, task_id=str(task_id)) I'm getting the error TypeError: download_game() takes 2 positional arguments but 3 were given If I interpret the examples correctly, the result of the first chained task get's sent as an argument to the second task? How can I chain tasks so they're executed in order without worrying about this? The functions return nothing. So I guess right now I end up with something like download_game.s(instance.id, instance.download_link, None)