Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python, Django, Hope to save a user's click event to database immediately, when clicking <a href...> link
I'm a newbie on programming and English is not my mother tongue. Also it is the first time to leave a question. Until now I just solved the problems by searching, reading and trying when I had a question. But I couldn't get any answer to solve my problems for now. So I post my question with a broken English. I'm developing a web with Python, Djanog. When a vistor clicking a link <a href="tel:00-0000-0000-0000">00-0000-0000-0000</a> on my web page, hope to save this event into my database(mysql) immediately. A user visits on index page, def storekeylog() makes data like IP, Full_query, Key_input and so on. then save it to database(def keylog()) in real time. For it, a user doesn't need to do anything. I use datatables(https://datatables.net/). At first, I was trying to use Ajax, but I couldn't get any result. On Ajax and Datatales, I didn't know before, but I met them in here. I can check it on my page 'mydomain.net/docu/keylog_list/' It works well. But I don't know how to save a user's click event on index page to database, then show it on 'mydomain.net/docu/keylog_list/' as well. My goal is to check a user with a specific query(keyword from … -
How to encrypt decrypted text by django-fernet-fields?
I am using django-fernet-fields, and documentation says By default, django-fernet-fields uses your SECRET_KEY setting as the encryption key. my SECRET_KEY in django is the one created by django let say it is "XXXX". my dectypted text is "gAAAAABfIrFwizr11ppteAXE3MOMItPDNfNkr5a4HcS3oiT7ih4Ln7y6TeCC5uXWPS3Yup_0s7whK3T44ndNlJRgc0Ii4_s3_A==" when I try to encrypt it by using the code below token = SECRET_KEY f = Fernet(token) d =f.decrypt(b"gAAAAABfIrFwizr11ppteAXE3MOMItPDNfNkr5a4HcS3oiT7ih4Ln7y6TeCC5uXWPS3Yup_0s7whK3T44ndNlJRgc0Ii4_s3_A==") print(d) it throws an error, error is ValueError: Fernet key must be 32 url-safe base64-encoded bytes. how can i avoid this error? -
Django CaptureQueriesContext can't see my objects filter query in captures_queries
I want to log the raw SQL statements in my Django testcases. I can see the INSERT sql statements, but I can't see the SELECT sql statements in the log. I want to see every SQL statement in the log, whether it is CREATE, SELECT, UPDATE or something else. Output $ python manage.py test <OUTPUT OMITTED> Found 1 test(s). Running tests... ---------------------------------------------------------------------- [{'sql': 'INSERT INTO "myapp_testtabletwo" ("test_field") VALUES (\'abc\') RETURNING "myapp_testtabletwo"."id"', 'time': '0.001'}] . ---------------------------------------------------------------------- Ran 1 test in 0.113s OK Destroying test database for alias 'default'... Closing active connection tests.py from django.db import connection from my_app.models import TestTableTwo class DatabaseExampleTests(TestCase): databases = '__all__' def test_example(self): with CaptureQueriesContext(connection) as ctx: created_object = TestTableTwo.objects.create(test_field="abc") all_objects = TestTableTwo.objects.all() print(ctx.captured_queries) models.py from django.db import models class TestTableTwo(models.Model): id = models.AutoField(primary_key=True) test_field = models.CharField(max_length=100, blank=True, null=True) settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': "testpostgres", 'USER': "postgres, 'PASSWORD': "password", 'HOST': "postgres" } } Version $ python -V Python 3.9.15 $ pip list # output omitted Package Version ---------------------- --------- Django 4.1 psycopg2 2.9.5 -
Django admin inline template for specific field
I have a page like this in site-admin. This is the Inline class class InvoicePaymentInline(admin.TabularInline): model = InvoicePayment raw_id_fields = ("invoice",) extra = 1 readonly_fields = ( "is_paid", "is_active", "paid_amount", "total_amount", "date_due", "date_paid", "deferred_payment_amount", "actions", ) formset = InvoicePaymentFormSet actions_template = get_template("admin/basetransactionlog_invoicepayment.html") @model_admin.display def actions(self, item: InvoicePayment) -> str: return self.actions_template.render({"payment": item}) @model_admin.display(boolean=True) def is_active(self, item: InvoicePayment) -> bool: return item.invoice.is_active @model_admin.display(boolean=True) def is_paid(self, item: InvoicePayment) -> bool: return item.invoice.is_paid ... What I want to do is to render invoice field with a specific template. Is that possible? -
React + Django - Access has been blocked by CORS
I'm trying to make an app using django and react which is gonna catch some data from twitter. Firstly I tried to catch data by directly from front end - React App - Issue with CORS - access to fetch has been blocked by cors policy , but I was told that I should do it from backend (if I correctly understood) and I tried to do it like that: views @api_view(['GET']) def getTweets(request, username="twitterdev"): auth = tweepy.OAuthHandler(api_key, api_key_secret) auth.set_access_token(access_token, access_token_secret) api = tweepy.API(auth) user1 = api.get_user(screen_name=username) return Response(user1._json) *used variables like api_key etc are being imported from other file. *do not pay attention that view is called getTweets and is getting user data. I want to change it when I get rid of CORS issues export default function Home(){ const [content, setContent] = useState(); useEffect(() => { const url = "http://127.0.0.1:8000/api/get"; fetch(url, { method: 'GET', headers: { 'Content-Type': 'application/json', } }) .then((response) => { if(response.status === 404){ console.log('404'); } else{ console.log(response.status) } }) .then((data) => { setContent(data) }) .catch((e) => { setContent(e.message); }) }, []) return(<div>{content}</div>) } but I'm still getting the same result. What am I doing wrong ? Is my approach to this case correct in anyhow … -
How I control not defined URLs in Django
My declared paths are urlpatterns = [ path('admin/', admin.site.urls), path('projects/',include('projects.urls')), path('', include('users.urls')), ] if user enter wrong URLs outside of my deceleration. How I control That? urlpatterns = [ path('admin/', admin.site.urls), path('projects/',include('projects.urls')), path('', include('users.urls')), ] -
How to load up the whole Django project (including js files) when testing with webdriver in Selenium?
I am using Selenium to test my Django project's JavaScript. The web driver is getting the index.html which is the home page but the JavaScript is not loading up in my index.html page (as if I were running the whole project, not individual page/template). How do I load up the whole Django project for the web driver to get the intended result? I ran the test file and got the following error: "self.assertEqual(driver.find_element(By.ID, "cash-table-usd").text, 100) AssertionError: '{{ usd|intcomma }}' != 100" {{ usd|intcomma }} is templated as I believe other files in my Django project is not loading up. I was expecting it to be 0 initially, then becomes 100 after the click button in the test. from selenium import webdriver from webdriver_manager.chrome import ChromeDriverManager from selenium.webdriver.common.by import By def file_uri(filename): return pathlib.Path(os.path.abspath(filename)).as_uri() driver = webdriver.Chrome(ChromeDriverManager().install()) class ClientSideTests(unittest.TestCase): def test_deposit_withdraw(self): driver.get(file_uri("portfolio/templates/portfolio/index.html")) balance = driver.find_element(By.ID, "cash-table-usd").text driver.find_element(By.ID, "cash-amount").send_keys(100) cash_submit = driver.find_element(By.ID, "cash-button") cash_submit.click() self.assertEqual(driver.find_element(By.ID, "cash-table-usd").text, 100) if __name__ == "__main__": unittest.main() -
Getting code signature issue for python's lib-dynload library in macos ventura
I have configured apache server for my Django app using mod_wsgi module. So after the configuration when I am trying to start the server, it is throwing error and I am seeing the below logs for the lib-dynload library. I tried self-signing this library but still it is giving me the same error. ImportError: dlopen(/Users/yadavv2/.pyenv/versions/3.9.5/lib/python3.9/lib-dynload/math.cpython-39-darwin.so, 0x0002): tried: '/Users/yadavv2/.pyenv/versions/3.9.5/lib/python3.9/lib-dynload/math.cpython-39-darwin.so' (code signature in <0122F4AE-8D49-3E40-832E-E54BABAE20DB> '/Users/yadavv2/.pyenv/versions/3.9.5/lib/python3.9/lib-dynload/math.cpython-39-darwin.so' not valid for use in process: mapped file has no Team ID and is not a platform binary (signed with custom identity or adhoc?)) Can someone share any ideas on this issue, I am stuck on this for a long time. Not able to bring up my django app using apache because of this error. -
Wagatail Custom User models not displaying ModelChoiceField
Im using wagtail 4.1 & Django 4.1 I'm trying to create a custom User model which selects from a Snippet I have created. class User(AbstractUser): custiommodel= models.ForeignKey(CustomModel, on_delete=models.SET_NULL, null=True, blank=False) user_type = models.CharField(blank=False, null=False, max_length=20, choices=USER_TYPE_CHOICES) panels = [ FieldPanel('custommodel'), FieldPanel('user_type'), ] class CustomUserCreationForm(UserCreationForm): user_type = forms.ChoiceField(required=True, choices=USER_TYPE_CHOICES, label=_("User Type")) custommodel = forms.ModelChoiceField(queryset=CustomModel.objects, required=True, label=_("Select Organisation")) In my settings I have WAGTAIL_USER_EDIT_FORM = 'users.forms.CustomUserEditForm' This used to previously work on older versions of wagtail. Now the only custom filed i can see from above is 'user_type' which means it's finding the correct file but won't display custom models. Is this related to this bug which won't allow me to directly register_snipets in the model file but instead in 'wagtail_hooks.py' through view sets? -
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 ?