Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
{'index': 0, 'code': 2, 'errmsg': "No array filter found for identifier 'i' in path 'Comments.$[i].Replies.$[j].Reply'"}
enter image description here WriteError: No array filter found for identifier 'i' in path 'Comments.$[i].Replies.$[j].Reply', full error: {'index': 0, 'code': 2, 'errmsg': "No array filter found for identifier 'i' in path 'Comments.$[i].Replies.$[j].Reply'"} I just want to update the reply in my data. I'm getting this error. Is there any other way to update? If yes. Then please kindly answer. Thank you. Code article_id = "6223bf189ee543673ca35940" comment_id = "2d1ae2a7-1488-44b0-8ba3-9e946ed8cca9" reply_id = "c0b9d54a-416f-4598-bf7b-33be80faa5c3" article_collection.update_one({'_id': ObjectId(article_id)}, { '$set': {'Comments.$[i].Replies.$[j].Reply': reply}, 'arrayFilters': [{'i.ID': comment_id}, {'j.ID': reply_id}] }, upsert=False) Data { "_id" : ObjectId("6223bf189ee543673ca35940"), "Comments" : [ { "ID" : "2d1ae2a7-1488-44b0-8ba3-9e946ed8cca9", "User_id" : 1, "Comment" : "Thank you for this simple explanation.", "Date" : ISODate("2022-03-13T02:13:09.022Z"), "Replies" : [ { "ID" : "c0b9d54a-416f-4598-bf7b-33be80faa5c3", "User_id" : 1, "Reply" : "You're welcome", "Date" : ISODate("2022-03-13T12:53:39.046Z") } ] } ] } Can anyone help me with this one. -
Format DateField model in Django
I used DateTime Field to format the date, but doesn't seem to work, what could be the isssue, below is my code : from django.conf.locale.de import formats as de_formats de_formats.DATE_FORMAT = 'd.m.Y' This is the model : contract_signed_on = models.DateField( _('Contract signed on'), null=True, blank=True) I want the date format to be like this : 04.3.2022 but it's not showing the exact format -
How can I automaticall add the currently logged in user to django models in react
This is the link to my previous question which will help you understand this question (How do I use localstorage.getItem or setItem to send a post request in my react application?). Thanks to you guys, I can successfully make a post request in the frontend (react). However, am unable to automatically include or save the user in the database record. The username field in the database table is blank. The username field is automatically included when creating a post request in the admin page but not in frontend react. The previous question includes all the relevant code. Below is the model class. I am using custom user model and hence the email is my username: class ClientInformation(models.Model): user = models.OneToOneField( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True) age = models.TextField(max_length=10) phone_number = models.TextField(max_length=20) country = models.TextField(max_length=30) city = models.TextField(max_length=30, blank=False) alergy = models.TextField(max_length=500, null=True, default=None) gender = models.TextField(max_length=20, null=False, blank=False) last_update = models.DateTimeField(default=now) -
Point NGINX to Domain Name: nginx.service: Failed with result 'timeout'
I am trying to point my Amazon EC2 instance to my sample.com domain name. The server is Django + NGINX based server. It works well with the public IP address of the server but when I add server_name example.com in my nginx config file the domain keeps loading forever. Please help: Mar 14 21:37:14 ip-172-31-19-81 systemd[1]: nginx.service: Failed with result 'timeout'. Mar 14 21:37:14 ip-172-31-19-81 systemd[1]: Stopped A high performance web server and a reverse proxy server. Mar 14 21:37:14 ip-172-31-19-81 systemd[1]: Starting A high performance web server and a reverse proxy server... Mar 14 21:37:14 ip-172-31-19-81 systemd[1]: Started A high performance web server and a reverse proxy server. NGINX Config file: server{ listen 80; listen [::]:80; server_name example.com; root /home/ubuntu/dir; location / { try_files $uri $uri/ /index.html; } location /api { include proxy_params; rewrite /api/(.*) /$1 break; proxy_pass http://unix:/home/ubuntu/dir/app.sock; } location /admin { include proxy_params; proxy_pass http://unix:/home/ubuntu/dir/app.sock; } location /static { autoindex on; alias /home/ubuntu/dir/dir/; } } -
Separate 0 from None
I want to implement next situation in my save function in model: if factor_rate exists in database ( not None) -> than do something. But in my case 0 is acceptable value for me, user can provide this value in form. And I don't know how to separate None from 0. Do you have any idea? if self.factor_rate: self.status = False else: self.status = True -
Permission denied on file django app published on IIS
I Have a django app puplished in my company's IIS that is reading the mail from an specific mail inbox registered in the tenant. I succesfully registered my python app on the tenant and use the credentials generated to read the inbox folder. everything works when I run my app locally using the manager.py file. However, when I want to enter the app through the IIS and I click on the view responsible of reading the mail i get the error: [Errno 13] Permission denied: 'o365_token.txt'. I went to the folder where my files are and added the IIS group to have total control over the folder and still not good results. Relevant part of the code: import O365 from O365 import Account, Connection, MSGraphProtocol, Message credentials=(client id, client secret) account = Account(credentials, auth_flow_type='credentials', tenant_id=tenant id) if account.authenticate(): print('Authenticated!') account.connection.refresh_token() if('QQ_FV_Mail' in diccionario['cadenaMail']): mailbox = account.mailbox(resource='mail1') elif('EE_FV_Mail' in diccionario['cadenaMail']): mailbox = account.mailbox(resource='mail2) query = mailbox.new_query() inbox=mailbox.inbox_folder() -
React - redirecting to full url and not relative url
Good afternoon, I built a django form for my thesis work that I intend to interviewees. To make it more appealing and increase the number of answers (I hope! :)) I built a page using a tutorial on react. It looks very nice. The problem is that building my form with react looks like a nightmare. So I would like to have a button on my react page that once clicked redirect to my django html page with the form. I looked online but none of the topics I found did the trick (React-Router External link, react-router redirect to a different domain url, react button onClick redirect page). I would like to have something like: <NavBtnLink to="http://127.0.0.1:8000/doctor/7f06cb1c-d68e-459e-9d07-ce4d52d2b50b/survey/%22%3ETake the survey</NavBtnLink> but that tries to redirect me to: http://localhost:3000/http://127.0.0.1:8000/doctor/7f06cb1c-d68e-459e-9d07-ce4d52d2b50b/survey/ instead of: http://127.0.0.1:8000/doctor/7f06cb1c-d68e-459e-9d07-ce4d52d2b50b/survey/ Any idea of things I could try (on top of what is suggested in the mentionned topics? -
The information of my foreign key is not displayed in my template
I have a doubt what happens is that I do not understand what I am doing wrong. I have a model that stores information very well(Inventory), everything is perfect in the template, views, etc.. But I have another model that has a foreign key that inherits to the model that works. Only when trying to display the data nothing is seen. I do not know what I'm doing wrong. ReporteGancias/modelos.py class ReporteGanancias(models.Model): mano_obra=models.ForeignKey(ManoObra, on_delete=models.CASCADE) parte=models.ForeignKey(Inventory, on_delete=models.CASCADE) def __str__(self): #return f'{self.parte} {self.mano_obra} ' inventario/modelos.py class Inventory(models.Model): STATUS = ( ('Ok', 'Ok'), ('Pending', 'Pending'), ) dealer = models.CharField(max_length=255, blank=True, null=True) codigoInventory=models.CharField(max_length=255,blank=True) invoiceNumber=models.IntegerField() descriptionInventory= models.CharField(max_length=255, blank=True, null=True) quantityInventory=models.IntegerField(default=0) unitPriceInventory=models.IntegerField() minimumInventory=models.IntegerField() # invoice_number=models.IntegerField() status=models.CharField(max_length=255,choices=STATUS,default='Ok') fecha_registro = models.DateTimeField(default=datetime.now) def __str__(self): return f'{self.dealer}: {self.codigoInventory} {self.invoiceNumber} {self.descriptionInventory} ' \ f'{self.quantityInventory} {self.unitPriceInventory}{self.minimumInventory}{self.status}{self.fecha_registro}' ReporteGancias/views.py class pendingStock(ListView): model=ReporteGanancias template_name = 'ReporteGanancias/reports-pending-stock.html' context_object_name='stocks' queryset=ReporteGanancias.objects.all() ReporteGancias/informes-pendiente-de-stock.html' {% for stock in stocks %} {% if stock.parte %} <tr> <td>{{ stock.parte.codigoInventory }}</td> <td>Part Name</td> <td>{{ stock.parte.unitPriceInventory }}</td> <td><a href="#" class="stock-quantity" data-type="text" data-pk="1">{{ stock.parte.quantityInventory }}</a></td> <td>{{ stock.parte.dealer }}</td> <td>{{ stock.parte.invoiceNumber }}</td> </tr> {% endif %} {% endfor %} -
Cloud Run error: Container failed to start. Failed to start and then listen on the port defined by the PORT environment variable. - Django
I'm new to asking questions on SO, so bear with me. I know there are a lot of answers about this already, but none of them work. I've been working on making a Django web app, and now I have to deploy it so you can access it on mobile. I've been trying to get it running on Google Cloud Run, but no luck. I've made the Docker container, and that runs fine locally, but when I try to deploy the container, it gives me the following error: Cloud Run error: Container failed to start. Failed to start and then listen on the port defined by the PORT environment variable. Logs for this revision might contain more information. The logs loop back to the exact same page, with no additional information. I've tried to switch the ports in the docker-compose.yml and Dockerfile to 80, 8000, 8080, and any variation in between, with no luck. I know with Django stuff you're meant to use the App Engine, but I've already loaded too much stuff into the sqlite3 database, and all the sources I can find for the App engine are about PostGres, which I don't have time to convert over to. … -
Implement Django Mnagement Command
I am trying to give the command like this if blacklist == true: is active = false else: no action from django.core.management import BaseCommand from wm_data_collection.models import roses class Command(BaseCommand): help = "Blacklist_TRUE then Active_FALSE." def handle(self, *args, **options): roses.objects.filter(active=False).update(blacklist=True) -
Django Initialise NOT value of Bool Field From Model in ModelAdmin Form
I have a boolean field in a legacy database and want to render it in a checkbox as the NOT value of the db field value. For example, false would be rendered as an checked checkbox true would be rendered as an unchecked checkbox class MyModel(models.Model): """Model with a boolean field for existing data in db""" flag = models.BoolField() How can I use a Django ModelAdmin form so that the field is loaded with the NOT value of the model on form load? Alternatively, how do I create my own checkbox widget to render the NOT value from the underlying model? -
django imagefield default image path has duplicate 'image' in it
i have followed many answers but i have already done those things they provide like Django ImageField Default Image my issue is when a user is created and default image is used, the path to it has double image like: Not Found: /images/images/df.png while the real path is static/images/dj.png and also when i search in the browser http://127.0.0.1:8000/images/df.png i get the correct image, when as soon as its rendered in my template its giving the above error, my template: <div class="col-md-3"> <div class="card card-body"> <a href="{% url 'home' %}" class="btn btn-warning bt1">&#8592; go back to home</a> <hr> <h3 style="text-align: center;">Profile Settings</h3> <hr> <img src="{{ request.user.profile.image.url }}" alt="" class="profile-pic"> {% if request.user == profile.user %} <a href="{% url 'edit-profile' profile.id %}" class="btn btn-info bt1" style="margin-top: 1rem;">Edit Profile</a> {% endif %} </div> </div> my settings is: STATIC_URL = '/static/' MEDIA_URL = '/images/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images') and lastly my model is: class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length=60, blank=True, null=True) address = models.CharField(max_length=400, null=True, blank=True) image = models.ImageField(default='df.png', null=True, blank=True) phone_no = models.CharField(max_length=40, null=True, blank=True) bio = models.TextField(max_length=400, null=True, blank=True) def __str__(self): return str(self.user) i have done many variations like changing the … -
super().__init__(**kwargs) TypeError: __init__() got an unexpected keyword argument 'max_length'
This my models.py code.Can anyone let me know whats wrong with this code ? I am getting this error please me tell solution ''' from django.db import models # Create your models here. class Users(models.Model): GENDER_CHOICES = ( ('M', 'Male'), ('F', 'Female'), ) name = models.CharField(max_length=255) date_of_birth = models.DateField(max_length=8) address = models.CharField(max_length=255) email = models.EmailField(max_length=50) phone_number = models.CharField(max_length=100) cnic = models.CharField(max_length=255) gender = models.CharField(max_length=1, choices=GENDER_CHOICES) password = models.CharField(max_length=255) city = models.CharField(max_length=255) postal_code = models.CharField(max_length=255) area = models.CharField(max_length=255) ''' This my serilizers.py code.Can anyone let me know whats wrong with this code ? ''' # from django.forms import forms from rest_framework import serializers class UserSerializer(serializers.Serializer): GENDER_CHOICES = ( ('M', 'Male'), ('F', 'Female'), ) name = serializers.CharField(max_length=255) date_of_birth = serializers.DateField(max_length=8) address = serializers.CharField(max_length=255) email = serializers.EmailField(max_length=50) phone_number = serializers.CharField(max_length=100) cnic = serializers.CharField(max_length=255) gender = serializers.CharField(max_length=1, choices=GENDER_CHOICES) password = serializers.CharField(max_length=255) city = serializers.CharField(max_length=255) postal_code = serializers.CharField(max_length=255) area = serializers.CharField(max_length=255) ''' This my views.py code.Can anyone let me know whats wrong with this code ? ''' from django.shortcuts import render from .models import * from .serializers import UserSerializer from rest_framework.renderers import JSONRenderer from django.http import HttpResponse # Create your views here. def user_details(request): user = Users.objects.get(id=1) # for complex data to python data serializer … -
Pycord (Discord Bot) Inside Django View
So, I run a rather larger discord bot (couple thousand users atm, trying to grow it). On the same server, I have a Django instance that I use for model storage and web dev. I'm trying to implement an admin panel using some of the model information, but also some information from the discord API. Unfortunately, however, the way that Pycord/Discord.py bots are started, the function is continuous, so I can't just run things normally. So to get the Discord information in a view, I'm attempting this. async def baseAdmin(request): intents = discord.Intents.default() intents.members = True intents.messages = True intents.guilds = True intents.presences = True bot = discord.Bot(intents=intents) print('1') @bot.event async def on_ready(): print('3') n = bot.get_guild(815846750652465202) name = n.name await bot.close(); print("4") return render(request, 'website/success.html') print("2") bot.run("MYTOKEN"); However, nothing works. I've tried going back and forth between sync and async views, using bot.run with and without an await, and a couple more things. Alas, nothing works. With this specific set, I'm getting an asyncio.exceptions.CancelledError result, but errors have been all over the place. Any assistance is GREATLY appreciated. -
estou tendo dificuldades com este erro MultiValueDictKeyError
Estou testando o Django para Desenvolvimento WEB no Pycharm, estou me deparando com o seguinte erro: enter image description here Segue Views.py: enter image description here Segue models.py: enter image description here Segue arquivo HTML - detalhe_cidades: enter image description here Segue Proj/urls.py: enter image description here Poderiam me auxiliar neste erro para a resolução do problema ?? -
Django FORM_RENDERER for frontend only
By default Django uses this setting determine where the form widgets come from: FORM_RENDERER = 'django.forms.renderers.DjangoTemplates' As we want all labels removed, and apply some overrides, it was changed to: FORM_RENDERER = 'django.forms.renderers.TemplatesSetting' This all works fine for the frontend. However, it renders the backend unusable as now all labels are removed there as well. My question, how do I get Django to use the original setting for the admin? -
How to set LOGIN_URL variable in Django settings so it doesn't redirect anywhere while not logged in
When trying to access url get_room_messages if user is not logged in @login_required redirects him to: /accounts/login/?next=/get_room_messages (as specified in docs) I want it to do nothing (or redirect to the original url, in this example /get_room_messages). I don't want to hardcode it like @login_required(login_url='/get_room_messages'), ideal solution would be to get somehow original url and pass it into @login_required() decorator. @login_required() def get_room_messages(request): user_id = request.user.user_ID user = get_object_or_404(CustomUser, pk=user_id) Thank you for help! -
uploading image in Django inside a for loop
I wanted show the uploaded image from admin url in my index.html template. so i needed to put a for loop and I got a probelm in image src. setting.py : STATIC_URL = 'static/' STATICFILES_DIRS = [ BASE_DIR / "static" ] models.py : class Home(models.Model): image = models.ImageField(upload_to = "static") titr = models.CharField(max_length=200) description = models.TextField() created = models.DateField(auto_now_add = True) updated = models.DateField(auto_now = True) class Meta: ordering = ['created'] def __str__(self): return str(self.titr) views.py : from django.shortcuts import render from .models import Home # Create your views here. def index(request): home = Home.objects.all() context = {"homes" : home} return render(request, 'home/index.html', context) index.html(doesn't work) : {% extends 'main.html' %} {% block content %} {% load static %} {% for home in homes %} <br> <h1>{{home.titr}}</h1> <img src="{% static '{{home.image.url}}' %}" style="width:50%" alt="My image"> <p>{{home.description}}</p> <br><hr> {% endfor %} {% endblock content %} index.html(work but it's not what i want): {% extends 'main.html' %} {% block content %} {% load static %} {% for home in homes %} <br> <h1>{{home.titr}}</h1> <img src="{% static '{{home.image.url}}' %}" style="width:50%" alt="My image"> <p>{{home.description}}</p> <br><hr> {% endfor %} {% endblock content %} -
Save data and show it in one http request Django ORM
I'm working on a little app and I'm stuck with one "error" and maybe someone could help me. So basically what I'm trying to achieve is that I want to update two fields from a model (let's say that I have 5 fields in db) and I'm using SomeData.objects.filter(id=pk).update(data=test, data1=test1) but the idea is that I conclude that is necessary to send two requests from views.py ( first request will update the db and the second one will output data desired). The big question is, how can I achieve this in one single http call? The http method is GET but I'm sure that it doesn't matter. Thanks in advance! -
Django Rest Framework - search_fields - DatabaseError at /chapters/ No exception message supplied
Based on the documentation of DRF search_fields, i have implemented search filter in one of my APIs with Foreign key field. So while searching i am facing this error. Can you guys please help me out to get this issue resolved? This is my Parent Model class Chapter(models.Model): id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=256) short_code = models.CharField(max_length=256, blank=True) description = models.TextField(blank=True) start_date = models.DateField(default=None) end_date = models.DateField(default=None) status = models.PositiveIntegerField(default=1) created_by = models.CharField(max_length=256, default=None) this is my child model class ChapterTopicTag(models.Model): id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=256, blank=True) parent_id = models.ForeignKey(Chapter, on_delete=models.CASCADE) And this is my viewset class ChapterViewSet(viewsets.ModelViewSet): serializer_class = ChapterSerializer filter_backends = [filters.SearchFilter, DjangoFilterBackend] filterset_fields = ['status'] search_fields = ('name', 'description', 'chpatertopic__name',) Whenever i am calling url like http://localhost:8000/parent/?search=childname It throws me this error which is attached in screenshot -
Cache problems in Django/PyMongo/MongoDB
I have a little Django app that uses PyMongo and MongoDB. If I write (or update) something in the database, I have to restart the server for it to show in the web page. I'm running with 'python manage.py runserver' I switched to the django dummy cache but that didn't help. Every database action is within an 'with MongoClient' statement. -
failed to solve: rpc error: code = Unknown desc = failed to solve with frontend dockerfile.v0:failed to read dockerfile: read /va.how do i solve this
On startup, the following error appears. OS win 10. how do i solve this problem? (venv) C:\shop>docker-compose up --build [+] Building 0.1s (2/2) FINISHED => [internal] load build definition from shop 0.1s => => transferring dockerfile: 1.78MB 0.0s => [internal] load .dockerignore 0.1s => => transferring context: 2B 0.0s failed to solve: rpc error: code = Unknown desc = failed to solve with frontend dockerfile.v0: failed to read dockerfile: read /var/lib/docker/tmp/buildkit-mount057531924/shop: is a directory Dockerfile and docker-compose are in the root of the project. dima@DESKTOP-1BLNH42:/mnt/c/shop$ ls Dockerfile account blog cart discount_system docker-compose.yaml favorites loyalty_program manage.py orders projectshop requirements.txt search shop venv Dockerfile: FROM python:3.9 RUN apt-get update -y RUN apt-get upgrade -y WORKDIR /app COPY ./requirements.txt ./ RUN pip install -r requirements.txt COPY . ./src CMD ['python3', './src/manage.py', 'runserver', '0.0.0.0:8000'] docker-compose: version: '3.9' services: rabbitmq: image: rabbitmq restart: always web: restart: always build: context: ./shop ports: - 8000:8000 command: ['python3', './src/manage.py', 'runserver', '0.0.0.0:8000'] depends_on: - pg_db pg_db: image: postgres:14 volumes: - postgres_data:/var/lib/postgresql/data/ volumes: postgres_data: -
Celery_worker fixture in pytest, connection already closed error
I have such pytest structure import pytest @pytest.mark.django_db class TestClass: def test_celery_mht_notification_create(self, celery_worker, user): # some test logic When I use celery_worker fixture, I get such error psycopg2.InterfaceError: connection already closed How to fix that? -
How can I instantiate multiple models on one user button press (Django)?
Design example image Code Snippet I'm trying to put together a CRM sort of website that allows users to create subjects and have tasks listed under them. These tasks all have a red or green circle under each week based on its completion status for that week. The problem is I'm not sure how to piece this all together. I can create a task object and have it be listed under the subject but cant find a way to create multiple completion objects and have each one link in with every task and week to allow the user to check off what they completed. I'd really appreciate if someone could point me in the direction as to how to split up the logic for these models so that I can piece them together. Thank you :D -
Django rest framework returning base64 image URL encoded
I have my viewset that returns a basse64 encoded image in the image variable: with open(f"image_file.jpg" , "rb") as image_file: order.image = base64.encodebytes(image_file.read()).decode('utf-8') The thing is, if this code is executed locally like python script.py it returns the right base64 and I can display it, but this viewset is returning a base64 that's URL encoded. Instead of returning something like NMR//9k=, it's returning NMR/9k%3D%0A. How can I change this? I need the proper base64 encoding to display the image on the front.