Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
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