Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
request.user in createdview
How implement that the user in the Model Entities add automatically the user that is authenticated in django? now, returning the following error: error I have tried differents methods that i have founding in the internet but not function. all cases return error in the momento to record a row. only, i need that, in the moment that create a row, the user field was the user that is authenticated. My Model: class Entities(models.Model): #class Category(models.Model): id = models.BigAutoField(primary_key=True) code = models.CharField(verbose_name='Código', max_length=10, blank=False, unique=True, help_text='Codigo de entidad.') name = models.CharField(max_length=150, verbose_name='Nombre', unique=True, help_text='Nombre de la entidad.') desc = models.CharField(max_length=500, null=True, blank=True, verbose_name='Descripción', help_text='Descripción de la entidad.') name_report = models.CharField(verbose_name='Nombre Reporte', max_length=100, blank=False, unique=True, help_text='Rellenar para ACTIVAR el reporte') long_desc = models.CharField(verbose_name='Descripción Larga', max_length=800, blank=True, help_text='Descripción larga. Máximo 800 caracteres.') language = models.CharField(verbose_name='Idioma', max_length=2, choices=languages, default='ES', help_text='Idioma del reporte') user = models.ForeignKey(User, default=0, verbose_name='Usuario', on_delete=models.DO_NOTHING) date_created = models.DateTimeField(default=timezone.now, verbose_name='Creado', blank=False, unique=False) date_updated = models.DateTimeField(default=timezone.now, verbose_name='Actualizado', blank=False, unique=False) historical = HistoricalRecords() def __str__(self): return self.name def toJSON(self): item = model_to_dict(self) return item class Meta: verbose_name = 'Entidad' verbose_name_plural = 'Entidades' ordering = ['id'] My CreateView: class entitiesCreateView(LoginRequiredMixin, ValidatePermissionRequiredMixin, CreateView): model = Entities form_class = EntitiesForm template_name = 'Entities/create.html' success_url = reverse_lazy('erp:entities_list') … -
Certbot failed to authenticate some domains (authenticator: standalone). The Certificate Authority reported these problems:
I am using nginx with docker, but getting error while trying to get ssl certificate. Full trace Certbot failed to authenticate some domains (authenticator: standalone). The Certificate Authority reported these problems: Domain: sub.domain.example.uz Type: unauthorized Detail: 109.205.182.6: Invalid response from https://t.me/Azamat_yamin: "<!DOCTYPE html>\n<html>\n <head>\n <meta charset=\"utf-8\">\n <title>Telegram: Contact @Azamat_yamin</title>\n <meta name=\"vi" Hint: The Certificate Authority failed to download the challenge files from the temporary standalone webserver started by Certbot on port 1337. Ensure that the listed domains point to this machine and that it can accept inbound connections from the internet. Dockerfile FROM nginx # Do this apt/pip stuff all in one RUN command to avoid creating large # intermediate layers on non-squashable docker installs RUN apt-get update && \ apt-get install -y apt-transport-https python3 python3-dev libffi7 libffi-dev libssl-dev curl build-essential gettext-base && \ curl -L 'https://bootstrap.pypa.io/get-pip.py' | python3 && \ pip install -U cffi certbot && \ apt remove --purge -y python3-dev build-essential libffi-dev libssl-dev curl && \ apt-get autoremove -y && \ apt-get clean && \ rm -rf /var/lib/apt/lists/* # Copy in scripts for certbot COPY ./compose/staging/nginx/scripts/ /scripts RUN chmod +x /scripts/*.sh # Add /scripts/startup directory to source more startup scripts RUN mkdir -p /scripts/startup # Copy in … -
my base.html page does not render with the other child pages
I am trying to render my base.html template into other templates. I have used ajax calls to get the data on the runtime to make cards for the website as well. The issue i am facing is that my base.html does not gets loaded nor my data for the cards is available. I have used the technique os.path.join. I have tried correcting the format of the doc as the base.html TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] -
Django css is not reflected
Django css is not reflected. I have checked for typos and cleared the cache, but to no avail. I have tried several solutions on the Internet, but they did not solve the problem, so I am asking this question. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] STATIC_URL = '/static/' STATICFILES_DIRS = ( [ os.path.join(BASE_DIR, "static"), ] ) <head> <meta http-equiv="Content-Type" content="text/html; charset=shift_jis" /> <title>不動産</title> <meta name="Keywords" content="不動産,ショップ,店舗,キーワード01,キーワード02,キーワード03" /> <meta name="Description" content="不動産・店舗用HTMLテンプレート no.005。ここにページの説明文を入れます。" /> {% load static %} <link rel="stylesheet" type="text/css" href="{% static"css/style.css" %}"> <script type="text/javascript" src="js/jquery.js"></script> <script type="text/javascript" src="js/jq_dim.js"></script> <script type="text/javascript" src="js/script.js"></script> <script type="text/javascript" src="js/jquery.ui.core.js"></script> </head> enter image description here -
How can I return new line in return statement?
I'm returning a statement in one of my models but I cannot use \n for a new line. I do not know why. How can I fix it? class MyModel(Base): ... def __str__(self): entity = self.entity_type() return f'{entity}: {self.identifier} \nMerchant Name: {self.company_name} \nMCC Code: {self.category_code}' -
Pass data from model clean function to template
Is there a way to pass a dictionary of errors from def clean function to the template ? I think that context_processors can do the trick but not sure if its the correct way. -
docker-compose not working on Azure App Service
I have pushed 4 images to Azure Container Registry: django-app, celery-worker, celery-beats and nginx. I have created docker-compose file that I used to created images and I want to upload to Azure App Service but I am getting this error: Exception in multi-container config parsing: YamlException: (Line: 12, Col: 9, Idx: 256) - (Line: 12, Col: 35, Idx: 282): Bind mount must start with ${WEBAPP_STORAGE_HOME}. I changed WEBSITES_ENABLE_APP_SERVICE_STORAGE to true. Below you can find docker-compose file I am uploading to Azure: version: '3' services: app: container_name: app.azurecr.io/app-app build: context: ./backend dockerfile: Dockerfile restart: always command: python manage.py runserver 0.0.0.0:8000 volumes: - backend/:/usr/src/backend/ networks: - app_network ports: - 8000:8000 env_file: - .env celery_worker: container_name: app.azurecr.io/app-celery_worker restart: always build: context: ./backend command: celery -A app_settings worker --loglevel=info --logfile=logs/celery.log volumes: - backend:/usr/src/backend networks: - app_network env_file: - .env depends_on: - app celery-beat: container_name: app.azurecr.io/app-celery-beat build: ./backend command: celery -A app_settings beat -l info volumes: - backend:/usr/src/backend networks: - app_network env_file: - .env depends_on: - app nginx: container_name: app_nginx restart: always build: ./azure/nginx ports: - "8080:8080" networks: - app_network volumes: - static_volume:/home/app/web/staticfiles - media_volume:/home/app/web/mediafiles depends_on: - app volumes: - backend: - static_volume: - media_volume: Below you can see my mouted storages I created in … -
How to create user status active deactivate switch button in personal admin panel in Django?
How to create user status active deactivate switch button in personal admin panel in Django and show categor if active or inactive I want something like this in my Django . enter image description here Can anyone tell me how should I code in html template and views.py and model ? Best path way how i can implement -
How to set the value of field dynamically in Model Class Django
I am new to django. I have following models: class MeetingUpdate(models.Model): meeting = models.ForeignKey("Meeting", on_delete=models.CASCADE) employee = models.ForeignKey("Employee", on_delete=models.CASCADE) work_done = models.TextField() class Meeting(models.Model): team = models.ForeignKey("Team", on_delete=models.CASCADE) name = models.CharField(max_length=128, unique=True) created_at = models.DateTimeField() class Team(models.Model): name = models.CharField(max_length=128) members = models.ManyToManyField("Employee") class Employee(models.Model): name = models.CharField(max_length=128) In my MeetingUpdate model class, employee attribute should display only those employees which are in a particular team, but currently it shows all the employees. How to do it? -
upload image in AWS s3 with my sql database in python django
i have mysql database and i would store the image link in char field and upload on AWS s3 bucket in python django. i upload image via postman and strore in AWS s3 and with mysql database in python django -
How to update template upon post_save with data from the database with *Django Channels*?
How can I update the template with Django signals when a post_save signal is triggered and update the template through Django channels with the recently added database entries. Client side javascripts (channels.js): const roomName = 'test' const chatSocket = new WebSocket( 'ws://' + window.location.host + '/ws/chat/' + roomName + '/' ); chatSocket.onopen = function(e) { console.log("Websocket connection is open") }; chatSocket.onmessage = function(e) { const data = JSON.parse(e.data); console.log(data.message) console.log(data) }; chatSocket.onclose = function(e) { console.error('Websocket closed unexpectedly'); }; Consumers.py: from channels.generic.websocket import WebsocketConsumer from asgiref.sync import async_to_sync import json from .models import * class PlanningConsumer(WebsocketConsumer): def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'planning_%s' % self.room_name print("Room name: " + self.room_name) # Join room group async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() def disconnect(self, close_code): # Leave room group async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) # Receive message from WebSocket def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] # Send message to room group async_to_sync(self.channel_layer.group_send)( self.room_group_name, { 'type': 'planning.message', 'message': message } ) # Receive message from room group def planning_message(self, event): print(event) message = event['message'] planning_entry = PlanningEntry.get_planning_entry_data(subject) print("Planning entry: " + str(planning_entry)) # Send message to WebSocket self.send(text_data=json.dumps({ 'message': message, 'planning_entry': planning_entry })) Signals.py: from django.db.models.signals import post_save from django.dispatch import … -
DB partioning in django
While trying to improve the performance i stumbled upon db partioning so i followed "https://architect.readthedocs.io/features/partition/mysql.html#" and now while i try to implement the same i'm facing an issue from django.db import models from django.contrib.auth.models import User from model_utils.models import TimeStampedModel # from django_mysql.models import JSONField import jsonfield import architect @architect.install('partition', type='range', subtype='date', constraint='month', column="created") class StateCityPincodeMapping(TimeStampedModel): ENABLE = 1 DISABLE = 0 DELETED = 2 STATUS_OPTIONS = ( (ENABLE, 'active'), (DISABLE, 'inactive'), (DELETED, 'deleted') ) original = models.ForeignKey(Area, on_delete=models.SET_NULL, null=True, blank=True, related_name="StateCityPincodeMapping_Area") insurer = models.ForeignKey(InsurerStateCityPincode, on_delete=models.SET_NULL, null=True, blank=True, related_name="StateCityPincodeMapping_InsurerStateCityPincode") status = models.IntegerField(choices=STATUS_OPTIONS, default=ENABLE) def __str__(self): return self.original.name if self.original is not None else "" class Meta: unique_together = ('original', 'insurer', 'status') verbose_name = "Insurer State City Pincode Mapping" verbose_name_plural = "Insurer State City Pincode Mapping" Error that i get while running the below command Command :- architect partition --module common.models Error Msg:- architect partition: error: unsupported partition function for column type "None" in "StateCityPincodeMapping" model, supported column types for "mysql" backend are: date, datetime, timestamp -
django project: isort ignores local .cfg file's "skip" parameter
I'm using "isort" in my Django project and the problem is when I make the isort command on the project level it ignores app-level ".isort.cfg" file's skip parameters. My isort version is 5.11.4. The local/app level ".isort.cfg" file: [settings] known_django=django sections=FUTURE,STDLIB,DJANGO,THIRDPARTY,FIRSTPARTY,LOCALFOLDER skip=migrations How to force it to not ignore nested folders cfg files? -
Django doesn't find some static files
I'm working on a project and since some days, one specific image cannot be found anymore. Everytime I reload the page, this line in the console appears: "GET /staticfiles/my_app/images/Logo.svg HTTP/1.1" 404 5715 I know that the image exists because sometimes it appears for a short moment (until you reload again) and other images in the same folder as the Logo.svg are also loading so I guess that the path is not the problem. The setting for the STATICFILES_DIRS is also correct since other things do work. STATICFILES_DIRS = ( os.path.join('my_app/static'), ) Did anyone have a problem like this before? -
Django Axes Log Turnover Time
Could not find the answer to this rather trivial question within the documentation... I am using Django Axes to track and log the access to my Django applications. In the admin interface I see very old logins older than 2 years. Is there a setting where I can tell Axes to automatically delete log entries older than time X? -
I'm trying to connect to oracle data base from django and i got this erorr(ORA-03113: end-of-file on communication channel )
I'am using django 4.1 and oracle 9.2 , when i'm trying to connect to oracle from django , i got this erorr ORA-03113: end-of-file on communication channel Process ID: 0 Session ID: 0 Serial number: 0 this is my connection DATABASES = { 'default': { 'ENGINE': 'django.db.backends.oracle', 'NAME': '***', 'USER': '***', 'PASSWORD': '***', 'HOST': '***', 'PORT': '***', } } what is the problem ? -
How to use native sql elegantly in django?
In django, sometimes I have to write some native sql, which looks long and ugly,such as: SELECT 'TT' P_TYPE, KEY_NAME NAME, KEY_VALUE_1 || ' ' || KEY_VALUE_2 || ' ' || KEY_VALUE_3 || ' ' || KEY_VALUE_4 || ' ' || KEY_VALUE_5 || ' ' || KEY_VALUE_6 || ' ' || KEY_VALUE_7 VALUE, ADD_DATE FROM MY_T1_TABLE UNION ALL SELECT 'TT' P_TYPE, KEY_NAME NAME, KEY_VALUE_1 || ' ' || KEY_VALUE_2 || ' ' || KEY_VALUE_3 || ' ' || KEY_VALUE_4 || ' ' || KEY_VALUE_5 || ' ' || KEY_VALUE_6 || ' ' || KEY_VALUE_7 VALUE, ADD_DATE FROM MY_T2_TABLE UNION ALL SELECT 'EE' P_TYPE, NAME, VALUE, ADD_DATE FROM MY_E1_TABLE UNION ALL SELECT 'EE' P_TYPE, NAME, VALUE, ADD_DATE FROM MY_E2_TABLE I hope there is a way to integrate all the native sql in my code to make the code look more beautiful.I have tried putting all the sql into a py file, using variables to define and call the sql, I don't know if this is a good solution, or who has a better solution? -
Hiding extra field Django Admin
I want to display an extra field based on a boolean check associated with the model. if obj.boolean: exclude(self.extra_field) But the issue with this is that the extra field is not associated with the model so it is throwing error stating model does not contain this extra field. The output that i am looking for is that, when this boolean is true the extra field should not get displayed in the model admin as well as model inline. But when it is false it should get displayed. How can i achieve this? -
It is impossible to add a non-nullable field 'name' to table_name without specifying a default
I have added a following field in my already existing model: name = models.CharField(max_length=128, unique=True) But it is giving following prompt when applying migrations: It is impossible to add a non-nullable field 'name' to table_name without specifying a default. This is because the database needs something to populate existing rows. Please select a fix: 1) Provide a one-off default now (will be set on all existing rows with a null value for this column) 2) Quit and manually define a default value in models.py. I cannot set it's attributes to blank=True, null=True as this field is must. I cannot set it's default value as the field has to be unique. If I try to set it's default value in command prompt, it says plz select a valid option. How to fix it? -
CheckConstraint checking that the sum of fields do not exceed a value
How should one approach writing a CheckConstraint for model that triggers when the sum of two fields exceeds the value of another? I am able to do a CheckConstraint that triggers when the value of one field exceeds another. How do I adapt that to include summation? (i.e. to modify check=models.Q(entry__lte=models.F("limit")), to something like check=models.Q(F('entry') + F('extra') <= models.F("limit")) -
How to create Amazon Clone using Django or DRF?
I want to create a Amazon clone what should I use Django or DRF(Django Rest Framework) for it what process should i follow to create this project. What will be more feasible for this project Django or DRF? -
Django websocket how to send message from server immediately
I has a long time task in django, then I want to use channels instead of loop http request. I create a asgi server follow the tutorial. It can work but i don't know how to send a message twice. I want the server send 'msg1' ===> then sleep 3s ===> then send 'msg2' Here is my consumer code import datetime import json import time from channels.generic.websocket import AsyncWebsocketConsumer class MessageConsumer(AsyncWebsocketConsumer): def __init__(self, *args, **kwargs): super().__init__(args, kwargs) self.group_name = 'BUILD' async def connect(self): # Join group await self.channel_layer.group_add( self.group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): await self.channel_layer.group_discard( self.group_name, self.channel_name ) # Receive message from WebSocket async def receive(self, text_data=None, bytes_data=None): text_data_json = json.loads(text_data) message = text_data_json['message'] if message == 'build': await self.build() async def sendMsg(self, data): # Send message to group await self.channel_layer.group_send( self.group_name, { 'type': 'sender', 'data': data } ) # Receive message from group async def sender(self, event): event.pop('type') # Send message to WebSocket await self.send(text_data=json.dumps(event)) print('send', datetime.datetime.now()) # takes long time async def build(self): await self.sendMsg('msg1') # it doesn't send right now time.sleep(3) # simulate long time await self.sendMsg('msg2') # frontend get two message but when i create a break point, it doesn't print anything … -
How to read additional data posted by form in django forms.py
I'm trying to write kind off bussiness mail management. In simple world, it'll have bunch of mail templates that will use un mailmerge operation There will be 2 kind of user: those who create mail templates, let's call them 'tc' (template creator) thoise who will issueing mails by term of triggering a mail merge. In this post I will only ask about the tc part. The work sequnce will : TC make a MS docx, upload to this web app web app will get all variable names from docx ( I use docxtpl library), and save it on MailTemplate model class. here is my MailTemplate model class class MailTemplate(models.Model): name = models.CharField(max_length=20) tfile = models.FileField(upload_to='uploads/mailtemplate', null=True, blank=True) schema = models.CharField(max_length=256, blank=True, null=True, editable=False) # conto: ['{"name": "kepada", "label": "Kepada", "type": 2, "format": ""}'] def __str__(self) -> str: return self.name all variables gathered by docxtpl, is combined in the form as list-of-dicts and saved in MailTemplate.schema example: [{"name": "date", "label": null, "type": 2, "format": ""}, {"name": "invoiceNumber", "label": null, "type": 2, "format": ""}, {"name": "company", "label": null, "type": 2, "format": ""}, {"name": "total", "label": null, "type": 2, "format": ""}] When TC first update new template, MailTemplate.schema is still empty. I make … -
How to run midee doctr in python file?
When I was trying to run the below code with python file : import os os.environ['USEA-TF'] ='1' from doctr.io import DocumentFile from doctr.models import ocr_predictor model = ocr_predictor(pretrained=True) document = DocumentFile.from_images('IM.jpg') result = model(document) result.show(document) json_response = result.export() print(json_response) Getting this error :- ImportError: cannot import name 'OrderedDict' from 'typing' (c:\users\shubham nagar\appdata\local\programs\python\python37\lib\typing.py) How will I able to run in .py file -
dockerizing django,nginx,gunicorn return exited code 3
Im new to learn this django in docker. Im following this guide: https://testdriven.io/blog/dockerizing-django-with-postgres-gunicorn-and-nginx/ In my lab ubuntu server 22.04, all working well until nginx part, i up and build the docker-compose.prod.yml and result the "web" services is exited by code 3. And when i browse http://localhost:1337, it show me 502 Bad Gateway. What is this issue? I cant found any relate error about this. Tried to google but no luck.