Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
'SignInForm' object has no attribute 'request'
I'm trining to set remember_me in forms.py insted of views.py via def clean_remember_me. but it dosn't work and give me error ! remember_me = forms.BooleanField(widget=forms.CheckboxInput(),label=_('Remember me'), required=False) def clean_remember_me(self): remember_me = self.cleaned_data['remember_me'] if not remember_me: self.request.session.set_expiry(0) -
can I use the slug from a different urls.py file?
I'm trying to access a slug field from a different urls.py file, and I'm getting this error FieldError at /new-api/tournaments/fifa-world-cup/teams/ Unsupported lookup 'custom_url' for ForeignKey or join on the field not permitted. I'm wondering if the reason I'm getting this error is because you cant do that or if it's another reason I have 2 files for urls, one includes the other in it, urls.py (tournament) urlpatterns = [ path("", views.getNewTournaments, name="tournaments"), path("<slug:custom_url>/", views.getNewTournament, name="tournament"), path("create/", views.postNewTournament, name="post-tournament"), path("<slug:custom_url>/teams/", include("teams.urls"), name="tournament-teams"), ] urls.py (teams) urlpatterns = [ path("", views.teams.as_view(), name="teams"), ] Here are the views.py files views.py (tournaments) @api_view(["GET"]) def getNewTournaments(request): tournaments = NewTournament.objects.all() serializer = NewTournamentSerializer(tournaments, many=True) return Response(serializer.data) views.py (teams) class teams(APIView): def get(self, request, custom_url): teams = Team.objects.filter(tournament__custom_url=custom_url) serializer = TeamSerializer(teams, many=True) return Response(serializer.data) -
Django JWT authentication TokenObtainPairView issue
I am trying to use CustomTokenObtainPairView to receive my username in token. #views: `if user.check_password(password): # refresh = RefreshToken.for_user(user) # refresh.access_token['username'] = user.username # token = str(refresh.access_token) request.data = { 'username': username, 'password': password } token_response = CustomTokenObtainPairView.post(request=request.data) response = Response() response.set_cookie(key='jwt', value=token_response.data['access'], httponly=True, secure=True) response.data = { 'access': token_response.data['access'] } return response else: return Response({'message': 'Wrong password!'}, status=400)` I tried to generate token and adding username in it but it didnot work. If anybody knows how to use TokenObtainPairView in correct way in your function please help. -
How to properly assign a value to a Django choice field
I am trying to assign a value to a ChoiceField in a Django form. # forms.py MONTH_CHOICES = ( ("JANUARY", "January"), ("FEBRUARY", "February"), #... ("DECEMBER", "December"), ) class SomeMonthSelectingform(forms.Form): month = forms.ChoiceField(choices=MONTH_CHOICES) def __init__(self, *args, **kwargs): month = kwargs.pop("month") super(SomeMonthSelectingform, self).__init__(*args, **kwargs) self.fields['month'] = month The selected value of the choice field named month should be the actual month (e.g. right now it would be 'JULY') # views.py def month_view(request: HttpRequest): month = datetime.now().month monthIndex = month - 1 monthChoice = MONTH_CHOICES[monthIndex][0] monthForm = SomeMonthSelectingform(month=monthChoice) if request.method == 'POST': filledForm = SomeMonthSelectingform(data=request.POST) if not filledForm.is_valid(): raise Exception("Month form was invalid") monthForm = filledForm args = { 'monthForm': monthForm } return render(request, 'month.html', 'args') <!-- month.html --> {% extends 'base.html' %} {% block content %} <h2>Month</h2> <form action="{% url '...' %}" method="post"> {% csrf_token %} {{ monthForm }} <input type="submit" name="..." value="Show"> </form> {% endblock %} Sadly, I keep getting the error 'str' object has no attribute 'get_bound_field'. I am quite sure it is because, I should not assign 'JULY' to self.fields['month'] inside the constructor of the form. But I can not find another solution. -
How To Redirect In Post Request Response
i wanna redirect to success page but it seems i should use different way in post request response. views.py : def uploader(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): return redirect("download",link = 'test') else: form = UploadFileForm() return render(request, 'uploader/pages/upload.html', {'form': form}) def downloader(request,link) : return render(request, 'uploader/pages/download.html',) urls.py : urlpatterns = [ re_path(r'^admin/', admin.site.urls), re_path(r'^$', views.uploader, name='upload'), re_path(r'^(?P<link>[\w-]+)/', views.downloader, name='download'), ] log in terminal : [27/Jul/2024 17:43:37] "POST / HTTP/1.1" 302 0 [27/Jul/2024 17:43:37] "GET /test/ HTTP/1.1" 200 46 I've tried HttpResponseRedirect('test') and HttpResponseRedirect(reverse('download', kwargs={'link': 'link'})) to -
How to implement Bootstrap Card Layout in Django: Achieving Desired Design vs. Current Output
I'm working on a Django application. I'm mostly working on the backend because of that in the frontend I'm terrible. I want to create a page that contains a couple of cards. I want to create this structure in the image-1 but I'm able to create image-2. I'll attach my code, can you help me to implement the first image? (the images in the picture is not important they can change) I'm using bootstrap 4.6 <div class="col-lg-5 col-md-12"> <img class="ca-icon" src="{% static 'images/list-icon.svg' %}" alt="List"> <div class="row ca-border mb-3 align-items-center ca-side-context"> <div class="col-6 "> <div class="row">Text-1</div> <div class="row "><img class="icon sound-icon" src="{% static 'images/sound-icon.svg' %}" alt="Sound Icon"></div> </div> <div class="col-6 ca-border"><img class="img-fluid" src="{% static 'images/temp.png' %}" alt="List"></div> </div> <img class="ca-icon" src="{% static 'images/parent-icon.svg' %}" alt="List"> <div class="row ca-border mb-3 align-items-center ca-side-context"> <div class="col-6 "> <div class="row">Text-2</div> <div class="row "><img class="icon sound-icon" src="{% static 'images/sound-icon.svg' %}" alt="Sound Icon"></div> </div> <div class="col-6 ca-border"><img class="img-fluid" src="{% static 'images/temp.png' %}" alt="List"></div> </div> </div> <style> .ca-border { border: 12px solid #ffdd43; border-radius: 20px; padding: 10px; } .ca-icon { width: 10%; height: 10%; } .sound-icon { width: 50%; height: 50%; } .play-icon{ width: 90%; height: 90%; } .clock-icon{ width: 50%; height: 50%; } .subject-title { margin-left: … -
Why Gemini API function calling response using old function definition even after changing tools in genai.GenerativeModel?
I want to build a django application that uses Google Gemini API at the backend. The challenge I have is that , the function call parameters change ( though very rarely ) based on a database entry. consider I have an enum as input arg to the function and whenever a new row is created I want to add new enum to this function definition. so this change take place quickly. but unfortunately this doesn't happen, instead the Gemini responds with response that looks it doesn't know about the change. Note I have configured the the flow to call genai.GenerativeModel for every new request and verified that self.function_collection.getdef() returns the updated function definition when I update the a row. self.model = genai.GenerativeModel( model_name=config('GEMINI_MODEL_NAME'), generation_config={ "temperature":config('TEMPERATURE',cast=float), "top_p": config('TOP_P',cast=int), "top_k": config('TOP_K',cast=int), "max_output_tokens": config('MAX_OUTPUT_TOKENS',cast=int), "response_mime_type": "text/plain", }, tools=[{ 'function_declarations': self.function_collection.getdef(), }], ) If I restart django development server this change will be quickly considered. but I can't do this in production. Also I have verified this change is available to the model using the following chat_session = self.model.start_chat(history=self.history) print("tools avaialbe",self.model._tools.to_proto()) print("function def",self.function_collection.getdef()) print("tools avaialbe in session before ",chat_session.model._tools.to_proto()) response = chat_session.send_message(query) print("tools avaialbe in session after ",chat_session.model._tools.to_proto()) I verified that the updated function … -
Django send just an alter in response instead of a full template
How can I send just an alert message in response to a request instead of having to send a template made just for the alert? I am using Javascript async call. I only need the alert html response to render an InnerHTML. View @login_required(login_url="/login/") @csrf_protect def usersave(request): msg = messages.add_message(request, messages.WARNING, "This is a demo. First complete all info to save.") return render(request, msg) # Want to send just msg instead of a template for an alert. -
Django modal window
I have a modal window for deleting comments. It looks like this: <div id="deleteModal" class="modal"> <div class="modal-content"> <img class="modal-image" src="{% static 'img/icon-modal-delete.png' %}" alt="DELETE"> <h1 class="modal-title">Delete comment?</h1> <div class="modal-block"> <form method="POST"> {% csrf_token %} <button class="modal-sucsess" type="submit">Delete</button> </form> <a class="modal-cancel" onclick="closeModal()">Cancel</a> </div> </div> </div> I include it with the include tag in the django template. There is also a js script for opening and closing the modal window, which looks like this: function openModal() { var modal = document.querySelector('.modal'); modal.style.display = 'block'; } function closeModal() { var modal = document.querySelector('.modal'); modal.style.display = 'none'; } In the django template I have a cycle where I display comments to the publication and each comment has a delete button, which on click calls a modal window, it looks like this: <a class="main-row-content-comments-users-info-delete" onclick="openModal()" >Delete</a> I wrote a view to delete a comment, but it needs to pass the comment id. If I were doing this directly via a link in a template tag, I would simply pass comment.pk, but how do I pass the key to the modal so that when I click the delete button in the modal, the delete view is called? I tried to solve this using Ajax requests, but … -
Lightsail deployment logging; Invalid HTTP_HOST header:You may need to add '****' to ALLOWED_HOSTS
I am deploying a containerised application on Lightsail and whilst the deployment itself is successful, logging shows hundreds of these messages from the same ip address, my assumption is this is some sort of automated process that's failing. I have set the allowed_hosts to just the Lightsail generated url (w/o https//.com etc.) and so I have no idea where this extra ip is coming from. I can't find anything which says I need to have an extra ip on allowed_hosts. Tried to deploy containerised application to Lightsail -
I cant understand this python script clearly?
Python script to load .dat files import csv from django.core.management.base import BaseCommand from recommender.models import User, Artist, Tag, UserArtist, UserTaggedArtist, UserFriend import os from django.conf import settings # Define the path to the database directory Database_path = os.path.join(settings.BASE_DIR, 'mldata') class Command(BaseCommand): help = 'Load data from .dat files into the databases' def handle(self, *args, **kwargs): self.create_default_users() self.load_artists() self.load_tags() self.load_user_artists() self.load_user_tagged_artists() self.load_user_friends() def create_default_users(self): users = [ {'username': 'User1', 'email': 'user1@example.com'}, {'username': 'User2', 'email': 'user2@example.com'} ] for user in users: User.objects.get_or_create(username=user['username'], email=user['email']) def load_artists(self): with open(os.path.join(Database_path, 'artists.dat'), 'r', encoding='utf-8', errors='replace') as file: reader = csv.reader(file, delimiter='\t') next(reader) for row in reader: artist_id, artist_name = row[0], row[1] Artist.objects.get_or_create(artist_id=artist_id, defaults={'artist_name': artist_name}) def load_tags(self): with open(os.path.join(Database_path, 'tags.dat'), 'r', encoding='utf-8', errors='replace') as file: reader = csv.reader(file, delimiter='\t') next(reader) for row in reader: tag_id, tag_name = row[0], row[1] Tag.objects.get_or_create(tag_id=tag_id, defaults={'tag_name': tag_name}) def load_user_artists(self): with open(os.path.join(Database_path, 'user_artists.dat'), 'r', encoding='utf-8', errors='replace') as file: reader = csv.reader(file, delimiter='\t') next(reader) for row in reader: user_id, artist_id, listening_count = row[0], row[1], row[2] user = User.objects.get(id=user_id) artist = Artist.objects.get(artist_id=artist_id) UserArtist.objects.get_or_create(user=user, artist=artist, defaults={'listening_count': listening_count}) def load_user_tagged_artists(self): with open(os.path.join(Database_path, 'user_taggedartists.dat'), 'r', encoding='utf-8', errors='replace') as file: reader = csv.reader(file, delimiter='\t') next(reader) for row in reader: user_id, artist_id, tag_id, timestamp = row[0], row[1], row[2], row[3] user … -
Cannot display image with JavaScript from Django Base
I am attempting to get a customer logo to load when a user signs into my app. To do that I am using the views function below to generate the logo url: Views: def view_company_logo(request): print("GETTING LOGO") client = Client.objects.get(user=request.user) logo = "" try: logo = client.customer.first().logo.logo.url print("GOT LOGO") return JsonResponse({"logo": logo, "media_url": settings.MEDIA_URL}, safe=False) except Exception as e: print(e) print(f'ERROR FOR LOGO {e}') return JsonResponse({"logo": logo}, safe=False) The function is attached the url below: url(r"^get/company_logo/$", views.view_company_logo), This is called in the base.html file in order to show the $(document).ready(function () { document.getElementById("logo").src = get_company_logo(); function get_company_logo() { log('TEST'); $.ajax({ url: '/get/company_logo/', method: 'GET', success: function (data) { console.log(data); console.log(data['logo']); return data.logo }, error: function () { console.log('HERE IS THE ERROR!!!') log('HERE IS THE ERROR!!!') }, }) } Which connects to the source of this image that gets generated when the pages loads: <img class="img-square center" id="logo" alt="logo" style="opacity: 1" height="45" width="125"> Could someone tell me why the image is not loading? It seems like the function is never called and I am not sure why. -
Problem with authentication of login in Django
When trying to authenticate a user using the "authenticate" method, it won't let me log in. I don't know if it is because the authentication method no longer works in new versions of django, or if another method is used. I'm new to django, so I'm just learning: def signin(request): if request.method == 'GET': return render(request, 'signin.html', { 'form': AuthenticationForm }) else: # POST user = authenticate(request, username=request.POST['username'],password=request.POST['password']) if user is None: return render(request, 'signin.html', { 'form': AuthenticationForm, 'error': 'Username or password is incorrect' }) else: login(request, user) return redirect('tasks') In the login template, the indicated method is POST, so that is not the problem there.I tried to change the login name to avoid any conflict, and it was not resolved. -
Count by Month in Django Query
Good afternoon, I am struggling with a query. Ultimately, I have some records I want to query and get a count by month. Ultimately, my goal is to come up with a data set that looks like: Month, opened, closed Jan, 2, 3 Feb, 1, 5 Etc... for the past six months. I have been using this as a base: Django: Query Group By Month This works to get each individually: six_months_ago = datetime.now() - timedelta(days = 180) open_six_months = (Rec.objects .annotate(open=Month('open_date')) .values('open') .annotate(rec_opened=Count('status', filter=Q(status__is_open=True))) .order_by()) closed_six_months = (Rec.objects .annotate(closed=Month('close_date')) .values('closed') .annotate(rec_closed=Count('status', filter=Q(status__is_open=False) and Q(close_date__isnull=False) )) .order_by()) Not all records have a closed date yet. This returns the right data when testing, but its in two different queries. I'd like to have one single data set if possible. Is there an easy way to combine this into one query that has a single row with both the count of the open date and the count of the closed date by month? Thank you for your help. BCBB -
Why can't I save the Django FileField with a null value
I want to use a POST request to create an object with file fields. At the same time, at the model level, I declared that fields can be null. But Django does not allow me to save this object with empty values in the file fields. At the same time, through Django admin, I can create an object with without specifying a file. Error: ValueError: The 'image_before' attribute has no file associated with it. What could this be related to? My request: { "type": "Type", "question": "Text", "category": [ 1 ] } My model: class Question(models.Model): class Meta: db_table = 'questions' question_type = models.CharField( max_length=300, ) category = models.ManyToManyField( Category, ) question_text = models.CharField( max_length=300, ) image_before = models.ImageField( upload_to='media/', null=True, blank=True, default=None, ) correct_answer= models.CharField( max_length=300, blank=True ) I tried to redefine save() and change the value of the field to None there. Then the value of the field will be <FileField: None> -
Mutliple JWT generation with different django secrets based on subdomains
I am using simple JWT (django-rest-framework-simplejwt). I have an auth server which authenticates users. Each user can belong to a single or multiple Tenants and each tenant is represented by a subdomain. I am trying to generate django secret for each tenant and when the tenant docker launches it uses the django secret generated by the auth server(i store it in .tenant1.local.env for tenant one) So when a user tries to connect to a domain, system will create auth token using the secret generated for that tenant. Since that tenant will have an access to .tenant.local.env (same secret that was used to generate the token for that tenant) it ll be able authenticate the users using the secret. The issue is I can not find a simple way to inherit or overwrite a class in django-rest-framework-simplejwt so that I can specify the secret to use to create the token. There is APISettings(which you specify which secrets to use) in the package but there is no example of how to use it. IS there a way to specify which secrets to use per access token generation request instead of initializing the whole API for each request. -
I am recieving a NoReverseMatch error does anyone know what I'm doing wrong?
Im trying to allow the user to edit an existing entry. But when I include new_entry.html `{% extends "learning_logs/base.html" %} {% block content %} <p> <a href="{% url 'learning_logs:topic' topic.id %}">{{ topic }}</a></p> <p>Add a new entry:</p> <form action="{% url 'learning_logs:new_entry' topic.id %}" method='post'> {% csrf_token %} {{form.as_div}} <button name='submit'>Add entry</button> </form> {% endblock content %}` The site throws a NoReverseMatch at /topics/1/ Not too sure where to start looking to solve this issue. Still fairly new to django. Rest of my code bellow views.py def new_entry(request, topic_id): """Add a new entry for a particular topic.""" topic = Topic.objects.get(id=topic_id) if request.method !='POST': #No data submitted; reate a blank form form = Entry() else: #POST data submitted; process data form =EntryForm(data=request.POST) if form.is_valid(): new_entry = form.save(commit=False) new_entry.topic = topic new_entry.save() return redirect('learning_logs:topic', topic_id=topic_id) #Display a blank or invalid form context = {'topic': topic, 'form': form} return render(request, 'learning_logs/new_entry.html', context) urls.py app_name = 'learning_logs' urlpatterns = [ #Home page path('', views.index, name='index'), #Page that shows all topics. path('topics/', views.topics, name='topics'), #Detail page for a single topic path('topics/<int:topic_id>/', views.topic, name='topic'), #Page for adding a new topic path('new_topic/', views.new_topic, name='new_topic'), #Page for adding a new entry path('new_entry/<int:topic_id>/', views.new_entry, name='entry'), ] -
auto-py-to-exe expected str, bytes or os.PathLike object, not NoneType
I'm using auto-py-to-exe to convert my django project in an exe file but I couldn´t: traceback: Running auto-py-to-exe v2.44.1 Building directory: C:\Users\gerar\AppData\Local\Temp\tmp92y6g42v Provided command: pyinstaller --noconfirm --onefile --windowed --add-data 674780 INFO: PyInstaller: 6.9.0, contrib hooks: 2024.7 674795 INFO: Python: 3.12.4 674797 INFO: Platform: Windows-11-10.0.22631-SP0 674813 INFO: Python environment: C:\Users\gerar\AppData\Local\Programs\Python\Python312 674828 INFO: wrote C:\Users\gerar\AppData\Local\Temp\tmp92y6g42v\manage.spec 674837 INFO: Module search paths (PYTHONPATH): ['C:\Users\gerar\AppData\Local\Programs\Python\Python312\Scripts\auto-py-to-exe.exe', File "C:\Users\gerar\AppData\Local\Programs\Python\Python312\Lib\site-packages\PyInstaller\compat.py", line 583, in importlib_load_source mod_loader.exec_module(mod) File "", line 995, in exec_module File "", line 488, in _call_with_frames_removed File "C:\Users\gerar\AppData\Local\Programs\Python\Python312\Lib\site-packages\PyInstaller\hooks\hook-django.py", line 71, in mod_dir = os.path.dirname(hooks.get_module_file_attribute(mod_name)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "", line 277, in dirname File "", line 241, in split TypeError: expected str, bytes or os.PathLike object, not NoneType Project output will not be moved to output folder Complete. -
Attempting to put data from database onto dashboard in Django
So I am following this guide: https://www.youtube.com/watch?v=_sWgionzDoM and am at around 55 mins so far I have the login stuff all working however I am unable to get the dashboard to show my data from the database. The table does show on the admin page with the data however when I go to my dashboard for the user it does not show. Here is the code of my dashboard. {% extends 'page.html' %} {% block content %} {% if messages %} <div class="row mt-3"> {% for message in messages %} {% if message.tags == 'error' %} <div class="col-md-10 col-12 mx-auto alert alert-danger"> {{ message }} </div> {% else %} <div class="col-md-10 col-12 mx-auto alert alert-success"> {{ message }} </div> {% endif %} {% endfor %} </div> {% endif %} <div class="row"> <div class="col-md-10 col-12 mx-auto mt-5"> <div class="d-flex justify-content-end"> <a href="{% url 'main' %}" class="btn btn-primary">+</a> </div> <table class="table table-hover table-striped"> <thead> <tr> <th scope="col">ID</th> <th scope="col">Name</th> <th scope="col">Qty</th> <th scope="col">Category</th> <th scope="col"></th> <th scope="col"></th> </tr> </thead> <tbody> {% if items|length == 0 %} <tr> <th scope="row">-</th> <td>no data</td> <td>-</td> <td>-</td> <td>-</td> <td></td> </tr> {% endif %} {% for item in items %} <tr> <th scope="row">{{ item.id }}</th> <td>{{ item.name … -
How To Register Model For Admin Page in Core App?
I defined a model (File) in core app(uploader) and tried to register it for admin page but didnt work. then i tried adding core apps name to installed_apps in setting . after that admin page shows model but when i open it it shows : no such table: uploader_file settings.py : INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'uploader' ] views.py : class uploader(View) : def get(self, request) : return render(request, "uploader/pages/upload.html", context={'form': UploadFileForm()}) @method_decorator(csrf_exempt) def post(self, request) : form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): messages.success(request, 'File uploaded successfully!') return redirect('download',link = 'link') messages.error(request, 'Error uploading file.') return render(request, 'uploader/pages/upload.html', {'form': form}) models.py : class File(models.Model) : link = models.CharField(max_length=38) fileField = models.FileField() allowed = models.JSONField() class Meta: app_label = 'uploader' admin.py : from django.contrib import admin from .models import File admin.site.register(File) -
Error while trying to connect Django With ReactNative
I am building a React Native app with Django as the backend. I have set up the login screen in React Native and configured JWT authentication with rest_framework_simplejwt in Django. However, I encounter an error when trying to log in. Within the login screen: const [username, setUsername] = useState(""); const [password, setPassword] = useState(""); const [error, setError] = useState(""); const handleSubmission = async () => { try { const response = await axios.post("http://127.0.0.1:8080/api/token/", { username, password, }); if (!response || !response.data) { throw new Error("Invalid server response"); } await AsyncStorage.setItem("accessToken", response.data.access); await AsyncStorage.setItem("refreshToken", response.data.refresh); navigation.navigate("Tab"); } catch (error) { console.error("error", error); const errorMessage = error.response && error.response.data && error.response.data.message ? error.response.data.message : "Whoops! Log In Failed, please try again later 😅."; setError(errorMessage); } }; In Django, views: @api_view(['POST']) @permission_classes([IsAuthenticated]) def create_user(request): serializer = CreateUserSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response({'message': "Whoops! error while creating user 🫣", 'error': serializer.errors}, status=status.HTTP_400_BAD_REQUEST) Serializers: class CreateUserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['username', 'password'] def create(self, validated_data): validated_data['password'] = make_password(validated_data.get('password')) return super(CreateUserSerializer, self).create(validated_data) and I set up cors in settings.py so that I can make API request on my machine: INSTALLED_APPS = [ 'corsheaders', # DEV ONLY ... ] MIDDLEWARE = … -
Heroku DB Connection Limit hit when using Python ThreadPoolExecutor
I have a Django app hosted on Heroku. Some user requests to this app require making long-running queries to external resources. In order to get around the Heroku 30 request timeout, I created a system where these long running queries are given unique IDs and handed to a Python ThreadPoolExecutor so as not to hold off the query. The original query returns immediately and the font end JS code periodically checks in for a results. This system is working great but since deploying that change I routinely get "FATAL: too many connections" errors from my app. It appears as though the automatic connection management Django provides doesn't work when ThreadPoolExecutors are in use. Unfortunately I have to have access to the DB from the spawned thread in order to save the results of the long-running query. Any recommendation as to how I can fix this so DB connections are managed correctly? -
I can't open server in 0.0.0.0 instead it is working in 127.0.0.1 in while using Docker , Django and Postgres
I am a newbie to this. settings.py file is: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'password', 'HOST': 'db', 'PORT': 5432, } } Docker file is: FROM python:3 ENV PYTHONUNBUFFERED=1 COPY . /usr/src/app WORKDIR /usr/src/app RUN pip install -r requirements.txt CMD ["python3", "manage.py", "runserver", "0.0.0.0:8000"] Docker compose file is: version: '3.8' services: db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data environment: POSTGRES_DB: postgres POSTGRES_USER: postgres POSTGRES_PASSWORD: password container_name: postgres_db web: tty: true command: python3 manage.py runserver 0.0.0.0:8000 build: . volumes: - .:/usr/src/app ports: - 8000:8000 container_name: django_container environment: POSTGRES_USER: postgres POSTGRES_PASSWORD: password POSTGRES_HOST: db depends_on: - db requirements.txt file is: Django psycopg2 docker-compose build docker-compose up docker exec -it django-container bash -l python manage.py migrate docker-compose ps is run and this is the output: ml: versionis obsolete" NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS django_container airline-web "python3 manage.py r…" web 4 minutes ago Up 48 seconds 0.0.0.0:8000->8000/tcp postgres_db postgres "docker-entrypoint.s…" db 3 hours ago Up 48 seconds 5432/tcp above were run server is running in 127.0.0.1:8000 instead of 0.0.0.0:8000. Am I missing something. I am a newbie to this. -
Custom email validation in django form
In my django Account app I have a model for AccountI class Account(AbstractBaseUser): wallet_value = models.DecimalField(max_digits=10, decimal_places=2, default=0.00) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) username = models.CharField(max_length=100) email = models.EmailField(max_length=200, unique=True) phone_number = models.CharField(max_length=20) """SOME OTHER REQUIED FIELD""" date_joined = models.DateTimeField(auto_now_add=True) last_login = models.DateTimeField(auto_now_add=True) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_superadmin = models.BooleanField(default=False) is_active = models.BooleanField(default=False) USERNAME_FIELD = "email" REQUIRED_FIELDS = ["first_name", "last_name", "username"] I also have a Registration form which is responsible for signup feature class RegistrationForm(forms.ModelForm): password = forms.CharField( widget=forms.PasswordInput( attrs={ "class": "form-control", } ) ) confirm_password = forms.CharField( widget=forms.PasswordInput(attrs={"class": "form-control"}) ) first_name = forms.CharField( widget=forms.TextInput( attrs={ "placeholder": "Enter First Name", "class": "form-control", } ) ) last_name = forms.CharField( widget=forms.TextInput( attrs={"placeholder": "Enter Last Name", "class": "form-control"} ) ) email = forms.CharField( widget=forms.EmailInput( attrs={ "placeholder": "Enter Email Adress", "class": "form-control", } ) ) phone_number = forms.CharField( widget=forms.NumberInput( attrs={"placeholder": "Enter Phone Number", "class": "form-control"} ) ) class Meta: model = Account fields = [ "first_name", "last_name", "email", "phone_number", "password", "confirm_password", ] def __init__(self, *args, **kwargs): super(RegistrationForm, self).__init__(*args, **kwargs) def clean(self): cleaned_data = super(RegistrationForm, self).clean() password = cleaned_data.get("password") confirm_password = cleaned_data.get("confirm_password") if password != confirm_password: raise forms.ValidationError( "password dose not match", ) and in my views.py which will handle registeration I … -
I get an error while running django project [closed]
Manage.py file looks like this: #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main() The terminal executes like this: (venv) PS C:\Users\Administrator\myproject> python manage.py runserver C:\Program Files\Python311\python.exe: can't open file 'C:\\Users\\Administrator\\myproject\\manage.py': [Errno 2] No such file or directory. I followed everystep in the documentation but I constantly receive the error. I am using windows.