Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Sentry + Django: unable to assign tag to event
I'm trying to set up logging for a Django application using Sentry. And I want to use custom tags. I try to assign a tag in the before_sent method for each one event, but these tags do not appear on the self-hosted Sentry. import sentry_sdk from sentry_sdk.integrations.django import DjangoIntegration def before_send(event, hint): with sentry_sdk.push_scope() as scope: scope.set_tag('test_tag', 'some_test') return event sentry_logging = LoggingIntegration(level=logging.INFO, event_level=logging.INFO) sentry_sdk.init( dsn=**my_dsn**, integrations=[ DjangoIntegration(), sentry_logging, ], traces_sample_rate=1.0, before_send=before_send, ) After assignment, I can find tags in scope, but events on the Sentry server do not have these tags. I also tried assigning tags to the middleware: from django.utils.deprecation import MiddlewareMixin from sentry_sdk import push_scope class SentryLogMiddleware(MiddlewareMixin): def process_response(self, request, response): with push_scope() as scope: scope.set_tag('test_tag', 'some_test') return response I also tried using set_tag without push_scope and assigning a tag immediately after the exception. None of this helped me to assign tags to events. But I really want to use them for filtering. What didn't I notice? I will be glad for any hints. -
Forbid Google to display others routes of my website
I'm using DigitalOcean to host an Ununtu VM on which I deployed a website. I'm using React and Django + Gunicorn. My frontend has several routes such as www.mywebsite.com/gallery, www.mywebsite.com/projects, etc ... My problem is that when looking up my website in Google, I find routes which don't exist in my frontend nor in my backend, for example www.mywebsite.com/tag/bali, i don't even have a /tag route (when clicking on it i get redirected to /home thanks to the Navigate component from React router) How can I fix this ? Is it possible to allow Google to only see www.mywebsite.com/home? I tried using the Navigate component from React router, hoping it would fix it, it didn't work. -
How to handle django import-export 'matching query does not exist.' error?
I am using import-export library and trying to add import functionality in admin panel. Resource: class DictCitizen_FisResources(resources.ModelResource): id = fields.Field( column_name='№', attribute='id', ) country_name = fields.Field( column_name='Name', attribute='dict_citizen', widget=ForeignKeyWidget(DictCitizen, field='sname') ) fis_id = fields.Field( column_name='Element Code', attribute='fis_id', ) class Meta: model = DictCitizen_Fis fields = ('id','country_name', 'fis_id',) import_id_fields = ('id',) As u can see, one of the fields in ResourceClass (country_name) has ForeignKeyWidget, which means that when importing data from file - model relation is going to be created. The problem is that, information in the file that i import from, does not always matches ForeignKeyWidget model data that is already in database and as a result i get next errors when trying to imoprt from admin panel: Same error written as a text: Номер строки: 25 - DictCitizen matching query does not exist. 25, БОЛИВИЯ, 238 Traceback (most recent call last): File "C:\venvs\abit\lib\site-packages\import_export\resources.py", line 737, in import_row self.import_obj(instance, row, dry_run, **kwargs) File "C:\venvs\abit\lib\site-packages\import_export\resources.py", line 557, in import_obj self.import_field(field, obj, data, **kwargs) File "C:\venvs\abit\lib\site-packages\import_export\resources.py", line 540, in import_field field.save(obj, data, is_m2m, **kwargs) File "C:\venvs\abit\lib\site-packages\import_export\fields.py", line 119, in save cleaned = self.clean(data, **kwargs) File "C:\venvs\abit\lib\site-packages\import_export\fields.py", line 75, in clean value = self.widget.clean(value, row=data, **kwargs) File "C:\venvs\abit\lib\site-packages\import_export\widgets.py", line 423, in clean return … -
Pass a class member via parameterized.expand
Is it possible to pass a object created in setUpTestData to a test via parameterized.expand? -
Django Javascript to Check Username Availability
I am working on a Django site with django-tenants and I want to check if a username has already been used when new users are signing up for an account. I am a newbie to django and I don't have much experience with javascript. I am attempting to adapt some code I was able to get to work in another site. Currently, I am getting the following error in the console when the ajax call is made: http://localhost:8000/ajax/check-username-email/?username=ad 404 (Not Found) Here is the relevant code: view: # used to create form for adding company (tenant) accounts class CreateTenantView(SuccessMessageMixin, CreateView): form_class = TenantForm template_name = 'public_site/add_tenant.html' success_message = "Company Created Successfully!" success_url = "/join" def form_valid(self, form): user = User.objects.create_user( username=form.cleaned_data.get('username'), password=form.cleaned_data.get('password'), full_name=form.cleaned_data.get('full_name'), email=form.cleaned_data.get('email') ) self.object = form.save(commit=False) self.object.schema_name = unique_slug_generator(self.object, form.cleaned_data.get('company_name')) self.object.user = user self.object.save() domain = Domain() domain.domain = self.object.schema_name domain.tenant = self.object domain.is_primary = True domain.save() self.domain = domain subdomain = self.object.schema_name host = self.request.META.get('HTTP_HOST', '') scheme_url = self.request.is_secure() and "https" or "http" url = f"{scheme_url}://{subdomain}.{host}" with schema_context(self.object.schema_name): User.objects.create_superuser( username=form.cleaned_data.get('username'), password=form.cleaned_data.get('password'), full_name=form.cleaned_data.get('full_name'), email=form.cleaned_data.get('email'), employee_type=None ) return HttpResponseRedirect(url) def check_username_email(request): username = request.GET.get('username') username_exists = Tenant.objects.filter(username=username).exists() email_exists = CustomUser.objects.filter(email=username).exists() context = { 'username_exists': username_exists, 'email_exists': email_exists, } return … -
how to use own permissions and group models instead of auth_group and auth_permission (AbstractBaseUser style)
I need to made own permissions system (not only single permission!) based on groups. But my groups and group_permissions are dynamicaly created from other tables so I would like to create myapp_groupview instead of auth_group and myapp_group_permissions instead of auth_group_permissions. After 8h of searching, testing i found nothing... auth_group is still there and can't find method to get rid of it.... AbstractBaseGroup would be a such easy solution.... -
PythonAnywhere and Cloudflare Certificate Issue
I am using Cloudflare to set up my PythonAnywhere domain. Question: Why are my browsers saying the certificate is a security risk even though I clearly have my keys entered correctly? What I have done so far: Browsersinclude: Safari, Chrome and Firefox. They are saying my Cloudflare Certificate is a security risk. Cloudflare uses LetsEncrypt. Settings: My HTTPS on PyAnywhere is OFF. My Cloudflare Proxies are off > it doesn't work if there on. Meaning www doesn't get sent to my cname The SSL certificates and keys from Cloudflare are entered into PythonAnywhere. The SSL is on Full (Strict) on Cloudflare. And I played around with this and none of them work, full got me the closest to the website error messages loading. Using dig on the Python Anywhere bash console I found that my www is pointing to cname successfully. Thank you for any suggestions. -
How to display celery output on the frontend?
I have a celery task in my project that trigger a command from another project. Everything is working well. I'm running the celery command as celery -A fdaconfig worker --loglevel=info How can I display the outputs of terminal in the frontend? @shared_task def trigger_model(main_config, runmode_config, modelreport): with cd("/another_project"): spark_submit_str = "python3 run_trigger.py " + "/this_project" + main_config process = subprocess.Popen(spark_submit_str, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, shell=True) stdout, stderr = process.communicate() if process.returncode != 0: print(stderr) print(stdout) -
How to make a queryset to refer to all inheriting models that have a separate but the same column?
I would like to catch all products by genre with a single query. Products inherit from Product class but have separate but same column. Is there any reasonable way to do this? models.py class Product(PolymorphicModel): title = models.CharField(max_length=100, blank=True) image = models.ImageField(upload_to='product', default=None) quantity = models.IntegerField(null=False) is_available = models.BooleanField(default=True, null=False) price = models.IntegerField(null=False, blank=False, default=15) popularity = models.IntegerField(default=0) def __str__(self): return str(self.title) def get_absolute_url(self): return reverse("ProductDetail", args=[str(self.pk)]) @property def model_name(self): return self._meta.model_name class CD(Product): GENRE_CHOICES = ( ('Disco', 'Disco'), ('Electronic music', 'Electronic music'), ('Rap', 'Rap'), ('Reggae', 'Reggae'), ('Rock', 'Rock'), ('Pop', 'Pop'), ) band = models.CharField(max_length=100, null=False, blank=False) tracklist = models.TextField(max_length=500, null=False, blank=False) genre = models.CharField(max_length=100, choices=GENRE_CHOICES, null=False, blank=False) class Book(Product): GENRE_CHOICES = ( ('Biography', 'Biography'), ('Criminal', 'Criminal'), ('Fantasy', 'Fantasy'), ('Historical Novel', 'Historical Novel'), ('Horror', 'Horror'), ('Romance', 'Romance'), ('Sci-Fi', 'Sci-Fi'), ) author = models.CharField(max_length=100, null=False, blank=False) isbn = models.CharField(max_length=100, null=False, blank=False, unique=True) genre = models.CharField(max_length=100, choices=GENRE_CHOICES, null=False, blank=False) class Film(Product): GENRE_CHOICES = ( ('Adventure', 'Adventure'), ('Animated', 'Animated'), ('Comedy', 'Comedy'), ('Horror', 'Horror'), ('Thriller', 'Thriller'), ('Romance', 'Romance'), ) director = models.CharField(max_length=100, null=False, blank=False) duration = models.IntegerField(null=False, blank=False) genre = models.CharField(max_length=100, choices=GENRE_CHOICES, null=False, blank=False) The query would work like this products = Product.objects.filter(genre="Disco") -
i have a logistic regression model connected with my django app. So in my model i have a column for example ST_Slope which has 3 string values
i have made some dummy datas. But my problem is, how will a user select for example, when they select flat, how will the model know that flat was selected and it must be assigned as 1 ,and the rest must be 0 am expecting that when a user selects flat on a drop down, the model must know what input the user had -
Blocking Datatables initial table loading display with a loading gif
I have a Django template html page that includes a form for users to upload a data file in JSON format. This data file is then processed, and the data is sent to my PostgreSQL database. The page displays a DataTables table populated by data from the database and three D3 charts. Currently, when I upload a file, I can see the datatable in its raw form for several seconds before the table is fully created. As the table is large, it obscures my D3 chart's initial animations. Ideally, I would like the initial datatable creation to be obscured by a 'loading.gif'. When the datatable creation is complete, I want the user to see the fully formed datatable, and only then do I want the D3 charts to be created/rendered on the page. I have included a loading.gif in my static folder, which correctly displays after file upload. However, after several seconds, the loading.gif disappears, and then, as before, I can briefly see the data in its raw form before the full datatable displays. I am unsure how to completely obscure the datatable creation (with the loading.gif) until the table is fully formed. Here is my DataTables script (below). As … -
Encode error in linux web server and ascii' codec can't encode characters in position 61-62: ordinal not in range(128)
After uploading the Django site to hosting, one of the pages gets a header error. The reason is already found, it is because of different encodings on the servers and when using the function: def view_locale(request): loc_info = "getlocale: " + str(locale.getlocale()) + \ "<br/>getdefaultlocale(): " + str(locale.getdefaultlocale()) + \ "<br/>fs_encoding: " + str(sys.getfilesystemencoding()) + \ "<br/>sys default encoding: " + str(sys.getdefaultencoding()) "<br/>sys default encoding: " + str(sys.getdefaultencoding()) return HttpResponse(loc_info) I get results On the local server: getlocale: ('Russian_Russia', '1252') getdefaultlocale(): ('ru_RU', 'cp1252') fs_encoding: utf-8 sys default encoding: utf-8 And at the time of the hosting: getlocale: (None, None) getdefaultlocale(): (None, None) fs_encoding: ascii sys default encoding: utf-8 And after checking the documentation of the libraries, I can say that ascii table with which the error occurs is used only here. More about the error: UnicodeEncodeError at /input/СТ Б 80x80x2_3600_ОЦ.pdf/extrainf 'ascii' codec can't encode characters in position 61-62: ordinal not in range(128) Unicode error hint The string that could not be encoded/decoded was: l/Pl/СТ Б 80 The error is due to Cyrillic lowercase characters not being included in the ascii. Codewise it occurs when you can't read the name in a function like: 'СТ Б 80x80x2_3600_ОЦ'. def file_assembling(self, input_file, mark_file): … -
Static files being served from the Django app instead of Nginx
My website serves the static files from the Django app instead of the Nginx staticfiles folder but I can't figure out why. My Django app static is on the (Linode) server at: /var/www/DjangoApp/myapp/static/myapp The server static folder is at: /var/www/html/staticfiles/myapp Here's my settings.py: STATIC_URL = '/static/' STATIC_ROOT = '/var/www/html/staticfiles/' Here's my urls.py: from django.contrib import admin from django.urls import path,include from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns = [ path('admin/', admin.site.urls), path('',include('myapp.urls')), ] urlpatterns += staticfiles_urlpatterns() Here's my config file at /etc/nginx/sites-enabled/default: server { server_name helpmesaythis.com; location / { proxy_pass http://172.105.76.53:8000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } location /static/ { root /var/www/html/staticfiles; } listen [::]:443 ssl http2 ipv6only=on; # managed by Certbot listen 443 ssl http2; # managed by Certbot ssl_certificate /etc/letsencrypt/live/helpmesaythis.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/helpmesaythis.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host = helpmesaythis.com) { return 301 https://$host$request_uri; } # managed by Certbot listen 80; server_name helpmesaythis.com; return 404; # managed by Certbot } I have restarted/reloaded Nginx and I have been using collectstatic without success. I have also tried the following changes to the default file: location /static { root /var/www/html/staticfiles; } location … -
django timezone dst change should not be observed for Asia/Tehran after 2023
Since 2023 Tehran observes standard Time all year and DST is no longer in use. Python datetime still uses DST for this zone. for example: timezone.localtime(timezone.now()) returns datetime.datetime(2023, 3, 27, 17, 34, 6, 13634, tzinfo=<DstTzInfo 'Asia/Tehran' +0430+4:30:00 DST>) but it should not consider DST and it should observer standard +3:30 time. does anyone know how to change the DST consideration for Django a specific zone? I have tried to use UTC timezone for my project and manually considering the +3:30 offset but I would like to user Asia/Tehran zone. -
No signatures found matching the expected signature for payload | Django - Webhooks - Stripe
I am using stripe and I am trying to connect webhooks to my local computer using django here is the code I am using to receive Stripe webhooks requet that tell me whether the Payment was secced or not: @csrf_exempt def StripeWebhookView(request): CHECKOUT_SESSION_COMPLETED = "checkout.session.completed" # Listen for success payment payload = request.body sig_header = request.META["HTTP_STRIPE_SIGNATURE"] endpoint_secret=settings.STRIPE_WEBHOOK_SECRET try: event = stripe.Webhook.construct_event( payload, sig_header, endpoint_secret ) except ValueError as e: print(e) return HttpResponse(status=400) except SignatureVerificationError as e: print(e) return HttpResponse(status=400) if event["type"] == CHECKOUT_SESSION_COMPLETED: print(event) what happens is : charge succeeded than Stripe try to send Request with the dat about the purchase but get error 400 enter image description here so I check out and found that I need to : "Make sure you're using the webhook signing secret which matches the Webhook Endpoint delivering the Event, which you can find in the Dashboard after selecting a specific Webhook Endpoint" (text So i double chekc my "webhook signing secret key" and even wrote it directly in my app: enter image description here the problem is gone and the request from Stripe is received by my computer ! To make sure I didn;t make any mistake configuring env.STRIPE_WEBHOOK_SECRET : I double … -
Django get_fields() call __str__ when returning ForeignKeyField Value
I want to be able to display every field with its respective label and value in an . I currently use the DetailView but when it comes to ForeignKeyFields the template renders the id of the related object. Is it possible to call the str method of the related model and display that value instead of its pk ? I already searched for that question but i seem to be the only person who needs this functionality :D -
Surround with tags option not showing for code fragments in PyCharm
I'm trying to surround a django template code fragment similar to the below with tags. {{ my_var }} or {% for i in my_list %} ... {% endfor %} When I press the key combination ⌥ ⌘ T on macOS, the surround with <tag></tag> option shows only if the selected fragment consists of other tags. It doesn't work for code fragments: -
How to customize django-filter DateTimeFromToRangeFilter
I have django-filter class with DateTimeFromToRangeFilter And im looking for way to custom that in my template like split form.work_date on 2 sides or this is not possible? filters.py class PresenceDateFilter(django_filters.FilterSet): work_date = DateTimeFromToRangeFilter( widget=django_filters.widgets.RangeWidget( attrs={'type': 'date', 'class': 'form-control'}, )) class Meta: model = PresenceDetailInfo fields = ('presence_info__counter_presence', 'work_date', ) template.html {% render_field form.work_date %} -
How to create new div when reach end of view port?
I have a for that shows images in the vertical direction, but when you get to the end of the page it keeps showing to the right so it is cut and to see the other images you have to use the horizontal scroll. template.html <div class="vertical-image"> {% for image in list %} <div class="image"> {{image}} </div> {% endfor %} </div> Result: But I would like that when it reaches the end of the view port it creates another <div class="vertical-image"> and continues showing the content below the previous div as in the following example: Does anyone know how I can do this? -
How to send HTTP-request to django inside a docker-compose network?
Background I have a project with a frontend- and a backend-service and am trying to access the django server via HTTP-request. My docker-compose looks like this: services: backend: build: . command: python manage.py runserver 0.0.0.0:8000 ports: - "9005:8000" networks: - test-network frontend: image: my-latest-image depends_on: - backend ports: - "9001:80" networks: - test-network networks: test-network: Issue I am able to successfully execute ping backend from inside the frontend-container, but if I execute curl backend:8000 I get the following message from django: django.core.exceptions.DisallowedHost: Invalid HTTP_HOST header: 'backend:8000'. You may need to add 'backend' to ALLOWED_HOSTS. What I tried Other people who got this message pointed out to include something like ALLOWED_HOSTS = ['backend'] in their 'settings.py'-file (as the error message pointed out). I already did that and am still getting the exact same error message. Is there something I still need to configure or should configure differently to communicate with the 'backend'-service from inside the 'frontend'-service? -
Messes up class names in Django admin panel
[enter image description here][1]Im practicing Django and Ive noticed something weird. For now Im working only in the admin page. Im defining a class model "Meetings", however in the admin panel its defined with double s at the end, why that happens ? models.py: class Meetings(models.Model): title = models.CharField(max_length=200) date = models.DateField() start_time = models.IntegerField(default=time(9)) # Hours duration = models.IntegerField(default=1) room = models.ForeignKey(Room, on_delete=models.CASCADE) def __str__(self): return f"{self.title} at {self.start_time} on {self.date}" admin.py from .models import Meetings admin.site.register(Meetings)``` Im expecting it to have the same name as my definition of it, aka "Meetings" [1]: https://i.stack.imgur.com/auLrj.png -
Sanitizing user input for writing into Python config file
How do you sanitize user input so that it's safe for writing into a Python file? Basically, there is a form where user submit some data, which I need to write into a Python file, userconfig.py. For example, a form field asking for title will be declared as value for TITLE in the file as below - TITLE = "some input by user" I write it simply as myfp.write(f"TITLE = {form.cleaned_data.get('user_title')}\n") The title here can allow a mix of ASCII & non-ASCII characters but still want it to be safe from any code injection. I just want to ensure that this user input is not malicious or has any malicious code in it. -
Django local server issue with env file
I'm using an env file to store passwords for database access. I created a python(db_config.py) file to use them: import os from constant.Const import Const mysql_db_config = Const() mysql_db_config.HOST = os.getenv('DB_MYSQL_HOST') mysql_db_config.USER_NAME = os.getenv('DB_MYSQL_USER') mysql_db_config.PASSWORD = os.getenv('DB_MYSQL_PASS') mysql_db_config.DBNAME = os.getenv('DB_MYSQL_NAME') In the Django seetings.py file I'm importing it and create the database: from project.config.db_config import mysql_db_config DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': mysql_db_config.DBNAME, 'USER': mysql_db_config.USER_NAME, 'PASSWORD': mysql_db_config.PASSWORD, 'HOST': mysql_db_config.HOST, 'PORT': '3306', 'OPTIONS': { 'sql_mode': 'traditional', } } } The problem is that when I'm trying to start the server locally the values are "None" and I can't figure it out what's the reason. -
PyScript - NameError: name 'function' is not defined -- then *.py is load with <py-script src="..."> (DJango)
I have a Python script containing a plot calculation and a function definition: import matplotlib.pyplot as plt import numpy as np from pyscript import Element import datetime x = np.random.randn(1000) y = np.random.randn(1000) fig, ax = plt.subplots() ax.scatter(x, y) display(fig, target="plot") def current_time(): now = datetime.datetime.now() # Get paragraph element by id paragraph = Element("current-time") # Add current time to the paragraph element paragraph.write(now.strftime("%Y-%m-%d %H:%M:%S")) which I want to load into the HTML using DJango expressions combined with the py-script: <py-script src="{% static 'py/script.py' %}"></py-script>. I found that the script is loaded and executed but the function is not recognised by the HTML button. If move the function code directly into the HTML tag, it works. What is going wrong here? Function definition within external py script {% extends "proj/base.html" %} {% load static %} {% block head %} <link rel="stylesheet" href="https://pyscript.net/latest/pyscript.css"/> <script defer src="https://pyscript.net/latest/pyscript.js"></script> <py-config type="toml"> packages = ["numpy", "matplotlib"] </py-config> {% endblock head %} {% block content %} <div id="plot"></div> <button py-click="current_time()" id="get-time" class="py-button">Get current time</button> <p id="current-time"></p> {% endblock content %} {% block script %} <py-script src="{% static 'py/script.py' %}"></py-script> {% endblock script %} results to: Function definition within HTML tag {% extends "proj/base.html" %} {% load … -
How to pass parameter to raw sql in Django
I am trying to create a simple ledger using raw SQL query in Django through my view.py. If I add my parameter value direct I get my required results but if I follow the tutorial here I get the error message below. ERROR MESSAGE ProgrammingError at /books/ledger/1005068200/ not enough arguments for format string Request Method: GET Request URL: http://127.0.0.1:8000/books/ledger/1005068200/ Django Version: 4.1.7 Exception Type: ProgrammingError Exception Value: not enough arguments for format string Exception Location: c:\xampp\htdocs\tammgo\app-env\Lib\site-packages\MySQLdb\cursors.py, line 203, in execute.... CODE I HAVE TRIED views.py from django.shortcuts import render from django.core.paginator import Paginator from django.contrib import messages from django.db.models import Q from django.shortcuts import redirect, render, reverse from django.urls import reverse_lazy from django.http import HttpResponse from books.forms import VoucherForm, GlForm, PersonForm, GlgroupForm, AccountForm from . models import Voucher, Gl, Persons, Glgroup, Account from django.views import generic from django.views.generic import ( CreateView, DetailView, View, ) class BookLedgerView(DetailView): model = Voucher template_name = "books/Vourcher_ledger.html" def get(self, request, *args, **kwargs): sql = '''SELECT datecreated, accountnumber, vtype, id, accountnumber, datecreated, debit, credit, @balance:= @balance + debit - credit AS balance FROM (SELECT datecreated, id, accountnumber, vtype, amount, @balance:=0, SUM(CASE WHEN vtype='dr' THEN amount ELSE 0 END) AS debit, SUM(CASE WHEN vtype='cr' THEN amount ELSE …