Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Send variable to Django crispy forms
I have a Django Crispy form defined in views.py: @login_required def PostCreate(request): if request.method == 'POST': form = PostFileForm(request.POST or None, request.FILES or None) files = request.FILES.getlist('file') if form.is_valid(): post = form.save(commit=False) post.author = request.user form.instance.author = request.user etc. and post_form.html: {% extends "blog/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <button class="btn btn-outline-info" id="audit" onclick="audit()">Basic</button> <form method="POST" id="PostForm" data-sektor-url="{% url 'ajax_load_sektors' %}" data-department-url="{% url 'ajax_load_departments' %}" data-person-url="{% url 'ajax_load_persons' %}" novalidate enctype="multipart/form-data"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4" style="color:red;">Order</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" id="submit" type="submit">Submit</button> </div> </form> in my models.py I have defined all models I need for the full form. Depending on the 4 buttons which user can click to call the form, that form should have some fields hidden/shown or autofilled. I hide them using Javascript, for example: <script type="text/javascript"> function on_load(){ document.getElementById('hidden_on_open').style.display = 'none'; My problem is, I don't know which button is pressed. Is there a way to 'pass a static variable' or something to the HTML, since if I pass it to views.py it's already rendered? So that I can use Javascript to hide/show and autofill certain fields depending on that variable. Just … -
Django ORM efficient way for annotating True on first occurrences of field
I have a situation where we have some logic that sorts a patient_journey queryset (table) by some heuristics. A patient_journey has a FK to a patient. I now need an efficient way of setting True for the first occurrence of a patient_journey for a given patient, false otherwise. The first heuristinc is patient_id so the queryset will already by grouped by patient. The algorithm is v straight forward & should be fast, yet I'm stuck at trying to get something <1s. I've tried using distinct and checking for existence, however that's adding 1-2s. I've tried using a subquery with [:1] & test on id, but that's even worse around 3-5s extra. def annotate_primary( *, qs: 'PatientJourneyQuerySet' # noqa ) -> 'PatientJourneyQuerySet': # noqa """ Constraints: -------------- Exactly One non-global primary journey per patient Annotations: ------------ is_primary_:Bool, is the primary_journey for a patient """ from patient_journey.models import PatientJourney qs = get_sorted_for_primary_journey_qs(qs=qs) # cost until now is around 0.17s # using distinct on patient_id & checking if id is in there adds around 1.5-2s # looking for something faster, i.e. this shoiuld be a straight forward scan. qs = qs.annotate( # True for first occurrence of a `patient_id` false otherwise primary= ) … -
"detail": "Authentication credentials were not provided." postman django
Trying to do authorization on tokens When I make a POST request through postman it gives an error "detail": "Authentication credentials were not provided." REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ], 'DEFAULT_PARSER_CLASSES':[ 'rest_framework.parsers.JSONParser', ], 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', #'rest_framework.authentication.SessionAuthentication', #'rest_framework_simplejwt.authentication.JWTAuthentication', ] manager.py from django.contrib.auth.models import BaseUserManager from django.core.exceptions import ValidationError from django.core.validators import validate_email from django.utils.translation import gettext_lazy as _ class UserManager(BaseUserManager): def email_validator(self, email): try: validate_email(email) except ValidationError: raise ValueError(_("please ener a valid email")) def create_user(self, email, username, password, **extra_fields): if email: email=self.normalize_email(email) self.email_validator(email) else: raise ValueError(_("an email adress is required")) if not username: raise ValueError(_("an username is required")) user=self.model(email=email, username=username, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, password, **extra_fields): extra_fields.setdefault("is_staff", True) extra_fields.setdefault("is_superuser", True) extra_fields.setdefault("is_verified", True) if extra_fields.get("is_staff") is not True: raise ValueError(_("is staff must be true for admin user")) if extra_fields.get("is_superuser") is not True: raise ValueError(_("is superuser must be true for admin user")) user = self.create_user( email, username, password, **extra_fields ) user.save(using=self._db) return user views.py from django.shortcuts import render from rest_framework.generics import GenericAPIView from .serializers import UserSerializer from rest_framework.response import Response from rest_framework import status from .utils import send_code_to_user class RegisterUserView(GenericAPIView): serializer_class=UserSerializer def post(self, request): user_data=request.data serializer=self.serializer_class(data=user_data) if serializer.is_valid(raise_exception=True): serializer.save() user=serializer.data send_code_to_user(user['email']) return Response({ 'data':user, 'message':f'hi{user.username}' }, … -
Azure Appservice for Django fails with Azure Devops Pipeline
I have an appservice running on Azure in a Linux environment. I try to associate it with a Azure Devops Pipeline so I can have CI/CD for the repositories & branches on Github. I want the builds to occur on Azure Pipeline & Azure infrastructure, not Github Actions. I have tried all other suggestions including following environment variables on App Service : SCM_DO_BUILD_DURING_DEPLOYMENT=true WEBSITE_NODE_DEFAULT_VERSION=~18 WEBSITE_RUN_FROM_PACKAGE=true Here is the logs that I receive from the Kudu / Azure Devops Pipeline / AppService logs : /home/LogFiles/2024_08_14_ln1xsdlwk0000K3_docker.log (https://project-app-development.scm.azurewebsites.net/api/vfs/LogFiles/2024_08_14_ln1xsdlwk0000K3_docker.log) 2024-08-14T23:51:45.168Z INFO - Status: Image is up to date for 10.1.0.6:13209/appsvc/python:3.10_20240619.2.tuxprod 2024-08-14T23:51:45.179Z INFO - Pull Image successful, Time taken: 0 Seconds 2024-08-14T23:51:45.223Z INFO - Starting container for site 2024-08-14T23:51:45.223Z INFO - docker run -d --expose=8000 --name project-app-development_0_f2e0544d -e WEBSITE_USE_DIAGNOSTIC_SERVER=false -e WEBSITE_SITE_NAME=project-app-development -e WEBSITE_AUTH_ENABLED=False -e WEBSITE_ROLE_INSTANCE_ID=0 -e WEBSITE_HOSTNAME=project-app-development.azurewebsites.net -e WEBSITE_INSTANCE_ID=3f627dbbecdaed255d87aa9c3e8f1448758df1cdff41f5e14b114384ea9b244a appsvc/python:3.10_20240619.2.tuxprod gunicorn -b :$PORT project.wsgi 2024-08-14T23:51:45.223Z INFO - Logging is not enabled for this container. Please use https://aka.ms/linux-diagnostics to enable logging to see container logs here. 2024-08-14T23:51:45.893Z INFO - Initiating warmup request to container project-app-development_0_f2e0544d for site project-app-development 2024-08-14T23:51:49.043Z ERROR - Container project-app-development_0_f2e0544d for site project-app-development has exited, failing site start 2024-08-14T23:51:49.057Z ERROR - Container project-app-development_0_f2e0544d didn't respond to HTTP pings on port: 8000, failing site … -
How do I use prefetch_related for Generic Relationship in Django?
I've multiple models. Model1, Model2, Model3, ... Each model requires multiple let's say feature/images. Can be implemented by making different Image models ( i.e. Morel1Image ) then link with foreign key. Or, Make a Generic Image Model and use it wherever it needs. The problem is, I'm having similar queries ( debug ). And prefect_related isn't working ( Django might not have the feature ). Now how do I solve the problem ( efficiently ) ? I'm expecting no similar or duplicate quary. -
Using formset in django formtool
am creating a 8 steps form wizard. 2 of the models are Qualification and SSCE and i used formset to create multiple forms inputs Formset factory QualificationsFormSet = modelformset_factory(Qualifications, form=QualificationsForm, extra=5) SscesFormSet = modelformset_factory(Ssces, form=SSCESubjectForm, extra=5) the View class StudentWizard(LoginRequiredMixin, SessionWizardView): form_list = FORMS # template_name = 'admission/form_wizard.html' file_storage = FileSystemStorage(location='/tmp/') def get_form(self, step=None, data=None, files=None): if step is None: step = self.steps.current form = super().get_form(step, data, files) form.request = self.request if step == '3': form = QualificationsFormSet(data, queryset=Qualifications.objects.none()) elif step == '4': form = SscesFormSet(data, queryset=Ssces.objects.none()) return form def get_form_instance(self, step): print(f"Current step: {step}") if step == '4': # SSCE step qualifications = self.get_cleaned_data_for_step('3') print(f"Qualifications data: {qualifications}") if qualifications: certificates = [qual['certificate_obtained'] for qual in qualifications] print(f"Certificates: {certificates}") if not any(cert in ['WASC', 'SSCE', 'NECO', 'GCE'] for cert in certificates): print("Skipping SSCE step") return None # Skip the Ssces formset return super().get_form_instance(step) def get_context_data(self, form, **kwargs): context = super().get_context_data(form=form, **kwargs) if self.steps.current in ["3", "4"]: context['formset'] = form context['formset_with_widgets'] = [ [(field, field.field.widget.__class__.__name__) for field in form] for form in context['formset'].forms ] else: context['fields_with_widgets'] = [ (field, field.field.widget.__class__.__name__) for field in form ] return context the problem is that the other forms works well upto the Qualification where after … -
Django admin popup window not closed after the form submitted successfully
I have a computed field(add_workplace_link) in display_list to open a popup window in order to add new instance of Workplace model. The popup window opens as expected. After form submitted successfully, the window remains open an empty page. models.py from django.db import models class Company(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name class Workplace(models.Model): title = models.CharField(max_length=255) company = models.ForeignKey(Company, on_delete=models.CASCADE) def __str__(self): return self.title admin.py @admin.register(Company) class CompanyAdmin(admin.ModelAdmin): list_display = ['name', 'add_workplace_link'] def add_workplace_link(self, obj): # Generate the URL to the Workplace add form with the company preselected url = reverse('admin:appname_workplace_add') + f'?company={obj.pk}' return format_html('<a href="{}">Add Workplace</a>', url) add_workplace_link.short_description = 'Add Workplace' class WorkplaceAdmin(admin.ModelAdmin): list_display = ['title', 'company'] def get_form(self, request, obj=None, **kwargs): form = super().get_form(request, obj, **kwargs) # Check if we have the company parameter in the URL and set the initial value if 'company' in request.GET: company_id = request.GET.get('company') form.base_fields['company'].initial = company_id return form Admin changelist for Company model popup window opened as expected popup window remains open after form submitted successfully I already checked to make sure RelatedObjectLookups.js is loaded in popup window. I expect the popup window close automatically after form submitted successfully. What is missing? -
How i run a program in background in django without loading page
i am working on a project which has a function which generate response automatically on loop using google gemini api and show it to the html page by saving it to the database, i want this function to run in background all the time without loading the page Currently what is happening is, if the function is generating 10 response in a loop then it is keep loading the page until all response get generated and then it is showing me home.html page. Someone told me to use command management and i made the command, but i dont know how this command is going to run a function automatically in background on starting a server. i am providing a example command code, suppose i want to run it in background withouth loading a page, what should i do. from django.core.management.base import BaseCommand from main.models import Data1 data1 = Data1.objects.all() class Command(BaseCommand): help = 'Displays stats related to Article and Comment models' def handle(self, *args, **kwargs): for data_test in data1: print(data_test) -
How to get an attribute of a serializer class in DRF?
I have a serializer class CourseSerializer. A course can have a number of groups, lessons and etc.. A code for a serializer: class CourseSerializer(serializers.ModelSerializer): lessons = MiniLessonSerializer(many=True, read_only=True) lessons_count = serializers.SerializerMethodField(read_only=True) students_count = serializers.SerializerMethodField(read_only=True) groups_filled_percent = serializers.SerializerMethodField(read_only=True) demand_course_percent = serializers.SerializerMethodField(read_only=True) def get_lessons_count(self, obj) -> int: return obj.lessons.count() def get_students_count(self, obj) -> int: amount = Subscription.objects.filter().count() return amount def get_groups_filled_percent(self, obj) -> int: counts = [group.users.count() for group in obj.groups.all()] return ((sum(counts) / len(counts)) / 30) * 100 def get_demand_course_percent(self, obj) -> int: users = CustomUser.objects.all().count() students = Subscription.objects.filter().count() return (students / users) * 100 As you see, a serializer has calculated attributes like lessons_count, students_count ad etc.. The question is: how can I get one of these attributes in a serializer method, for example: def get_demand_course_percent(self, obj) -> int: users = CustomUser.objects.all().count() return (self.students_count / users) * 100_ If I do like this explicitly, it gives an Attribute error that there's no such attribute in a serializer class -
Incorrect inharitance of objects in django python app
I have a model MenuIngredientConsumption, which is inherited from MenuOfferOptionModificationThrough. class MenuOfferOptionModificationThrough(models.Model) : 'content of offer' menu_offer_option_modification = models.ForeignKey(MenuOfferOptionModification, on_delete=models.CASCADE) storage_position = models.ForeignKey(StoragePosition, on_delete=models.CASCADE) quantity = models.DecimalField(max_digits=20, decimal_places=2, null=True) ingredient_name = models.CharField( max_length=200, validators=[MinLengthValidator(2, "Title must be greater than 2 characters")] ) class MenuIngredientConsumption(MenuOfferOptionModificationThrough) : created_at = models.DateTimeField(auto_now_add=True) I have 2 created objects of MenuOfferOptionModificationThrough. MenuOfferOptionModificationThrough(..., ingredient_name="potato") MenuOfferOptionModificationThrough(..., ingredient_name="tomato") So i want to copy these 2 objects of MenuOfferOptionModificationThrough to MenuIngredientConsumption. And i wrote a code in view.py: def post(self, request, **kwargs): gastronomy = get_object_or_404(Gastronomy, id=self.kwargs['gastronomy_pk']) order_modification_through = get_object_or_404(OrderModificationThrough, id=self.kwargs['order_modification_pk']) menu_offer_option_modification = order_modification_through.menu_offer_option_modification quantity = order_modification_through.quantity menu_offer_option_modification_through_list = MenuOfferOptionModificationThrough.objects.filter(menu_offer_option_modification=menu_offer_option_modification) if menu_offer_option_modification_through_list: for i in range(quantity): for ingredient in menu_offer_option_modification_through_list: menu_ingredient_consumption = MenuIngredientConsumption( menu_offer_option_modification = ingredient.menu_offer_option_modification, storage_position = ingredient.storage_position, quantity = ingredient.quantity, ingredient_name = ingredient.ingredient_name, ) menu_ingredient_consumption.save() Yes, I copy 2 objects to MenuIngredientConsumption, but also i have 6 objects of MenuOfferOptionModificationThrough. But there should be 2 still (I didn;t work with it). I don't understand why it happens. Please, help. -
Django module not found error on running docker-compose up command
I'm trying to setup local development server for my website www.priyaji.thakurani.in using dockers. The website is built on using python 3.6.8 and django 3.1.5. On running docker-compose build django command, I can see the packages from priyaji_requirements.txt getting loaded. And the command finishes successfully. However on running docker-compose up django command I'm constantly getting django module not found error. **Here's the output of docker-compose build django **. kunjabeharidasa@Kunjabeharis-MacBook-Air Priyaji % docker-compose build django WARN[0000] /Users/kunjabeharidasa/Priyalaljiu/Priyaji/docker-compose.yml: version is obsolete [+] Building 840.8s (32/32) FINISHED docker:desktop-linux => [django internal] load build definition from Dockerfile 0.0s => => transferring dockerfile: 4.10kB 0.0s => [django internal] load metadata for docker.io/library/python:3.6.8 2.2s => [django internal] load .dockerignore 0.0s => => transferring context: 412B 0.0s => [django internal] load build context 4.2s => => transferring context: 13.00MB 3.5s => [django builder 1/18] FROM docker.io/library/python:3.6.8@sha256:f20a9bfddd87c238c3d2316b4179222f219090cbb25 0.0s => CACHED [django builder 2/18] RUN sed -i 's/deb.debian.org/archive.debian.org/g' /etc/apt/sources.list && 0.0s => CACHED [django builder 3/18] RUN apt-get update && apt-get install -y build-essential libssl-dev 0.0s => CACHED [django builder 4/18] RUN pip install six && pip install --upgrade pip && pip install setupto 0.0s => CACHED [django builder 5/18] RUN groupadd -r django && useradd -r -g django django … -
Unable to update latest database configuration in settings.py in django
I write code on my local machine and then use github to transfer the code to my Amazon AWS EC2 server, I am using AWS Route53 to connect to a domain name and AWS RDS for database (started using recently, few days ago). In my previous code I was using Hostinger's remote mysql capability for a hosted database which was working fine, I deployed the code on AWS EC2 server and tested, however, when I created MySql database using RDS and updated its details in the settings.py the application is still being run using the old Hostinger's database settings only. I have tried the following things: deleting all the cache files, removing all migrations files and creating migrations once again, checked settings.py (database configuration settings) multiple times Restarted the EC2 instance, restarted supervisor, gunicorn, nginx Deleted the RDS database and created one more and updated its respective settings in settings.py To my surprise, for some reason it is still working on the old database, I am not able to figure out where exactly is it picking up the details of the old database and why is the latest settings.py file not being loaded in real time? -
Why is Django App Not Rendering HTML Page
Hello I am using Django version 4.2.3 to build my website for building my website. I have an Object called UE (upcoming_events) that I have added several fields to however, these fields don't seem to be rendering when I call the object instead the words No Events render which only happen when the upcoming_events object is empty. In order to see why this is happening I used the Django Shell to visualize the code post processing. But in the visualization the code seems to populate the objects just fine just not when rendering the object on the website. {% extends "webapp/header.html" %} {% block content %} <div class = "centerbody"> <div class="liner"> <!--Carousel Starts--> <div class = 'dive'></div> <div class = float_col> <div id="carouselExampleFade" class="carousel slide carousel-fade span" data-ride="carousel"> <div class="carousel-inner carouselMargin1"> <div class="carousel-item active"> <img src="/static/images/CarouselPictures1/canyonphoto1.jpg/" class="d-block w-100 carouselImgs" alt="..."> </div> <div class="carousel-item"> <img src="/static/images/CarouselPictures1/canyonphoto2.jpg" class="d-block w-100 carouselImgs" alt="..."> </div> <div class="carousel-item"> <img src="/static/images/CarouselPictures1/canyonphoto3.jpg/" class="d-block w-100 carouselImgs" alt="..."> </div> </div> <a class="carousel-control-prev" href="#carouselExampleFade" role="button" data-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="carousel-control-next" href="#carouselExampleFade" role="button" data-slide="next"> <span class="carousel-control-next-icon next_button" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> </div> </div> <div class="announcements"> <h2>Announcements</h2> <div class="announcement-container"> {% for announcement in announcements %} <div class="announcement-item"> <img … -
Django Choice Dropdown Not Working on Cloned Form in Formset
I am cloning my an empty form in django following guidance I've found elsewhere in stack overflow. The JS will append a new form as intendended however the dropdowns from a choice widget are no longer working and I can't figure out why. I have already validated that all of my options are there using my browser's inspect feature. It appears to be that the javascript isn't working with the object. This is from the template: <form method="post"> {% csrf_token %} <div id="form_set"> {{ FightForms.management_form|materializecss }} {% for form in FightForms %} <div class="card white darken-1 col m12"> <table class='no_error'> {{ form.non_field_errors }} <row> <div class="col m3"> <div class="fieldWrapper"> {{ form.guild_member_id|materializecss }} </div> </div> </row> {% for hidden in form.hidden_fields %} {{ hidden }} {% endfor %} </table> </div> {% endfor %} </div> <div class="col m12"> <div> <input class="btn light-blue lighten-1" type="button" value="Add More" id="add_more"> </div> <br> <button class="btn light-blue lighten-1" type="submit">Submit Guild Members</button> </div> <div id="empty_form" style="display:none"> <div class="card white darken-1 col m12"> <table class='no_error'> {{ FightForms.empty_form.non_field_errors }} <row> <div class="col m3"> <div class="fieldWrapper"> {{ FightForms.empty_form.guild_member_id|materializecss }} </div> </div> </row> {% for hidden in form.hidden_fields %} {{ hidden|materializecss }} {% endfor %} </table> </div> </div> </form> <script> $('#add_more').click(function() { … -
Do Django generic views automatically generate templates for Django models?
That’s all the Python code we need to write. We still need to write a template, however. We could explicitly tell the view which template to use by adding a template_name attribute to the view, but in the absence of an explicit template Django will infer one from the object’s name. In this case, the inferred template will be "books/publisher_list.html" – the “books” part comes from the name of the app that defines the model, while the “publisher” bit is the lowercased version of the model’s name. This comes from https://docs.djangoproject.com/en/5.1/topics/class-based-views/generic-display/ after the PublisherListView is displayed and the URL is configured. I have several questions: By changing the model equal to publisher, I understand that this view looks at a template books/publisher_list. Is this template already created by Django, with default code/logic to handle the display of multiple items of the given model? Or do we need to write it ourselves, with the context object_list? To be clear, if we create any generic view which inherits from ListView, and pass it a Django model as an attribute, will the template it's assigned to (if it already exists) look at all instances of that model, and display them in some pre-written … -
Django REST Framework cached view returning 2 different payloads
I'm experiencing a strange issue with my Django REST Framework paginated list view, which utilizes a 2 hour cache. If I repeatedly make requests to the view's endpoint, I am sometimes getting Response 1 (x bytes in size) and sometimes getting Response 2 (y bytes in size). The view code is as follows: class MyListView(generics.ListAPIView): model = MyListModel serializer_class = MyListSerializer pagination_class = PageNumberPagination pagination_class.page_size = 1000 def get_queryset(self): region = self.kwargs.get('region') sort_param = '-date_created' return MyListModel.objects.filter(region=region).order_by(sort_param) @method_decorator(cache_page(2*60*60)) def get(self, *args, **kwargs): return super().get(*args, **kwargs) I'm not sure if this is relevant, but once a day, I run a cronjob which clears all cached views using the following code: from django.core.cache import cache cache.clear() I have confirmed that the difference in response data from this endpoint is not due to the cache expiring and being replaced with new data. I have also confirmed that the data in the database for MyListModel is not being changed at all. I have also confirmed that the region parameter is consistent between requests. I'm at a loss for how I could be getting 2 different responses from this endpoint. Cache or no cache, the underlying data is not changing so the response should be … -
ModuleNotFoundError: No module named 'django.contrib.contenttyfrom datetime import timedelta'
I try to do a migration “python manage.py makemigrations ” but I get an error Traceback (most recent call last): File "/home/anton/Documents/project2/backend/my_backend/manage.py", line 22, in <module> main() File "/home/anton/Documents/project2/backend/my_backend/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/anton/Documents/project2/backend/pr2_venv/lib/python3.12/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line utility.execute() File "/home/anton/Documents/project2/backend/pr2_venv/lib/python3.12/site-packages/django/core/management/__init__.py", line 416, in execute django.setup() File "/home/anton/Documents/project2/backend/pr2_venv/lib/python3.12/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/anton/Documents/project2/backend/pr2_venv/lib/python3.12/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) ^^^^^^^^^^^^^^^^^^^^^^^ File "/home/anton/Documents/project2/backend/pr2_venv/lib/python3.12/site-packages/django/apps/config.py", line 193, in create import_module(entry) File "/usr/lib/python3.12/importlib/__init__.py", line 90, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1387, in _gcd_import File "<frozen importlib._bootstrap>", line 1360, in _find_and_load File "<frozen importlib._bootstrap>", line 1324, in _find_and_load_unlocked ModuleNotFoundError: No module named 'django.contrib.contenttyfrom datetime import timedelta' INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttyfrom datetime import timedelta', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'auth_app', 'corsheaders' ] P.S. I already noticed the error in INSTALLED APS I can't find the file with this error, and I can't install this module either pip install timedelta i also did in .env file only SECRET_KEY=django-insecure-3+qcjvwgd8r95x++s85nwz7xa+#^v2hiv7-pbgdz)b1s5)gx&w DEBUG=TRUE -
How to update code for Django Stack on Google Cloud Platform
i have used Django Stack listed on Marketplace of GCP. When I visit the IP address I get an error DisallowedHost so I've changed settings.py to (for now) ALLOWED_HOSTS = ["*"]. Problem is I don't see any changes, still same error. How do I make it update? I run python manage.py collectstatic and sudo service apache2 restart but that did nothing. -
AttributeError: 'PosixPath' object has no attribute 'read'
I wanted to do a migration, but I got an error My python version in the virturalenv is Python 3.12.3 I haven't found a single appropriate response to stackoverflow yet. Traceback (most recent call last): File "/home/anton/Documents/project2/backend/my_backend/manage.py", line 22, in <module> main() File "/home/anton/Documents/project2/backend/my_backend/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/anton/Documents/project2/backend/pr2_venv/lib/python3.12/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line utility.execute() File "/home/anton/Documents/project2/backend/pr2_venv/lib/python3.12/site-packages/django/core/management/__init__.py", line 382, in execute settings.INSTALLED_APPS File "/home/anton/Documents/project2/backend/pr2_venv/lib/python3.12/site-packages/django/conf/__init__.py", line 81, in __getattr__ self._setup(name) File "/home/anton/Documents/project2/backend/pr2_venv/lib/python3.12/site-packages/django/conf/__init__.py", line 68, in _setup self._wrapped = Settings(settings_module) ^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/anton/Documents/project2/backend/pr2_venv/lib/python3.12/site-packages/django/conf/__init__.py", line 166, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/lib/python3.12/importlib/__init__.py", line 90, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1387, in _gcd_import File "<frozen importlib._bootstrap>", line 1360, in _find_and_load File "<frozen importlib._bootstrap>", line 1331, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 935, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 995, in exec_module File "<frozen importlib._bootstrap>", line 488, in _call_with_frames_removed File "/home/anton/Documents/project2/backend/my_backend/my_backend/settings.py", line 12, in <module> environ.Env.read_env(BASE_DIR / '.env') File "/home/anton/Documents/project2/backend/pr2_venv/lib/python3.12/site-packages/environ/environ.py", line 646, in read_env content = f.read() ^^^^^^ AttributeError: 'PosixPath' object has no attribute 'read' I had the same error when I reconnected the postgres database and then sqlite3 again. -
Django Mock database not working properly
I was coding a unit test method for a post method, but for some reason, it keeps modifying the actual database instead of the mock database. This is my test method: def test_post_contest(self): mock_collection = self.mock_db.collection.return_value mock_document = mock_collection.document.return_value mock_document.set.return_value = None response = self.client.post( reverse('contest-list'), data={ 'ONI2024F2': { 'name': 'ONI2024F2', 'problems': ['problem1', 'problem2'], 'administratorId': '0987654321' } }, format='json' ) self.assertEqual(response.status_code, 201) self.assertEqual(response.json(), {'id': 'ONI2024F2'}) This is the setUp method: def setUp(self): self.client = APIClient() self.mock_db = patch('firebase_config.db').start() self.addCleanup(patch.stopall) And this is the firebase_config.py file import os import firebase_admin from firebase_admin import credentials, firestore #Path to Firebase credentials cred_path = os.path.join(os.path.dirname(__file__), 'credentials','firebase_credentials.json') #Initialize Firebase cred = credentials.Certificate(cred_path) firebase_admin.initialize_app(cred) #Firestore client db = firestore.client() I thought that it could be the firebase-config file, so I tried changing it but then all the tests raised exceptions. -
How i run python function without loading a page in django
i am working on a project which has a function which generate response automatically on loop using google gemini api and show it to the html page by saving it to the database, i want this function to run behind the scene without loading the page Currently what is happening is, if the function is generating 10 response in a loop then it is keep loading the page until all response get generated and then it is showing me home.html page. this is the function enter code here def home(request): print("Bot: Hello how can i help you?") # main code starts here i = 0 while i < 2: if len(history_global) == 0: user_input = input("You: ") chat_session = model.start_chat( history=history ) response = chat_session.send_message(user_input) #1 Taking input from user #generating output result....... model_response = response.text history.append({"role" : "user", "parts" : [user_input]}) #3 updating history - (user part) history.append({"role" : "model", "parts" : [model_response]}) #4 updating history - (response part) history_global = model_response #5 updating value of history_global with the response created # Save the data to the database saveit = Data1(question=user_input, answer=history_global) saveit.save() print(i) print("Question : ", user_input) print() print("Answer : ", model_response) print() print("...............................................................................................1") print() random_interval = random.randint(10, … -
Django Rest api json imput for m-m relation
I am trying to post json file and save the models into database. AttributeName and AttributeValue is generated correctly but Attribute is saved without "nazev_atributu_id" and "hodnota_atributu_id". [ { "AttributeName": { "id": 2, "nazev": "Barva" } }, { "AttributeValue": { "id": 2, "hodnota": "modrá" } }, { "Attribute": { "id": 1, "nazev_atributu_id": 2, "hodnota_atributu_id": 2 } } ] models.py from django.db import models class AttributeValue(models.Model): unique_id = models.AutoField(primary_key=True) id = models.IntegerField(unique=True) hodnota = models.CharField(max_length=255, null=True, blank=True) def __str__(self): return f"AttributeValue with id: {self.id}" class AttributeName(models.Model): unique_id = models.AutoField(primary_key=True) id = models.IntegerField() nazev = models.CharField(max_length=255, null=True, blank=True) kod = models.CharField(max_length=255, null=True, blank=True) zobrazit = models.BooleanField(default=False) def __str__(self): return f"AttributeName with id: {self.id}" class Attribute(models.Model): unique_id = models.AutoField(primary_key=True) id = models.IntegerField(unique=True) nazev_atributu_id = models.ManyToManyField(AttributeName, through='AttributeAttributeNameMapping') hodnota_atributu_id = models.ManyToManyField(AttributeValue, through='AttributeAttributeValueMapping') def __str__(self): return f"Attribute with id: {self.id}" class AttributeAttributeNameMapping(models.Model): attribute = models.ForeignKey(Attribute, on_delete=models.CASCADE) attribute_name = models.ForeignKey(AttributeName, on_delete=models.CASCADE) class Meta: unique_together = ('attribute', 'attribute_name') class AttributeAttributeValueMapping(models.Model): attribute = models.ForeignKey(Attribute, on_delete=models.CASCADE) attribute_value = models.ForeignKey(AttributeValue, on_delete=models.CASCADE) class Meta: unique_together = ('attribute', 'attribute_value') serializer from rest_framework import serializers from .models import * class AttributeNameSerializer(serializers.ModelSerializer): class Meta: model = AttributeName fields = '__all__' class AttributeValueSerializer(serializers.ModelSerializer): class Meta: model = AttributeValue fields = '__all__' class AttributeSerializer(serializers.ModelSerializer): nazev_atributu_id = serializers.SlugRelatedField(queryset=AttributeName.objects.all(),slug_field='id') … -
How to pass a related objects parameters in the main objects serializer
I have a Room object, which will have some settings. I wanted to make Room and RoomSettings different objects but bound to each other. RoomSettings will be created whenever a Room is created, so I'm using signals. However, while creating the room, I need to pass RoomSettings arguments from Room to RoomSettings through signals, so I can set the settings in creation. models.py from django.db import models from users.models import AppUser as UserModel from django.core.validators import MaxValueValidator, MinValueValidator import random, string from datetime import datetime def generate_unique_key(): length = 10 while True: key = ''.join(random.choices(string.ascii_uppercase, k=length)) if Room.objects.filter(key=key).count() == 0: break return key class Room(models.Model): host = models.ForeignKey(UserModel, on_delete=models.CASCADE, related_name='rooms') key = models.CharField(max_length=10, default=generate_unique_key, unique=True, editable=False) created_at = models.DateTimeField(auto_now_add=True, editable=False) def __str__(self): return f'{self.key} - {self.host.username}' def get_chat(self): return self.chat class RoomSettings(models.Model): room = models.OneToOneField(Room, on_delete=models.CASCADE, related_name='settings') max_users = models.PositiveIntegerField(default=8, validators=[MaxValueValidator(8), MinValueValidator(1)]) is_public = models.BooleanField(default=True) users_can_send_message = models.BooleanField(default=True) serializers.py from rest_framework import serializers from .models import Room, RoomSettings from users.serializers import UserSerializer from chats.serializers import RoomChatSerializer class SettingSerializer(serializers.ModelSerializer): class Meta: model = RoomSettings exclude = ['room'] class CreateRoomSerializer(serializers.ModelSerializer): max_users = serializers.IntegerField() is_public = serializers.BooleanField() users_can_send_message = serializers.BooleanField() class Meta: model = Room fields = ['max_users', 'is_public', 'users_can_send_message'] signals.py from django.db.models.signals … -
Highlight Active Links are not working in Django Website
I fulfilled all requisite steps to highlight the active links in my Django Website Project. As I click on About Us, Contact Us, or Services options in the menu bar, No menu bar options are highlighted, for guide me. Thanks for your kind anticipation <!-- Main header start --> <header class="main-header sticky-header header-with-top"> <div class="container"> <nav class="navbar navbar-expand-lg navbar-light"> <a class="navbar-brand company-logo" href="index.html"> <img src="{% static 'img/logos/black-logo.png'%}" alt="logo"> </a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbar" aria-controls="navbar" aria-expanded="false" aria-label="Toggle navigation"> <span class="fa fa-bars"></span> </button> <div class="navbar-collapse collapse w-100" id="navbar"> <ul class="navbar-nav ml-auto"> <li class="nav-item"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Home </a> </li> <li class="nav-item"> <a class="nav-link" href="cars.html"> Cars </a> </li> {% url 'about' as url %} <li class="nav-item"> <a class="nav-link {% if request.path == about %} active {% endif %}" href="{{url}}"> About </a> </li> {% url 'services' as url %} <li class="nav-item"> <a class="nav-link {% if request.path == services %} active {% endif %}" href="{{url}}"> Services </a> </li> {% url 'contact' as url %} <li class="nav-item dropdown"> <a class="nav-link {% if request.path == contact %} active {% endif %}" href="{{url}}">Contact</a> </li> <li class="nav-item dropdown m-hide"> <a href="#full-page-search" class="nav-link h-icon"> <i class="fa fa-search"></i> </a> </li> </ul> </div> </nav> </div> </header> … -
Model indexing on Choice field in django
i have a model which has a status field of choice field which are pending,approved,cancel,rejected. And i index the field status in my model and the makemigrations but the index only works for other values but not approved value. if i filter by other status like, pending,cancel it will shows that it get it from the index but if i filter by approved it won't work and it will load slowly. Though the dataset of the model is much which is around 7million. I get the details from a django debug tools this will show if i filter by other values if i filter by other values if i filter by approved value this is my view which i use to test the filter def testing(request): context['response'] = Task_Submitted.objects.filter(status='approved') return render(request, 'testing.html', context) is there any way to fixed this so approved too will be in index so if i filter by approved value too it will load faster