Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I would like to disable the clickable link only for an object in Django-admin
I would like to disable the clickable link in the django admin object so that the displayed link is only as plain text without <a href ... in HTML. The current code looks like this current situation in the code here is where I would like to disable the clickable link, which would be displayed as plain text e.g. in /csvinput/3c1927f2-9ef6-45b8-a9aa-0021ef64a46f/change/.(of course I would like to keep the functionality for uploading the csv file mean /csvinput/add/) display on page of instance object /csvinput/3c1927f2-9ef6-45b8-a9aa-0021ef64a46f/change/ Many thanks for every thought or idea. -
Django admin page if statements
I'm building a webpage to present sports results but on the admin page I want it, to when a certain sport is set, the points will change to be a certain number of points like this: sports = [ ('Voléi', 'Voleibol'), ('Fut', 'Futebol'), ] team_name = models.CharField(max_length=50, blank=False, null=False, default="") sport = models.CharField(max_length=20, blank=False, null=False, choices=sports) final_score = models.IntegerField(blank=False, default=0) game_date10 = models.DateField() game_description = models.TextField(blank=True, null=True) The Sport is a list of tuples to choose and when you choose, for example, voleibol the final_score field is supposed to change to 1 or 2 points and not infinite, can I do that? -
Cannot find pg_config executable
Having no idea what pg_config is, I searched online and it seems to be part of or connected to PostgreSQL. I don't have or use that though and never have but I suspect that I may be getting this because I recently started using azure libraries in Python (I never had this problem before). Here is one of the error messages: WARNING: Discarding https://files.pythonhosted.org/packages/aa/8a/7c80e7e44fb1b4277e89bd9ca509aefdd4dd1b2c547c6f293afe9f7ffd04/psycopg2-2.9.1.tar.gz#sha256=de5303a6f1d0a7a34b9d40e4d3bef684ccc44a49bbe3eb85e3c0bffb4a131b7c (from https://pypi.org/simple/psycopg2/) (requires-python:>=3.6). Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. Using cached psycopg2-2.9.tar.gz (379 kB) Preparing metadata (setup.py) ... error ERROR: Command errored out with exit status 1: command: 'C:\Users\E\AppData\Local\Programs\Python\Python310\python.exe' -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\E\\AppData\\Local\\Temp\\pip-install-q50_w0n5\\psycopg2_b3e7f5e155154965bfc0d5340d85b1ff\\setup.py'"'"'; __file__='"'"'C:\\Users\\E\\AppData\\Local\\Temp\\pip-install-q50_w0n5\\psycopg2_b3e7f5e155154965bfc0d5340d85b1ff\\setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base 'C:\Users\E\AppData\Local\Temp\pip-pip-egg-info-ufqtnd89' cwd: C:\Users\E\AppData\Local\Temp\pip-install-q50_w0n5\psycopg2_b3e7f5e155154965bfc0d5340d85b1ff\ Complete output (23 lines): running egg_info creating C:\Users\E\AppData\Local\Temp\pip-pip-egg-info-ufqtnd89\psycopg2.egg-info writing C:\Users\E\AppData\Local\Temp\pip-pip-egg-info-ufqtnd89\psycopg2.egg-info\PKG-INFO writing dependency_links to C:\Users\E\AppData\Local\Temp\pip-pip-egg-info-ufqtnd89\psycopg2.egg-info\dependency_links.txt writing top-level names to C:\Users\E\AppData\Local\Temp\pip-pip-egg-info-ufqtnd89\psycopg2.egg-info\top_level.txt writing manifest file 'C:\Users\E\AppData\Local\Temp\pip-pip-egg-info-ufqtnd89\psycopg2.egg-info\SOURCES.txt' Error: pg_config executable not found. pg_config is required to build psycopg2 from source. Please add the directory containing pg_config to the $PATH or specify the full executable path with the option: python setup.py build_ext --pg-config /path/to/pg_config build ... or with … -
Python class variable is None despite being set
I'm struggling with thread communication in Python. I'm clearly missing something, but I'm new to Python so I don't know very well what I'm doing. When the server gets a GET request, I want it to get two numbers (x and y coords) from a separate thread, which constantly updates those values and to return those numbers as a response. I have a simple Django project with the following structure: it is very basic, made according to tutorial. When the server starts, I start a thread that looks launches my coordinate generator in a separate thread: class GpsMockCoordsServiceConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'gps_mock_coords_service' def ready(self): if os.environ.get('RUN_MAIN', None) != 'true': _thread.start_new_thread(CoordsTracker.launch_recognition, ()) CoordsTracker class looks like so: coords = None class CoordsTracker: #coords = None #tried placin it here, but same effect - it is None when retreived from views.py logger = logging.getLogger("CoordsTrackerLogger") @staticmethod def draw_contours(mask, frame, color): ...... for stuff in stuffs: ...... CoordsTracker.set_coords((x, y)) ...... @staticmethod def launch_recognition(): ........ while True: ........ CoordsTracker.draw_contours(....) ........ @staticmethod def set_coords(new_coords): global coords CoordsTracker.logger.debug("setting coords " + str(new_coords)) coords = new_coords # here coords var is OK @staticmethod def get_coords(): CoordsTracker.logger.debug(coords) # Here it is OK if I call this method … -
In Django, what is the better way to pass arguments to a create view?
I need help with two questions. Number one: I have Orders model and generic create view for it and OrderDetails model with create view. After order is created the get_absolute_url method in Orders model redirects to a page with OrderDetails creation form. I want this OrderDetails create view to get arguments from order we just created such as order.pk, now I have to fill this field manually. So, is get_absolute_url method is what I need, or should I override dispatch method in my view, but may be I need to work on get_success_url method? Number two: when I go to Order creation page, how to automatically fill Employee field? E.g. I'm logged in system as Bob Smith and when I create new order I don't want to set myself there manually, I want system do it for me. Here's models: class OrderDetails(models.Model): order = models.OneToOneField('Orders', models.DO_NOTHING, primary_key=True) product = models.ForeignKey('products.Products', models.DO_NOTHING) unit_price = models.FloatField() quantity = models.SmallIntegerField() discount = models.FloatField() class Meta: managed = False db_table = 'order_details' unique_together = (('order', 'product'),) class Orders(models.Model): customer = models.ForeignKey('contractors.Customers', models.DO_NOTHING, blank=True, null=True) employee = models.ForeignKey('employees.Employees', models.DO_NOTHING, blank=True, null=True) order_date = models.DateField(blank=True, null=True) required_date = models.DateField(blank=True, null=True) shipped_date = models.DateField(blank=True, null=True) ship_via = … -
How To set edit / delete permissions for the creator only django
How To Give User Permission To Delete Or Edit It's Post @login_required(login_url="login") def editsell(request , pk): context= {} user = request.user if not user.is_authenticated: return redirect('login') sell_listing = get_object_or_404(listingsell , id=pk) if request.POST: form = UpdateSellForm(request.POST or None , request.FILES or None , instance = sell_listing) if form.is_valid(): obj = form.save(commit = False) editsell.user == user obj.save() context['success_message'] = "Updated" sell_listing = obj form = UpdateSellForm( initial = { "title" : sell_listing.title, "subtitle" : sell_listing.subtitle, "description" : sell_listing.description, "image" : sell_listing.image, "image2" : sell_listing.image2, "image3" : sell_listing.image3, "image" : sell_listing.image, "number_phone" : sell_listing.number_phone, "ville" : sell_listing.ville, } ) context['form'] = form return render(request , 'Swapdz/add_listing.html' , context) -
AttributeError: module 'speedtest' has no attribute 'Speedtest' test_get_server is not defined
!am trying to get the download and upload speed in python by using the "speedtest" module, but it gives me that error when I use the module: AttributeError: module 'speedtest' has no attribute 'Speedtest'. and I was only declaring the variable, that is my code : import speedtest test = speedtest.Speedtest() -
if field.many_to_many and field.remote_field.through._meta.auto_created: AttributeError: 'str' object has no attribute '_meta'
A source Django 3 by examples Chapter 14 When I try to run python manage.py migrate --settings=educa.settings.pro Another files are copies and pastes from the book The result is File "C:\Python\educa\manage.py", line 22, in <module> main() File "C:\Python\educa\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\migrate.py", line 244, in handle post_migrate_state = executor.migrate( File "C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\executor.py", line 227, in apply_migration state = migration.apply(state, schema_editor) File "C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\migration.py", line 126, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\operations\fields.py", line 104, in database_forwards schema_editor.add_field( File "C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\base\schema.py", line 487, in add_field if field.many_to_many and field.remote_field.through._meta.auto_created: AttributeError: 'str' object has no attribute '_meta' Migration file: from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('account', '0005_contant'), ] operations = [ migrations.CreateModel( name='Contact', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=True, verbose_name='ID')), ('user_from', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='rel_from_set', to=settings.AUTH_USER_MODEL)), … -
Is there any way to get the exact datatype of fields of csv file reading using pandas? [duplicate]
i have used dtypes of pandas to get the datatype of csv file, ``` with codecs.open(new_file_path_is, encoding="utf8") as csvfile: df = pd.read_csv(csvfile,nrows=100) print(df.dtypes) ``` Here the string fields are considered as object also the date field, I have appended field name and its datatype to a dictionary and the result is: {'First Name': 'object', 'Last Name': 'object', 'Date': 'object', 'Id': 'int64'} is there any method to get the exact datatype of fields?why its taken as object? -
How to get "HTTP_CF_IPCOUNTRY" with django python
I'm unable to get HTTP_CF_IPCOUNTRY from http meta data. I want to get country code. def register(request): country_code = request.META.get('HTTP_CF_IPCOUNTRY', 'N/A').strip() print("THIs is ",country_code) this prints --> N/A -
Django Please help me place a checkbox and a mail box with a send button on the html page
One of functionality in my training project: subscribe to the news by check-box and e-mail. Send newsletter daily. The user can unsubscribe from the mailing list in his profile by unchecking the checkbox. It so happened that first I set up a daily newsletter for users who have booleanfield = true. For it I marked the checkboxes in the admin panel. It works. Now it is necessary to add the checkbox and the mail field to the news page. I'm stuck on the simplest. Tired and confused. Please help me place a checkbox and a mail box with a send button on the news page models.py class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) hr = models.BooleanField(default=False) subscribed_for_mailings = models.BooleanField(default=False) subscription_email = models.EmailField(default="") def __str__(self): return str(self.user) Forms.py class MailingForm(forms.ModelForm): class Meta: model = models.Profile fields = ('subscription_email', 'subscribed_for_mailings', ) widgets = { 'subscription_email': forms.EmailInput(attrs={"placeholder": "Your Email..."}), 'subscribed_for_mailings': forms.CheckboxInput, } views.py def all_news(request): today = date.today() today_news = models.TopNews.objects.filter(created__gte=today) return render(request, "news.html", {'today_news': today_news}) def mailing_news(request): if request.method == 'POST': mailing_form = forms.MailingForm(request.POST) if mailing_form.is_valid(): mailing_form.save() return HttpResponse('You will receive news by mail') else: mailing_form = forms.MailingForm() return render(request, "news.html", {'mailing_form': mailing_form}) urls.py ... path('news/', views.all_news, name='all_news'), ... news.html {% extends 'base.html' … -
Exe creation using pyinstaller for django rest app
I am trying to create an exe file using Pyinstaller for Django project having only REST api framework used. I am running manage.py runserver command by creating another file run.py and executing that file. run.py content: import os if name == 'main': os.system("python manage.py runserver 0.0.0.0:5000") I am trying to create exe file by giving command pyinstaller --onefile -w run.py manage.py (Giving two files by keeping in mind that it should analyze both the files but execute run.exe, I may be wrongly doing it) It is creating a run.exe file which is not giving any error or output. I tried --noreload option but still no error and no output at console while exe execution. I am running exe file as: run.exe --noreload (not giving runserver as it is already mentioned in run.py file) Could someone please help on how to create exe file in such scenario and as I am mentioning runserver inside another function? -
Django forms.PasswordInput() updated my application main password
On my Django app, I have a custom field rendered with the forms.PasswordInput() widget. This works as expected from a visual perspective. However, Chrome detects this as a password and then updates this field with the master password that a user might have set on his account on the app. Is there a way to get a forms.PasswordInput() field without Chrome messing passwords fields in it? -
How to put template into iframe?
The very similiar problem as mine I found here: Set URL to load iframe in a Django template but it doesn't help. Having a route in my urls.py written as (...) path('rejestracja/', views.rejestracja, name = 'rejestracja'),(...) where the view is to render page named rejestracja.html, I have to put the content of it into iframe. And I do it assigning src = "{% url 'rejestracja' %}". Unfortunatelly the iframe is showing me an error: "Page localhost is blocked" "Server localhost denied connection." ERR_BLOCKED_BY_RESPONSE The strange thing is, source of iframe shows me content of rejestracja.html. It means, I think, my code is ok, but somewhere I have any restrictions. But I have no idea which, how and where... Could someone tell me what is wrong, or at least, where to look for solution? -
Django creates a migration that seems already reflected in original postgresql schema
I've modified the foreign key calendar as nullable in my Django model CalendarAssign. \ # ---------------------------------------------------------------------------- # class Calendars(models.Model): id = models.CharField(primary_key=True, max_length=100) cms_id = models.CharField(max_length=100) default_program = models.ForeignKey(ControlPrograms, models.CASCADE, blank=True, null=True) timestamp = models.DateTimeField(auto_now_add=True) class Meta: managed = True db_table = 'calendars' # ---------------------------------------------------------------------------- # class CalendarAssign(models.Model): device_mac = models.ForeignKey(Device, models.CASCADE) calendar = models.ForeignKey(Calendars, models.CASCADE, null=True) timestamp = models.DateTimeField(auto_now_add=True) class Meta: managed = True db_table = 'calendar_assign' When applying the migration generated by Django it gives me an error. operations = [ migrations.AlterField( model_name='calendarassign', name='calendar', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='smartbridge.Calendars'), ) Generated sql code uses unsupported feature 'WITH ORDINALITY'. It's because Django doesn't support the Postrges version we are using. WITH ORDINALITY appears in psql 9.4 but we use version 9.1. Both Postgres and Django cannot be upgraded right now. So I need to write the migration manually (without 'WITH ORDINALITY' feature). migrations.RunSQL("DO $$DECLARE r record;\ BEGIN\ FOR r IN SELECT table_name,constraint_name \ FROM information_schema.constraint_table_usage \ WHERE table_name IN ('calendars') AND constraint_name like '%calendar_assign_calendar_id%'\ LOOP\ EXECUTE 'ALTER TABLE calendar_assign DROP CONSTRAINT '|| quote_ident(r.constraint_name) || ';';\ END LOOP;\ ALTER TABLE calendar_assign ALTER COLUMN calendar_id DROP NOT NULL; \ ALTER TABLE calendar_assign \ ADD CONSTRAINT calendar_assign_calendar_id_fk_calendars_id FOREIGN KEY (calendar_id) REFERENCES calendars(id);\ END$$;") Migration … -
Making any changes to inline css of the HTML file inside DJANGO project is not woking
I have to make changes in my code that if approverFlag is "Approved" then display the record as green and if the approverFlag is "Not Approved" then display the record as red. Folllowing are the changes I have made in my HTML file:- {% if awp.approveFlag == "Approved" %} <td style = "color:green;" id=displayrecord >{{ awp.approveFlag }} </td> {% elif awp.approveFlag == "Not Approved"%} <td style = "color:red;" id=displayrecord >{{ awp.approveFlag}} </td> {% endif %} But it is not working. I have also tried writing class here as follows:- <td class = "approved" id=displayrecord >{{ awp.approveFlag }} </td> And then making changes in tag of the HTML file:- <style> .approved{ color:red; } </style> But nothing is working. Can anyone suggest any solution to make it work? -
Invalid block tag on line 7: 'endif', expected 'empty' or 'endfor'. Did you forget to register or load this tag?
I am beginner in html-templates and Django. author_list.html {% extends "base_generic.html" %} {% block content %} <h1>All authors</h1> <ul> {% for author in author_list %} <li><a href="">{{ author.last_name }}:</a> {% for book in author.book_set.all %} {{ book.title }} {% if not forloop.last %}, {% endif %}{% endfor %}</li> {% endfor %} </ul> {% endblock %} Error: Invalid block tag on line 7: 'endif', expected 'empty' or 'endfor'. Did you forget to register or load this tag? I have the block of code. It works without block if, but doesn't work with the conditional. How to fix it. Help! I should paste "," after each name of book. -
Can I change the django rate limiter timeout?
I'm building an API in Python and Django and have encountered the rate limits set by django. Now, I've adjusted the rate limits for users and anons accordingly but I was wondering if there was a way to change or reduce the time in the following error response. { "detail": "Request was throttled. Expected available in 7735 seconds." } Specifically I would like to reduce the 7735 seconds. Also, if I'm not mistaken, the timer counts down from 86400 seconds i.e. 1 day ? -
Better way of hiding entries not created by current user in Django?
Im pretty new to Django, and right now I have created a site that lets users register/login, make entries that are associated to that user via a "user" field in the entries database. Iv'e managed to get all the functionality of hiding other users entries by adding get_queryset() methods that only return the current users entries. But I feel like this is a bad way of doing this. I feel like im reusing a lot of code and that there could be backdoors to display other users entries. Is there a way to completely disable other users entries from the current user, not just not display it? views.py class EntryListView(LockedView, ListView): model = Entry def get_queryset(self): return super().get_queryset().filter(user=self.request.user).order_by("-date_created") class EntryDetailView(LockedView, DetailView): model = Entry def get_queryset(self): return super().get_queryset().filter(user=self.request.user) class EntryCreateView(LockedView, SuccessMessageMixin, CreateView): model = Entry fields = ["title", "content"] success_url = reverse_lazy("entry-list") success_message = "Your new entry was created!" def form_valid(self, form): user = self.request.user form.instance.user = user return super(EntryCreateView, self).form_valid(form) def get_queryset(self): return super().get_queryset().filter(user=self.request.user) class EntryUpdateView(LockedView, SuccessMessageMixin, UpdateView): model = Entry fields = ["title", "content"] success_message = "Your entry was updated!" def get_success_url(self): return reverse_lazy( "entry-detail", kwargs={"pk": self.object.pk} ) def get_queryset(self): return super().get_queryset().filter(user=self.request.user) -
Use of queryset inside Primarykeyfield of ModelSerializer in Django Rest
I am making a simple create api for a model which has almost all fields as foriegn key to other models. I am writing create logic inside the serializer. It is working fine. However if I define all the fields as pkrelated field in serializer, it asks for queryset attribute. Why it is asking that. And if I put queryset and import all the objects(queryset= Example.objects.all()) wouldnt it make the code and api slow since it is importing all the objects from Example model. Also, what its use to be honest? My model: class Example(TimeStampAbstractModel): abc = models.ForeignKey(User,.... xyz_info = models.ForeignKey(XYZ,... mnp = models.ForeignKey(MNP,...... status = models.CharField(....blank=True) My serializer: class AttendanceSerializer(serializers.ModelSerializer): xyz_info = serializers.PrimaryKeyRelatedField(required=True, queryset=XYZ.objects.all()) mnp= serializers.PrimaryKeyRelatedField(required=True, queryset=MNP.objects.all()) #mnp = serializers.IntegerField(required=True) status = serializers.CharField(required=True) class Meta: model = Attendance fields = ['xyz_info','mnp','status'] def create(self, validated_data): ............. In above serializer class, if I hadnt defined all those fileds in the serializer, it works fine. But if I define them as pkfield as above ( I am passing only ids in the body from frontend), it asks for queryset. Why it is asking queryset and what its use there? Also can I defined them as integarfield? When to define as pkfield and … -
How to mix multiple querysets into one and re order them by time created?
I am learning Django and still a beginner. For practising, i am trying to make a demo social media website. In my project, users can create groups, then they can post and comment there. In the home page, i am trying to add a section like 'recent activities' where a user can see recent activities in that website like "John created a group 'Javascript', Tim posted a comment in 'Python', Sarah posted in 'CSS'" Now i have made some queries like: groups = Group.objects.all().order_by('-created')[0:5] posts = Post.objects.all().order_by('-created')[0:5] comments = Comment.objects.all().order_by('-created')[0:5] I want to mix them all in a single queryset. Then order them all by the time they were created. I know it's a silly question and i have been stuck here since morning. Can you help me and show me the process please? -
How to hoste multiple Django websites on single sever using NGINX and uWSGI
i have a linux server running under Ubuntu server 20.04 LTS, i'm using NGINX as a web server and uWSGI as an application server, i have a Django website is already installed and running perfectly, and the exact way i did that is by following the instructions from this video https://www.youtube.com/watch?v=ZpR1W-NWnp4&t=2s, but the thing is that i have several websites that needs to be installed, so i tried to redo all of it for a second website on the same server, but that did not work at all. My question is: once i install a Django project exactly the way shown in the video using Nginx and uWSGI, how to install another Django project in a practical manner, in other words how to install multiple Django projects using Nginx and uWSGI. -
How to create database connection using REST API in Django?
Currently, I'm trying to make a Database Connection with Django REST API. The goal: To create an API for DB connection with any databases by inputting the properties (e.g., host, dbname, username, password, etc). I already tried using GET method to connect and retrieve the output. However, all the DB properties are written in the script. This is my result using GET: Now, I want to modify it into POST method to connect and retrieve the output. (It seems that user gives the input). My expected result is: The problem is: I don't know how to modify it into POST method (request JSON) and retrieve the desired output (response JSON) as I mentioned in the above picture. The MyApp\src\DBConn.py file: import psycopg2 class DbConnection: def __init__(self, host, port, dbname, user, password): self.host = host self.port = port self.dbname = dbname self.user = user self.password = password def create_conn(self): # connection string conn = 'host = {host} port = {port} dbname = {dbname} user = {user} password = {password}'.format( host = self.host, port = self.port, dbname = self.dbname, user = self.user, password = self.password ) # establish the connection self.db = psycopg2.connect(conn) self.cursor = self.db.cursor() def check_conn(self): sql = "SELECT VERSION()" … -
Why is the server not working when using django_prometheus?
There is a django application. It is necessary to collect metrics. I'm using django_prometheus. I added the django_prometheus app to my project. INSTALLED_APPS = [ ... 'django_prometheus', ... ] MIDDLEWARE = [ 'django_prometheus.middleware.PrometheusBeforeMiddleware', ... 'django_prometheus.middleware.PrometheusAfterMiddleware', ] I don't want to add the URL "/ metrics". I need to start the server on a separate port using prometheus_client.start_http_server. I added this code to wsgi.py: from django.conf import settings from django_prometheus.exports import SetupPrometheusEndpointOnPort SetupPrometheusEndpointOnPort(9090) This starts the server and it works. But the correct metrics are not displayed. If you add the url "/metrics": urlpatterns += [ path('', include('django_prometheus.urls')), ] Then localhost:8000/metrics will display the correct metrics. What could be the problem? P.S.: I started the server via start_http_server in parallel with the FastAPI application and everything worked correctly. -
how to get param in permission.py django
I want to work with 'start' param in permissions.py How I can take it ? My model class Quiz(models.Model) : title = models.CharField(max_length=50) start = models.DateTimeField(default="2021-10-10") end = models.DateTimeField(default="2021-10-11") description = models.CharField(max_length=250) permissions.py from rest_framework import permissions class IsTimeNotDefined(permissions.BasePermission) : def has_permission(self, request, view): if request.method in permissions.SAFE_METHODS: return False return False