Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python Django Authentication (Login/Register) Errors
I am making a weather application and wanted to incorporate authentication into it, so I decided to use django and postgres as my backend. I am new to all of this, so this may seem like a really dumb and easy fix for some of you... but for me I've spent a few hours with no success. The error I come through is: I have 3 html pages, dashboard.html, login.html and register.html. My folder structure is as follows: --- Folder Structure --- .DS_Store README.md db.sqlite3 manage.py [my_weather_project] ├── __init__.py ├── [__pycache__] ├── __init__.cpython-310.pyc ├── settings.cpython-310.pyc ├── urls.cpython-310.pyc └── wsgi.cpython-310.pyc ├── asgi.py ├── settings.py ├── [staticfiles] # a lot of files here that I did not include ├── urls.py └── wsgi.py my_weather_project.zip [myapp] ├── .DS_Store ├── __init__.py ├── [__pycache__] ├── __init__.cpython-310.pyc ├── admin.cpython-310.pyc ├── apps.cpython-310.pyc ├── forms.cpython-310.pyc ├── models.cpython-310.pyc ├── urls.cpython-310.pyc └── views.cpython-310.pyc ├── admin.py ├── apps.py ├── forms.py ├── [migrations] ├── 0001_initial.py ├── __init__.py └── [__pycache__] ├── 0001_initial.cpython-310.pyc └── __init__.cpython-310.pyc ├── models.py ├── [templates] ├── .DS_Store ├── [dashboard] └── dashboard.html └── [registration] ├── login.html └── register.html ├── tests.py ├── urls.py └── views.py requirements.txt [static] └── [js] └── cookies.js Here is my cookies.js: document.addEventListener('DOMContentLoaded', function () { const form = document.getElementById('registration-form'); … -
Adding plugins inside HTMLField in Django-CMS
I am struggling adding plugins inside HTMLField as djangocms-text-ckeditor in the latest version Django-Cms 4.1.0rc4 add fileimage plugin/button in the toolbar of it. In my models.py class PortfolioItem(CMSPlugin): # Attributes - Mandatory title = models.CharField(_('title'), max_length=200, blank=False) content = HTMLField() In the settings.py CMS_PLACEHOLDER_CONF = { 'content': { 'name' : _('Content'), 'plugins': ['TextPlugin', 'LinkPlugin', 'FilerImage'], 'default_plugins':[ { 'plugin_type':'TextPlugin', 'values':{ 'body':'<p>Great websites : %(_tag_child_1)s and %(_tag_child_2)s</p>' }, 'children':[ { 'plugin_type':'LinkPlugin', 'values':{ 'name':'django', 'url':'https://www.djangoproject.com/' }, }, { 'plugin_type':'FilerImage', 'values':{ 'name':'django-cms', 'url':'https://www.django-cms.org' }, }, ] }, ] } } CKEDITOR_SETTINGS = { 'language': '{{ language }}', 'toolbar': 'CMS', 'toolbar_HTMLField': [ ['Undo', 'Redo'], ['cmsplugins', '-', 'ShowBlocks'], ['Format', 'Styles'], ], 'skin': 'moono-lisa', } I can not get the list of plugins and fileimage button does not show up. How do I get the plugins inside nested editor? ps: in the console i am getting bundle-9f0bbac8ec.cms.ckeditor.min.js:25 [CKEDITOR] Error code: editor-plugin-deprecated. {plugin: 'flash'} -
Getting n*n forms when I use formset
I am using multiple formsets in one page according to the categories I require,this has lead me to getting two errors right now; 1.I am getting n*n number of forms for one formset when asked for n 2.The cleaned data gives a none value at the end views.py def form_faculty(request): submitted=False Tutorial_number=request.session["Tuts"] Lab_number=request.session["Lab"] Lecture_Number=request.session["Lec"] Lab_Faculty=[] Tut_Faculty=[] Lec_Faculty=[] #number of forms get squared here Lectureformset=formset_factory(facultyform1,extra=Lecture_Number) Tutformset=formset_factory(facultyform2,extra=Tutorial_number) Labformset=formset_factory(facultyform3,extra=Lab_number) if request.method=="POST": form_lec=Lectureformset(request.POST or None) form_tut=Tutformset(request.POST or None) form_lab=Labformset(request.POST or None) if all([form_lec.is_valid(),form_tut.is_valid(),form_lab.is_valid()]): for form1 in form_lec.forms: Lec_Faculty.append(form1.cleaned_data.get('Faculty_Lec')) #gives none as the value for form2 in form_tut.forms: Tut_Faculty.append(form2.cleaned_data.get('Faculty_Tut')) #gives none as the value for form3 in form_lab.forms: Lab_Faculty.append(form3.cleaned_data.get('Faculty_Lab')) #gives none as the value create_file(FIC_name=FIC,cdc=cdc_name,Lecture=Lecture_Number,Tutorial=Tutorial_number,Lab=Lab_number,Faculty_Lab=Lab_Faculty,Faculty_Lec=Lec_Faculty,Faculty_Tut=Tut_Faculty) return HttpResponseRedirect('choose_new_table?submitted=True') return render(request, 'homepage/facultyForm.html', {'Lectureformset': Lectureformset,'Tutformset':Tutformset,'Labformset':Labformset,"submitted":submitted}) forms.py class facultyform1(forms.Form): Department_name = department_description.objects.get() Faculty = forms.ModelChoiceField(queryset=Faculty_List.objects.filter(Department=Department_name),label="Faculty_Lec") class facultyform2(forms.Form): Department_name = department_description.objects.get() Faculty = forms.ModelChoiceField(queryset=Faculty_List.objects.filter(Department=Department_name),label="Faculty_Tut") class facultyform3(forms.Form): Department_name = department_description.objects.get() Faculty = forms.ModelChoiceField(queryset=Faculty_List.objects.filter(Department=Department_name),label="Faculty_Lab") .html <form action="" method=POST> {% csrf_token %} <center> <center> <b>Tutorial</b> </center> <br><br> <center> {% for form in Tutformset %} {{Tutformset.as_table}} {%endfor%} </center> <br><br> <center> <b>Lab</b> </center> <br><br> <center> {% for form in Labformset %} {{Labformset.as_table}} {%endfor%} </center> <br><br> <center> <b> Lecture </b> </center> <br> <br> <center> {% for form in Lectureformset %} {{Lectureformset.as_table}} {%endfor%} </center> <br /> <br … -
failing to build django cookiecutter
I guess its stupid question, but still when im trying to build like in docs docker-compose -f production.yml build its give me error like CELERY_BROKER_URL=\"\" DJANGO_SETTINGS_MODULE=\"config.settings.test\" python manage.py compilemessages" did not complete successfully: exit code: 1 in default Dockerfile its contains empty field`s. What's im doing not rigth ? im tryed fill this fields by my credetials, and still getting this error. -
Django: sending email through smtp.gmail.com
I am using Django==4.2.1 I want to send an email to user using django.core.mail.EmailMessage, but facing this exception: socket.gaierror: [Errno -3] Temporary failure in name resolution My Django settings: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = "smtp.gmail.com" EMAIL_HOST_USER = "my-email" EMAIL_HOST_PASSWORD = "xxxxxxxxxxxxxxxx" # 16-char Google App password EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_USE_SSL = False DEFAULT_FROM_EMAIL = "foo my-email" Code: from django.core.mail import EmailMessage from rest_framework.viewsets import GenericViewSet from rest_framework.mixins import CreateModelMixin from rest_framework.response import Response from settings import EMAIL_HOST_USER from .models import Instance class InstanceViewSet(GenericViewSet, CreateModelMixin): serializer_class = InstanceCreateSerializer queryset = Instance.objects.all() def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) instance = serializer.save() email = EmailMessage( subject="subject", body="sup", from_email=EMAIL_HOST_USER, to=[instance.user.email] ) email.content_subtype = 'html' email.send() return Response(serializer.data, status=201) I tried to ping smtp.gmail.com from my docker container and it works fine. Tried to recreate EMAIL_HOST_PASSWORD. Also tried to use other EMAIL_HOST_USER. Any thoughts? -
Django Error: "Select a valid choice. That choice is not one of the available choices." Form works for one ID, but not the other
Models.py class PointCategoryRecord(models.Model): point_category_assignment_id = models.AutoField(primary_key=True) league_id = models.ForeignKey(League) description = models.TextField(default="") user_getting_points = models.ForeignKey(TeamMember) date_created = models.DateTimeField(auto_now=True) Forms.py class UserForm(ModelForm): class Meta: model = PointCategoryRecord fields = '__all__' Views.py def point_form(request, league_id): form = UserForm() if request.method == "POST": if form.is_valid(): form.save() return redirect(request.path_info) form.fields['league_id'].queryset = League.objects.filter(league_id = league_id) form.fields['point_category'].queryset = PointCategory.objects.filter(league_id = league_id) form.fields['user_getting_points'].queryset = TeamMember.objects.filter(league_id = league_id) urls.py I have the path() correct and it's passing the league_id through int:league_id I'm trying to create a form that filters by the 'league_id' parameter being passed in the views.py function. I have two objects, one with the league_id of 1 that works perfectly. The other with the league_id of 2 that throws the "Select a valid choice. That choice is not one of the available choices." error. Any idea why it works for the first ID but not the second? -
Function not triggering correctly when called
I am using request.session to pass value from one page to another in django but apparantly when you trigger the latter function,it does not update the variable. views.py first function` def form_CDC(request): global FIC if request.method == 'GET': cdc_name = request.GET.get('data') if request.method == 'POST': form = classForm(request.POST) if form.is_valid(): FIC=form.cleaned_data["FIC"] request.session['Tuts']=form.cleaned_data["Tutorials"] request.session['Lec']=form.cleaned_data["Lectures"] request.session['Lab']=form.cleaned_data["Labs"] return HttpResponseRedirect("form_Faculty") else: form = classForm() return HttpResponseRedirect('form_CDC') else: form = classForm() return render(request, "homepage/form_CDC.html", context={'form': form,"cdc_name":cdc_name}) second function def form_faculty(request): submitted=False #these lines of code are not triggered when page is loaded Tutorial_number=request.session["Tuts"] Lab_number=request.session["Lab"] Lecture_Number=request.session["Lec"] Lab_Faculty=[] Tut_Faculty=[] Lec_Faculty=[] Lectureformset=formset_factory(facultyform1,extra=Lecture_Number) Tutformset=formset_factory(facultyform2,extra=Tutorial_number) Labformset=formset_factory(facultyform3,extra=Lab_number) if request.method=="POST": form_lec=Lectureformset(request.POST or None) form_tut=Tutformset(request.POST or None) form_lab=Labformset(request.POST or None) if all([form_lec.is_valid(),form_tut.is_valid(),form_lab.is_valid()]): for form1 in form_lec.forms: Lec_Faculty.append(form1.cleaned_data['Faculty']) for form2 in form_tut.forms: Tut_Faculty.append(form2.cleaned_data['Faculty']) for form3 in form_lab.forms: Lab_Faculty.append(form3.cleaned_data['Faculty']) create_file(FIC_name=FIC,cdc=cdc_name,Lecture=Lecture_Number,Tutorial=Tutorial_number,Lab=Lab_number,Faculty_Lab=Lab_Faculty,Faculty_Lec=Lec_Faculty,Faculty_Tut=Tut_Faculty) return HttpResponseRedirect('choose_new_table?submitted=True') return render(request, 'homepage/facultyForm.html', {'Lectureformset': Lectureformset,'Tutformset':Tutformset,'Labformset':Labformset,"submitted":submitted}) urls.py urlpatterns = [ path('form_CDC',views.form_CDC,name='form_CDC'), path('form_Faculty',views.form_faculty,name='form_Faculty'), ] ` I feel its a dumb intendetion mistake since it was working fine before but now trying every possible outcome,nothing I can think of is remaining.Hope someone can help me out. -
django manage.py can not find command
When I run python manage.py loadcsv --csv reviews/management/commands/WebDevWithDjangoData.csv manage.py cannot find command loadcsv. Any help -
Many to Many Django Model
Hello i am trying to figure out the best way to design this model, this is what i have so far but i am running into issues of having a start and end date per service per customer class Customer(models.Model): name = models.CharField(max_length=255, null=False, unique=True) services = models.ManyToManyField(Service) class Service(models.Model): name = models.CharField(max_length=255, null=False) What would be the best way to design this in order to get the data to look like this: Customer || Services || Start || End Customer A Service A 1/1/2001 1/1/2010 Service B 2/2/2002 2/2/2011 Service C 3/3/2003 3/3/2012 Customer B Service A 4/4/2004 4/4/2014 Service C 5/5/2005 5/5/2015 Have been breaking my head for last few days trying to figure out what is the best way to design this model. Any help would be very much appreciated. -
Django + IIS + HttpPlatform handler
I'm trying to configure the web.config file but I can't, I would like help on how to configure it <?xml version="1.0" encoding="utf-8"?> <configuration> <system.webServer> <handlers> <add name="PythonHandler" path="*" verb="*" modules="httpPlatformHandler" resourceType="Unspecified"/> </handlers> <httpPlatform processPath="C:\Program Files\Python312\venv\Ambiente_datafit\Scripts\python.exe" arguments="C:\Application\Datafit.Pro\Projeto_datafit\manage.py runserver %HTTP_PLATFORM_PORT%" stdoutLogEnabled="true" startupTimeLimit="60" processesPerApplication="16"> <environmentVariables> <environmentVariable name="SERVER_PORT" value="%HTTP_PLATFORM_PORT%" /> </environmentVariables> </httpPlatform> </system.webServer> </configuration> I put the path to python in my virtual environment in processPath and in arguments I put the path to manage.py, but something is still missing I have this error The requested page cannot be accessed because the configuration data related to the page is invalid. Help configuring the web.config file -
Django Container Fails to Find Settings Module Specified in Environment Variable
I'm encountering a persistent issue when deploying my Django application using Docker. Despite specifying the settings module in my environment variable, Django throws an OSError indicating it cannot find the file. Here's the error I'm getting: OSError: No such file: /code/app/settings/environments/.py This suggests that Django is looking for a .py file without a preceding filename in the /code/app/settings/environments/ directory. Moreover, when I remove the development.py file, Django raises a different error: ModuleNotFoundError: No module named 'app.settings.environments.development' Here's how I have my DJANGO_SETTINGS_MODULE set in docker-compose.yml: `services: web: build: context: ./ dockerfile: docker/Dockerfile.backend volumes: - ./backend/:/code/ ports: - 8000:8000 environment: - DJANGO_SETTINGS_MODULE=app.settings.environments.development env_file: - backend/.env depends_on: - database database: image: postgres:14-alpine volumes: - postgres_data:/var/lib/postgresql/data/ env_file: - backend/.env ports: - "5434:5432" volumes: postgres_data:` `FROM python:3.11-slim ARG DJANGO_ENV ENV DJANGO_ENV=${DJANGO_ENV} \ PYTHONFAULTHANDLER=1 \ PYTHONUNBUFFERED=1 \ PYTHONHASHSEED=random \ PIP_NO_CACHE_DIR=off \ PIP_DISABLE_PIP_VERSION_CHECK=on \ PIP_DEFAULT_TIMEOUT=100 RUN apt-get update && apt-get install -y \ gcc \ python3-dev \ libpq-dev \ netcat-openbsd \ && rm -rf /var/lib/apt/lists/* WORKDIR /code COPY backend/requirements /code/requirements COPY backend/app/settings /code/app/settings RUN pip install -r requirements/development.txt COPY backend /code EXPOSE 8000 CMD ["sh", "run.sh"]` In backend/.env file I have only DB settings. In run.sh file script check if database has been started and then … -
How to make Django Dynamic Inline Forms as like admin (using Class Based Views)?
I have 2 Models class Section(models.Model): SECTION_CHOICES_CLASS_6_7_8 = [ ("A", "Section A"), ("B", "Section B"), ("C", "Section C"), ] SECTION_CHOICES_CLASS_9_10 = [ ("Sc", "Science"), ("Co", "Commerce"), ("Ar", "Arts"), ] name = models.CharField( max_length=2, verbose_name="Section", choices=SECTION_CHOICES_CLASS_6_7_8 + SECTION_CHOICES_CLASS_9_10, ) description = models.TextField( null=True, blank=True, help_text="Section Description, e.g. 'Section A of Class 6, total 30 students'", ) class_name = models.ForeignKey( Class, on_delete=models.CASCADE, help_text="Class", verbose_name="Class", ) teacher = models.OneToOneField( "Teacher", on_delete=models.SET_NULL, null=True, blank=True, verbose_name="Section Teacher", ) seat = models.PositiveIntegerField(default=0) subjects = models.ManyToManyField(Subject, through="SectionSubject") class SectionSubject(models.Model): section = models.ForeignKey(Section, on_delete=models.CASCADE) subject = models.ForeignKey(Subject, on_delete=models.CASCADE) teachers = models.ForeignKey(Teacher, on_delete=models.CASCADE) period = models.IntegerField( default=0, validators=[MaxValueValidator(10), MinValueValidator(0)] ) time = models.TimeField( null=True, blank=True, ) After configuring the admin, Using Tabular Inline How can I achieve the same kinda UI functionality in the template. Or suggest me a better way to make it comfortable for user. I've tried the inlineformset_factory forms.py class SectionSubjectForm(forms.ModelForm): class Meta: model = SectionSubject fields = "__all__" widgets = { "subject": forms.Select(attrs={"class": "form-select"}), "teachers": forms.Select(attrs={"class": "form-select"}), "period": forms.TextInput(attrs={"class": "form-control "}), "time": forms.TextInput(attrs={"class": "form-control "}), } SectionSubjectInlineFormset = inlineformset_factory( Section, SectionSubject, form=SectionSubjectForm, extra=1, can_delete=True, can_delete_extra=True, ) views.py class SectionCreateView(SuccessMessageMixin, CreateView): form_class = SectionForm template_name = "dashboard/section/section_add_or_update.html" success_message = "Section created successfully" def get_context_data(self, **kwargs): context … -
Open the link in new tab instead of the default action of a bootstrap template
I am using a bootstrap MyResume And there is this section This is the piece of code for it <div class="row portfolio-container" data-aos="fade-up" data-aos-delay="200"> <div class="col-lg-4 col-md-6 portfolio-item filter-app"> <div class="portfolio-wrap"> <img src="assets/img/portfolio/portfolio-1.jpg" class="img-fluid" alt=""> <div class="portfolio-info"> <h4>App 1</h4> <p>App</p> <div class="portfolio-links"> <a href="assets/img/portfolio/portfolio-1.jpg" data-gallery="portfolioGallery" class="portfolio-lightbox" title="App 1"><i class="bx bx-plus"></i></a> <a href="portfolio-details.html" class="portfolio-details-lightbox" data-glightbox="type: external" title="Portfolio Details"><i class="bx bx-link"></i></a> </div> </div> </div> </div> <div class="col-lg-4 col-md-6 portfolio-item filter-web"> <div class="portfolio-wrap"> <img src="assets/img/portfolio/portfolio-2.jpg" class="img-fluid" alt=""> <div class="portfolio-info"> <h4>Web 3</h4> <p>Web</p> <div class="portfolio-links"> <a href="assets/img/portfolio/portfolio-2.jpg" data-gallery="portfolioGallery" class="portfolio-lightbox" title="Web 3"><i class="bx bx-plus"></i></a> <a href="portfolio-details.html" class="portfolio-details-lightbox" data-glightbox="type: external" title="Portfolio Details"><i class="bx bx-link"></i></a> </div> </div> </div> </div> <div class="col-lg-4 col-md-6 portfolio-item filter-app"> <div class="portfolio-wrap"> <img src="assets/img/portfolio/portfolio-3.jpg" class="img-fluid" alt=""> <div class="portfolio-info"> <h4>App 2</h4> <p>App</p> <div class="portfolio-links"> <a href="assets/img/portfolio/portfolio-3.jpg" data-gallery="portfolioGallery" class="portfolio-lightbox" title="App 2"><i class="bx bx-plus"></i></a> <a href="portfolio-details.html" class="portfolio-details-lightbox" data-glightbox="type: external" title="Portfolio Details"><i class="bx bx-link"></i></a> </div> </div> </div> </div> <div class="col-lg-4 col-md-6 portfolio-item filter-card"> <div class="portfolio-wrap"> <img src="assets/img/portfolio/portfolio-4.jpg" class="img-fluid" alt=""> <div class="portfolio-info"> <h4>Card 2</h4> <p>Card</p> <div class="portfolio-links"> <a href="assets/img/portfolio/portfolio-4.jpg" data-gallery="portfolioGallery" class="portfolio-lightbox" title="Card 2"><i class="bx bx-plus"></i></a> <a href="portfolio-details.html" class="portfolio-details-lightbox" data-glightbox="type: external" title="Portfolio Details"><i class="bx bx-link"></i></a> </div> </div> </div> </div> <div class="col-lg-4 col-md-6 portfolio-item filter-web"> <div class="portfolio-wrap"> <img src="assets/img/portfolio/portfolio-5.jpg" class="img-fluid" alt=""> <div class="portfolio-info"> <h4>Web 2</h4> <p>Web</p> <div class="portfolio-links"> <a href="assets/img/portfolio/portfolio-5.jpg" … -
The dropdown in side-bar not working in django
i created a side-bar in my django template, the side bar is displayed, but the dropdown is not working, i checked every thing like code or environments and didn't found any reason for this problem . here is my code: sidebar.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Sidebar Menu for Admin Dashboard</title> <!--<link rel="stylesheet" href="style.css" />--> <!-- Fontawesome CDN Link --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css" /> <script src="static/js/sidebar.js"></script> <style> .sidenav { height: 100%; width: 200px; position: fixed; z-index: 1; top: 0; left: 0; background-color: #111; overflow-x: hidden; padding-top: 20px; } .sidenav a, .dropdown-btn { padding: 6px 8px 6px 16px; text-decoration: none; font-size: 20px; color: #818181; display: block; border: none; background: none; width:100%; text-align: left; cursor: pointer; outline: none; } .sidenav a:hover, .dropdown-btn:hover { color: #f1f1f1; } .dropdown-container { display: none; background-color: #262626; padding-left: 8px; } .fa-caret-down { float: right; padding-right: 8px; } </style> </head> <body> <div class="sidenav"> <a href="#">Home</a> <button class="dropdown-btn">Dropdown <i class="fa fa-caret-down"></i> </button> <div class="dropdown-container"> <a href="#">Link 1</a> <a href="#">Link 2</a> <a href="#">Link 3</a> </div> <a href="#">Contact</a> </div> <script> var dropdown = document.querySelector('.dropdown-container'); var dropdownBtn = document.querySelector('.dropdown-btn'); dropdownBtn.addEventListener('click', function() { dropdown.classList.toggle('show'); }); dropdown.addEventListener('click', function() { dropdown.classList.remove('show'); }); </script> … -
How to dump custom annotated fields to JSON fixture (Django)
I want to change token field to facebook_token in fixtures. I would be glad if your help me please 😁 models.py class FacebookAdAccounts(models.Model): id_ad = models.CharField(max_length=255) name_ad = models.CharField(max_length=255) currency = models.CharField(max_length=255, default='USD') is_active = models.BooleanField(default=True) business_account = models.ForeignKey(FacebookBusinessAccounts, on_delete=models.CASCADE, blank=True, null=True) token = models.CharField(max_length=510, blank=True, null=True) def __str__(self): return f'{self.id_ad} {self.name_ad} - {self.name_ad}' class FacebookTokens(models.Model): token = models.CharField(max_length=510) user_id = models.CharField(max_length=255) Given this model, I want to make fixtures of FacebookAdAccounts model to JSON format. I have this result: [ { "model": "facebook.FacebookAdAccount", "pk": 1, "fields": { "id_ad": "id_ad1", "name_ad": "name_ad_1", "currency": "USD", "is_active": true, "business_account": null, "token": "TOKEN_USER#1" }, ... ] I expect this result: [ { "model": "facebook.FacebookAdAccount", "pk": 1, "fields": { "id_ad": "id_ad1", "name_ad": "name_ad_1", "currency": "USD", "is_active": true, "business_account": null, "facebook_token": 4 }, ... ] I have tried this: FacebookAdAccounts._meta.model_name = "FacebookAdAccount" FacebookAdAccounts._meta.app_label = "facebook" subquery = FacebookTokens.objects.filter(token=OuterRef("token")).values("pk")[:1] queryset = FacebookAdAccounts.objects.annotate( facebook_token=Subquery(subquery) ) # I want facebook_token field to also be serialized json_data = serializers.serialize("json", queryset, indent=4) file_path = "data2.json" with open(file_path, "w") as file: file.write(data) -
problem in real time match-making and lobby implementation
I want to implement a real time match making using web sockets for a 2 playered game . I checked if there any waiting player by querying the data base (if channel_name``_2 = null). if yes connect incoming channel with waiting channel in database . However this fails in real time .for example consider two clients wanted to connect and there is single waiting player in db .Both get connected .here is my implementation. consumers.py import json import random from channels.generic.websocket import AsyncWebsocketConsumer from django.db import IntegrityError from asgiref.sync import sync_to_async from channels.db import database_sync_to_async from .models import Game from .generator import Generator class LobbyConsumer(AsyncWebsocketConsumer): @database_sync_to_async def anyWaitingPlayer(self): return Game.objects.filter(channel_name_2=None).count() > 0 @database_sync_to_async def addPlayerToLobby(self , id , channel_name_1): try: Game.objects.create(gameid=id , channel_name_1 =channel_name_1).save() except IntegrityError as e: print(f"IntegrityError: {e}") @database_sync_to_async def waitingPlayerRoom(self , channel_name_2): waiting_games = Game.objects.filter(channel_name_2=None) earliest_game = waiting_games.earliest('time') id = earliest_game.gameid updated_record = Game.objects.get(gameid = id ) updated_record.channel_name_2 = channel_name_2 updated_record.save() return id @database_sync_to_async def getGroupId(self , channel_name): if Game.objects.get(channel_name_1 = channel_name).gameid == None : return Game.objects.get(channel_name_2 = channel_name).gameid async def connect(self): # Get the unique channel name # if Any waiting player , pair new player with waiting player if await self.anyWaitingPlayer(): id =await self.waitingPlayerRoom(self.channel_name) await … -
Filter queryset from filename field based on two words that appear one after the other Django
I have a Files table, which contains various fields, one of which is a filename. Within each one of the files in this table, there is a specific file that I'd like to retrieve, which is basically a terms and conditions. This filename will always have the words 'terms' and 'conditions' within the filename itself, and it will always be in that order. However, there could be other words surrounding both 'terms' and 'conditions'. For example, a filename could be 'my new terms and conditions' or 'my even better terms blah blah conditions'. I'm trying to write a queryset that will retrieve such a file using Regex but I'm not able to do so. So far, I have something like: file = Files.objects.filter( Q(filename__iregex=r'(^|\W){}.*({}|$)'.format("term", "condition")) ).first() but this doesn't work. -
pytest-django cannot find my existing module
to give a bit of context, I'm learning test unit in django and made an overly simple app to get started (Attach is the structure of my project). Here is my problem: When launching my unit tests on my django app, I get a ModuleNotFoundError event though the module exists. Sample of code: from django.shortcuts import get_object_or_404, render from .models import Book def book_infos(request, pk): book = get_object_or_404(Book, pk=pk) return render(request, "book_infos.html", {'book': book}) And the test associated: import pytest from django.urls import reverse from django.test import Client from django_pytest.library.models import Book from pytest_django.asserts import assertTemplateUsed @pytest.mark.django_db def test_book_infos_view(): client = Client() Book.objects.create(author="Jules Verne", title="20 milles lieues sous les mers") path = reverse('infos', kwargs={'pk': 1}) response = client.get(path) content = response.content.decode() expected_content = "<p>Jules Verne | 20 milles lieues sous les mers</p>" assert content == expected_content assert response.status_code == 200 assertTemplateUsed(response, "book_infos.html") My pytest.ini is as follow [pytest] pythonpath = . library tests DJANGO_SETTINGS_MODULE = django_pytest.settings python_files = test_*.py When I run pytest tests/library/test_views.py from django-pytest I get this result: platform win32 -- Python 3.11.5, pytest-7.4.3, pluggy-1.3.0 django: version: 4.2.7, settings: django_pytest.settings (from ini) rootdir: ...\django-pytest\django_pytest configfile: pytest.ini plugins: django-4.6.0 _ ERROR collecting tests/library/test_views.py _ ImportError while importing test module … -
Communication between AWS App Runner & EC2 instance
I've read about this subject in a couple of questions, but I haven't found the solution yet. So, I'm reasking almost the same question, as many others have done before: I have a Django app deployed on an App Runner server, and I have a backend process (in Python too) deployed on an EC2 instance. I need to be able to communicate values between this two servers, so when the user interacts with the django app, this calls the EC2 backend, processes the info and returns an output. Currently, I'm trying this like so: On my Django app I have this code. On button click it executes the ecconsult(): from django.shortcuts import render, HttpResponse from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt import json import requests def home(request): return render(request, 'index.html') def ecconsult(request): data_to_send = "communication test" response = requests.post('http://specific_host:specific_port/api/procesar', json=data_to_send) if response.status_code == 200: jsondatabe = response.text response_data = {'jsondatabe': jsondatabe} else: print('Error al procesar la call del backend') return render(request, 'index.html', response_data) And on my EC2 BackEnd server, I recieve the data like so: from flask import Flask, request, jsonify from flask_cors import CORS app = Flask(__name__) CORS(app, resources={r"/api/*": {"origins": "Django_app_domain"}}) @app.route('/') def hello(): print("accesing from outside") return … -
Trouble with Docker and Colima: Django Container Not Reflecting Code Changes Until Docker Restart
I'm using colima version 0.5.6 to run Docker. I have three containers: Django, .... I'm encountering a problem with the Django container.When I edit the code and save it, no changes appear on the interface, even after refreshing the page. The only way to see the changes is by executing the following command: docker restart django. the same config works. with docker descktop. i checked the yaml file and it already contains this line :restart: unless-stopped in the container config: services: django: build: context: . dockerfile: ./compose/local/django/Dockerfile image: local_django container_name: django depends_on: - mysql volumes: - .:/app:z env_file: - ./.envs/.local/.django - ./.envs/.local/.s3 - ./.envs/.local/.mysql ports: - "8000:8000" command: /start restart: unless-stopped platform: linux/x86_64 -
I got this 'TypeError: unsupported operand type(s) for +=: 'CartItems' and 'int' ' error while i am trying to add items to the cart
Views.py: def add_to_cart(request, product_id): product = Product.objects.get(id=product_id) try: cart = Cart.objects.get(cart_id=_cart_id(request)) except Cart.DoesNotExist: cart = Cart.objects.create(cart_id=_cart_id(request)) cart.save() try: cart_item = CartItems.objects.get(product=product, cart=cart) cart_item += 1 cart_item.save() except CartItems.DoesNotExist: cart_item = CartItems.objects.create(product=product, quantity=1, cart=cart) cart_item.save() return redirect('cart_app:cart_details') i need cart_item incremented by one when an item is added to the cart -
How do I change the 12 hour format in django?
I have a DateTimeField in my model. When I add this field to admin.py , then the format shows as 4:00 pm , how can this be changed to 16:00? creation_date = models.DateTimeField(auto_now_add=True,) If I do this def time(self): return self.creation_date.timezone().strftime('%Y-%m-%d %H:%M:%S') that time field is not sorted -
what is the proper way to use aggregate in a complicated structured Django models
I have a Django app that represents a football league and should show scores points and other stuff, I need to create a function based on the models in this app to get the sum of goals, points, matches won, and positions in the current season, here are my models : **models.py class TeamName(models.Model): """ Stores Available team name to be picked later by users """ name = models.CharField(max_length=33, verbose_name=_( "Team Name"), help_text=_("Name of the team to be used by players")) logo = models.FileField(upload_to="uploads", verbose_name=_( "Logo Image"), help_text=_("The File that contains the team logo image"), null=True) def image_tag(self): """ This method created a thumbnil of the image to be viewed at the listing of logo objects :model:'teams.models.TeamName' """ return mark_safe(f'<img src="/uploads/{self.logo}" width="100" height="100" />') image_tag.short_description = _("Logo") image_tag.allow_tags = True class Meta: """ Defines the name of the model that will be viewied by users """ verbose_name = _("1. Team Name") def __str__(self) -> str: """ Make sure to view the name as string not the id or pk """ return str(self.name) class TeamStrip(models.Model): """ Stores Available team Strip to be picked later by users """ image = models.FileField(upload_to="uploads/uploads", verbose_name=_( "Team Strips"), help_text=_("A Strip to be used later by users")) … -
No data displayed in template from Django TemplateView
I am new to Djago and am trying to show the detail of an object from a list. Everything works from the code below except for the small matter of the detaill not being displayed. Here is my view `class PieceDetail(TemplateView): template_name = 'cabinets/piece_detail.html' def get_context_data(self, **kwargs): id = kwargs.get('pk') piece = get_object_or_404(Piece, pk=id) pprint(piece.pk) serializer = PieceSerializer(piece) pprint(serializer.data) return {'serializer': serializer, 'cabinets/piece_detail': piece.pk} Here is the urlpath('piece_detail/int:pk/', views.PieceDetail.as_view(), name = 'piece_detail'),` Here is the html {% extends "shared/base.html" %} {% load static %} {% block content %} </br> <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom"> <div class="btn-toolbar mb-2 mb-md-0"> <div class="btn-group me-2"> <a href="/cabinet/piece_list" ><button class="btn btn-primary"> Back </button></a> </div> </div> <br class="modal-body py-0"> <p>{{ serializer.data.id }}</p> <div class="container"> <div class="form-group"> {{ piece.description }} </div> <div class="form-group"> {{ piece.quantity }} </div> </div> </div> <p>The quantity shown is that usually used during construction of components</p> </div> {% endblock %} and here is some pprint output from the terminal on show detail selected 1 {'description': 'door rail', 'quantity': 2} [03/Nov/2023 12:16:05] "GET /cabinet/piece_detail/1/ HTTP/1.1" 200 14603 I have tried various different methods to get the data from the view to the template, but it still seems to go … -
How to implement accurate (hight resolution) zoom on DICOM images?
I use Pydicom and matplotlib to read and display DICOM images in a djANGO PROJECT inspired by Gregorio Flores dicom_django_viewer (thank to him). He use wheelzoom to add zoom fonctionnality but it seems that dicom image loss resolution when zoom is applied. Is there an efficient solutio to implement zoom on DICOM images?