Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Use own __str__() method instead of model's through which object was accessed in Django
I have such models: class Location(models.Model): pass class Place(Location): name = models.CharField(...) def __str__(self): return str(self.name) class Coordinates(Location): x = models.DecimalField(...) y = models.DecimalField(...) def __str__(self): return f"({x}, {y})" I'm browsing locations through Locations.objects, but I want them to be displayed as defined in child __str__() methods. In addition, I can't make Location model abstract, because I use it as ForeignKey in other models. How to make objects use their own __str__() method, instead of model's through which I've accessed the object? -
how to run multiple Django project in using on Nginx and Gunicorn on docker(two diffrent django servers with diffent ports)
need to docker nginx configuration this is how basic nginx setup works for a single service nginx ├── Dockerfile └── nginx.conf Dockerfile: FROM nginx:1.21-alpine RUN rm /etc/nginx/conf.d/default.conf COPY nginx.conf /etc/nginx/conf.d nginx.conf: upstream hello_django { server web:8000; } server { listen 80; location / { proxy_pass http://hello_django; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } } Then, update the web service, in docker-compose.prod.yml, replacing ports with expose: Then, update the web service, in docker-compose web: build: context: ./app dockerfile: Dockerfile.prod command: gunicorn hello_django.wsgi:application --bind 0.0.0.0:8000 expose: - 8000 env_file: - ./.env.prod depends_on: - db -
Invalid block tag on line 117: 'endblock', expected 'empty' or 'endfor'. Did you forget to register or load this tag?
{% extends 'shop/basic.html' %} {% block css %} .col-md-3 { display: inline-block; margin-left: -4px; } .col-md-3 { width: 100%; height: auto; } body .no-padding { padding-left: 0; padding-right: 0; } .carousel-control-prev-icon { background: black no-repeat center center; background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' fill='%23fff' viewBox='0 0 8 8'%3e%3cpath d='M5.25 0l-4 4 4 4 1.5-1.5-2.5-2.5 2.5-2.5-1.5-1.5z'/%3e%3c/svg%3e"); } .carousel-control-next-icon { background: black no-repeat center center; background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' fill='%23fff' viewBox='0 0 8 8'%3e%3cpath d='M2.75 0l-1.5 1.5 2.5 2.5-2.5 2.5 1.5 1.5 4-4-4-4z'/%3e%3c/svg%3e"); } body .carousel-indicators{ bottom:0; } .carousel-indicators .active{ background-color: blue; } {% endblock css %} {% block body %} {% load static %} <!-- carousel indicators starts from here--> <div class="container" xmlns:data="http://www.w3.org/1999/xhtml"> <div id="demo" class="carousel slide my-3" data-ride="carousel">' <ul class="carousel-indicators"> <li data-target="#demo" data-slide-to="0" class="active"></li> {% for i in range %} <li data-target="#demo" data-slide-to="{{i}}" ></li> {% endfor %} </ul> <!-- slideshow starts here--> <div class="carousel-inner"> <div class="carousel-item active"> <div class="col-xs-3 col-sm-3 col-md-3"> <div class="card" style="width: 18rem;"> <img src='/media/{{product.0.image}}' class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title">Card title</h5> <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p> <a href="#" class="btn btn-primary">Go somewhere</a> </div> </div> </div> {% for i in product|slice:"1:" %} <div class="col-xs-3 col-sm-3 col-md-3"> <div class="card" … -
How to move only login page to another server with django (CSRF token missing)
I have login page with django authentication system. Now, I want to move only the login page to another server(external login page). So, my purpose is make username and password field on another server(external login page), then login to the django system. I made html on another server. <form method="POST" action="http://djangoserver.com/"> <input type="text" name="username"> <input type="password" name="password"> <input type="submit"> </form> However, this shows the error. Reason given for failure: CSRF token missing I checked the login page html source as django automatically created and confirmed there is csrf that django middleware makes. <form method="POST"> <input type="hidden" name="csrfmiddlewaretoken" value="VEkMTu0EpmLbMVLRh4h9MOcuvcryIlA0M1USByG7R5PXkgYvMyzAhdKyq7gohpko"> Username <input type="text" name="username" autofocus autocapitalize="none" autocomplete="username" maxlength="150" class="form-control" placeholder="Username" required id="id_username"> Password <input type="password" name="password" autocomplete="current-password" class="form-control" placeholder="Password" required id="id_password"> <button type="submit">login</button> </form> So, I guess I should mimic like this about csrf in external login page. Is there any good suggestion? -
How to pass JavaScript variables to Django template tags and filters?
I created test1 tag and test2 filter which both print arg on console in custom_tags.py as shown below: # "custom_tags.py" from django.template import Library register = Library() @register.simple_tag def test1(arg): print(arg) # Here return @register.filter def test2(arg): print(arg) # Here return Then, I passed Hello to test1 tag and test2 filter in <script></script> in index.html as shown below: {% "index.html" %} {% load custom_tags %} <script> {% test1 "Hello" %} {{ "Hello"|test2 }} </script> Then, Hello is printed on console as shown below: # "custom_tags.py" @register.simple_tag def test1(arg): print(arg) # Hello return @register.filter def test2(arg): print(arg) # Hello return Next, I passed JavaScript's val set Hello to test1 tag and test2 filter in <script></script> in index.html as shown below: {% load custom_tags %} <script> let val = "Hello" {% test1 val %} {{ val|test2 }} </script> But, nothing is printed on console as shown below: # "custom_tags.py" @register.simple_tag def test1(arg): print(arg) # Nothing return @register.filter def test2(arg): print(arg) # Nothing return So, how can I pass JavaScript's val set Hello to test1 tag and test2 filter to print Hello on console? -
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 …