Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How i can replicate my Postgres database in CPanel
PLZ HEPL ME. I have problem -I can not find the answer to how I can do so that I could upload my real database in Postgress to the hosting and make it so that when you change data or add data in the database on the hosting it all automatically done in my database on the local machine (ie comp'yutera). I use CPanel to load my project on Django where my local Postgres database is connected. I need that somebody can me explain it, because in Internet i coudn't find ,y problem and AI too can't hepl me(((( -
pytest-django doesn't work in Github Actions
I have Django project that uses pytest and pytest-django. I have some tests, when I run them in docker-compose using docker exec -it <container name> pytest they are passing successfully. But when Github Actions run pytest command it gives me an error: ============================= test session starts ============================== platform linux -- Python 3.11.3, pytest-7.4.2, pluggy-1.3.0 django: settings: ***.settings (from env) rootdir: /home/runner/work/Meduzzen-backend-intership/Meduzzen-backend-intership/*** plugins: django-4.5.2 collected 3 items apps/api/tests/test_user_model.py EEE [100%] ==================================== ERRORS ==================================== ___________________ ERROR at setup of test_create_user_fail ____________________ request = <SubRequest '_django_db_marker' for <Function test_create_user_fail>> @pytest.fixture(autouse=True) def _django_db_marker(request) -> None: """Implement the django_db marker, internal to pytest-django.""" marker = request.node.get_closest_marker("django_db") if marker: > request.getfixturevalue("_django_db_helper") /opt/hostedtoolcache/Python/3.11.3/x64/lib/python3.11/site-packages/pytest_django/plugin.py:465: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /opt/hostedtoolcache/Python/3.11.3/x64/lib/python3.11/site-packages/pytest_django/fixtures.py:122: in django_db_setup db_cfg = setup_databases( /opt/hostedtoolcache/Python/3.11.3/x64/lib/python3.11/site-packages/django/test/utils.py:187: in setup_databases test_databases, mirrored_aliases = get_unique_databases_and_mirrors(aliases) /opt/hostedtoolcache/Python/3.11.3/x64/lib/python3.11/site-packages/django/test/utils.py:334: in get_unique_databases_and_mirrors default_sig = connections[DEFAULT_DB_ALIAS].creation.test_db_signature() /opt/hostedtoolcache/Python/3.11.3/x64/lib/python3.11/site-packages/django/db/backends/base/creation.py:371: in test_db_signature self._get_test_db_name(), _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ … -
Get raw SQL query for further execution in database client
How am I able to retrieve the produced plain SQL statement from a Django ORM query which I can use in another database client program? For example, having a ModelA.objects.filter(name='abc') queryset. I imagine setting a breakpoint somewhere in the Django/3rd-party-apps code to get a plain Select * from TabelModelA where name='abc'; statement which I can directly copy/paste into DBeaver or something else and execute without the need for further processing into the needed SQL dialect. We use Server SQL and the django-mssql package. I know the django.db.connection.queries thing and its resulting SQL/params strings, but that's not what I mean. Is there something else? Or is it doable in pyodbc? Or is there another technique? -
How can I make Django library code visible to VS2022 at develop- and run-time?
Following a Microsoft tutorial for Django, using VS2022, but I have hit what seems to be a simple scope / visibility problem. Intellisense shows references to some Django imports as "unresolvable by source". The specific error (sample): Import "django.urls" could not be resolved from source I think it indicates that the Django module is not visible to VS, and that is supported by the fact that the app does actually run OK. So I think that I have not successfully specified to VS which env it should use during development. A post from a few years ago suggests that development-time and run-time are using different Python environments, but I have followed the instructions to make sure that the (virtual) env ("env" below) is specified for the project. The project file includes this: <ItemGroup> <Interpreter Include="env"> <Id>env</Id> <Version>3.7</Version> <Description>env (Python 3.7 (64-bit))</Description> <InterpreterPath>Scripts\python.exe</InterpreterPath> <WindowsInterpreterPath>Scripts\pythonw.exe</WindowsInterpreterPath> <PathEnvironmentVariable>PYTHONPATH</PathEnvironmentVariable> <Architecture>X64</Architecture> </Interpreter> </ItemGroup> Any suggestions welcome. -
How to implement a maintenance mode for a backend on Django, Docker and AWS ECS?
I have a backend for an e-commerce app, built on Django, and hosted on AWS ECS (more precisely with Fargate). Django is in a container, and this container works with another based on Nginx. ECS is used to host several tasks of this group of containers. Theses tasks can be removed / replaced / duplicated depending on the load to the app. The aim is to respond with a 503 status codes when maintenance mode is activated. I already have a maintenance mode, based on a custom Django middleware. I use an environment variable to check if the site is in maintenance. class MaintenanceMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): try: maintenance = int(os.environ['MAINTENANCE']) except Exception: maintenance = 0 if maintenance: return HttpResponse(status=503) return self.get_response(request) Very simple and efficient. But to enable maintenance mode, I have to update my task definition in ECS in order to change the environment variable ; and then, redeploy the service. In this way, every running ECS task is replaced with a new task, which contains the new value of the environment variable. It's not something very easy to do. And in my point of view, a task definition must not be … -
Python django-oauth-toolkit client_credentials allows anything to go through and doesn't add user to the token
I'm using django-oauth-toolkit and I can't figure out why when I use client_credentials, I can literally insert any username/password combo and they always return a token even if the username/password combo is nowhere in the database. This is my postman request body: On the admin portal, I don't even see the user selected under "user": How do I only allow valid username/password combos to return an access token and how do I attach a user to an access token? -
Can we send form data picked up by Javascript from a html doc to Django views.py file ? If so what are the methods?
I need to pickup the data entered in a form in a HTML document using javascript and perform some operations on it and then send it to Django in the back-end to store the data in the Database. What are the ways/methods by which I can do the above scenario? I heard that we can use an Ajax call to do the described problem, but is there any other easy/secure method to do it? -
Connect my Flutter Mobile App to backend from my laptop with same internet connections
ClientException with SocketException:connection failed(OS Error: Permissio Denied,errno = 13),address = 192.168.43.155, port = 8000, uri=http://192.168.43.155:8000/api/login/ im facing this when i tried to run flutter app from mobile and connect to backend from my laptop what im going to do? -
Django AssertionError GraphQL
I have an error on my GraphQL instance, I load the /graphql endpoint and it pops up with the below error. AssertionError: You need to pass a valid Django Model in AuthorType.Meta, received "None". My schema for each is as follows: class UserType(DjangoObjectType): class Meta: model = get_user_model() class AuthorType(DjangoObjectType): class Meta: models = models.Profile class PostType(DjangoObjectType): class Meta: model = models.Post class TagType(DjangoObjectType): class Meta: model = models.Tag I also have a Query within that schema: class Query(graphene.ObjectType): all_posts = graphene.List(PostType) author_by_username = graphene.Field(AuthorType, username=graphene.String()) post_by_slug = graphene.Field(PostType, slug=graphene.String()) posts_by_author = graphene.List(PostType, username=graphene.String()) posts_bt_tag = graphene.List(PostType, tag=graphene.String()) def resolve_all_posts(root, info): return ( models.Post.objects.prefetch_related("tags").select_related("author").all() ) def resolve_author_by_username(root, info, username): return models.Profile.objects.select_related("user").get( user__username=username ) def resolve_post_by_slug(root, info, slug): return ( models.Post.objects.prefetch_related("tags") .select_related("author") .get(slug=slug) ) def resolve_posts_by_author(root, info, username): return ( models.Post.objects.prefetch_related("tags") .select_related("author") .filter(author__user__username=username) ) def resolve_posts_bt_tag(root, info, tag): return ( models.Post.objects.prefetch_related("tags") .select_related("author") .filter(tags__name__iexact=tag) ) Here is the model for the blog posts: class Profile(models.Model): user = models.OneToOneField( get_user_model(), on_delete=models.PROTECT, ) website = models.URLField(blank=True) bio = models.CharField(max_length=240, blank=True) def __str__(self) -> str: return self.user.get_username() class Tag(models.Model): name = models.CharField(max_length=50, unique=True) def __str__(self): return self.name class Post(models.Model): class Meta: ordering = ["-publish_date"] title = models.CharField(max_length=255, unique=True) subtitle = models.CharField(max_length=255, blank=True) slug = models.SlugField(max_length=255, … -
Django export PDF directly from view
I'm wondering if it's somehow possible to process the PDF export directly in the main view, and have it triggered by a button click in the template. The reasoning is that in the main view (dispatcher_single) I have 300 lines of code of data manipulation (including charts) that I would like to export to PDF and would like to avoid having to copy/paste all this code from main view to the PDF export view. Main view with a bunch of calculations: views.py def dispatcher_single(request, pk): dispatcher = Dispatcher.objects.select_related("company", "location").get(id=pk) # data manipulation here (about 300 lines of code) context = { 'dispatcher': dispatcher 'bunch_of_other_data': data } return render(request, 'dispatchers/dispatcher-single.html', context) Another view for exporting to PDF: views.py from renderers import render_to_pdf def dispatcher_statement_form(request, pk): dispatcher = Dispatcher.objects.get(id=pk) context = { 'dispatcher': dispatcher, } response = renderers.render_to_pdf("pdf/statement_form.html", context) if response.status_code == 404: raise Http404("Statement form not found.") filename = "Statement_form.pdf" content = f"inline; filename={filename}" download = request.GET.get("download") if download: content = f"attachment; filename={filename}" response["Content-Disposition"] = content return response And the render function: renderers.py def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result) if pdf.err: return HttpResponse("Invalid PDF", status_code=400, content_type='text/plain') return HttpResponse(result.getvalue(), content_type='application/pdf') -
Why divs slide to the next row when setting margin, Bootstrap, Django
{% for plant in plants %} {% if forloop.counter0|divisibleby:3 %} <div class="row row-cols-3"> {% endif %} {% include 'included/_plant_cell.html' %} {% if forloop.counter|divisibleby:3 %} </div> {% endif %} {% endfor %} _plant_cell.html: <div class="plant-cell card col-md-4 m-1"> <div class="card-body"> <div class="card-text"> {{ plant.name }} </div> </div> </div> the following code results in rows that contain only two cards, and the third slides down to the next row (when margin m-1 is removed, then ok), so the general view is repeatedly row with two cards, row with one card. Expected to see rows with three cards in each. -
After submitting, data not visible on admin page
When I'm trying to submit my form, server gives me a successful GET and POST request, but when I come to the admin page it doesn't show me data from the Form. The problem is that I want to see submitted data on the admin page. I registered Model in admin.py, but still didn't help from django.contrib import admin from .models import Reservation # Register your models here. admin.site.register(Reservation) Here is my models.py from django.db import models # Create your models here. class Reservation(models.Model): name = models.CharField(max_length=100) phone_number = models.IntegerField() email = models.EmailField() reservation_date = models.DateField() reservation_slot = models.SmallIntegerField(default=10) def __str__(self): return self.email reservation.html where I trying to submit form {% extends 'base.html' %} {% load static %} {% block base%} <section> <article> <h1>Make a reservation</h1> <!--Begin row--> <div class="row"> <!--Begin col--> <div class="column"> {% csrf_token %} <form method="POST" id="form"> <!-- {% csrf_token %} --> <p> <label for="first_name">Name:</label> <input type="text" placeholder="Your Name" maxlength="200" required="" id="first_name"> </p> <p> <!-- Step 9: Part one --> <label for="reservation_date">Reservation date:</label> <input type="date" placeholder="Your reservation" maxlength="200" required="" id="reservation_date"> </p> <p> <label for="reservation_slot">Reservation time:</label> <select id="reservation_slot"> <option value="0" disabled>Select time</option> </select> </p> <button type="button" id="button">Reserve</button> </form> </div> <!--End col--> <!--Begin col--> <div class="column"> <h2>Bookings For <span … -
Poetry and Vercel issue
I have found out about Poetry recently, and I am amazed by how well it works compare to the regular pip and whatnot. But I am facing issues with when I try to host my Django app on Vercel. Since Vercel have no functionality of poetry I cannot host my django over there. I have tried chatgpt and the solution is to modify the vercel.json file which I did. { "build": { "env": { "POETRY_VERSION": "1.1.4" } }, "builds": [ { "src": "test/wsgi.py", "use": "@vercel/python", "config": { "maxLambdaSize": "15mb", "runtime": "python3.9" } } ], "routes": [ { "src": "/(.*)", "dest": "test/wsgi.py" } ] } but then I got these errors. [ERROR] Runtime.ImportModuleError: Unable to import module 'vc__handler__python': No module named 'django' then I tried this solution text but when I followed this solution my app would not even deploy it would give error even the building part Error: Command failed: python3.9 -m poetry export --without-hashes -f requirements.txt --output requirements.txt and ImportError: urllib3 v2.0 only supports OpenSSL 1.1.1+, currently the 'ssl' module is compiled with 'OpenSSL 1.0.2k-fips 26 Jan 2017'. See: https://github.com/urllib3/urllib3/issues/2168 so after exhausting everything that I could am here for help. -
multiple try/except , n etx one catch exception after first one handle it
I have 2 try except block, the second one trigger the first one exception i'm expecting that the first one handle the first exception and that the second one not trigger that exception the second try/catch block catch the exception generated in the first one unless i handle it, why ? can someone help me solve this issue ? try: if isinstance(request.data['name'],str): progetto.name = request.data['name'] progetto.save() else: raise TypeError('Validation error') except TypeError as te: print('type error catched error: ',te) errori.append({'name': str(te)}) except Exception as e: print('name catched error: ',e) errori.append({'name': str(e)}) try: progetto.expiration = request.data['expiration'] progetto.save() except Exception as ex: print('exp block catched error: ',ex) errori.append({'expiration': str(ex)}) -
Can't fill my custom user model in django with automatic script
Made a new custom django user model class UserProfile(User): phone_number = models.CharField(max_length=20, verbose_name='Номер телефона', unique=True) Trying to Automatize filling it wit information from API with this script: import requests import json from django.contrib.auth.models import User from tarifs.models import Software_Products, UserProfile url = "My API" headers = { "Content-Type": "application/json", "Authorization": "Basic ..." } subscribers = {} page = 0 size = 300 while True: data = {"page": page, "size": size} response = requests.post(url, data=json.dumps(data), headers=headers) data = json.loads(response.content) if not data.get('subscribers'): break for subscriber in data['subscribers']: code = subscriber['code'] name = subscriber['name'] subjects = subscriber.get('subjects', []) reg_numbers = subscriber.get('regNumbers', []) if reg_numbers: subscribers[name] = { 'code': code, 'name': name, 'subjects': subjects, 'reg_numbers': reg_numbers } page += 1 for name, reg_numbers_data in subscribers.items(): user_profile, created = UserProfile.objects.get_or_create(name=name) for reg_number in reg_numbers_data['reg_numbers']: software_product, created = Software_Products.objects.get_or_create( user_id=user_profile, reg_number=reg_number, defaults={'name': reg_numbers_data['name']} ) if not created: software_product.name = reg_numbers_data['name'] software_product.save() Running this script ends with this error: Traceback (most recent call last): File "c:\work\Bizstart\bizstart_django\bizstartprj\parse2.py", line 3, in from django.contrib.auth.models import User # Перенесите этот импорт в начало ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\work\bizstart\bizstart_django\bizstartenv\Lib\site-packages\django\contrib\auth\models.py", line 3, in from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "C:\work\bizstart\bizstart_django\bizstartenv\Lib\site-packages\django\contrib\auth\base_user.py", line 49, in class AbstractBaseUser(models.Model): File "C:\work\bizstart\bizstart_django\bizstartenv\Lib\site-packages\django\db\models\base.py", line 127, in new app_config = apps.get_containing_app_config(module) … -
is there any solution to show data on django website
project in python and java language django website is used data store in database but not show on website and the software used is pycharm I just want to know the solution to show data on website which is store on database I tried alot of query -
Django MigrationAutodetector not detecting changes properly
I'm developing an app that must handle dynamic models creation using Django v. 4.2.6. I was inspired by the great work of Will Hardy looking at his repo dynamic-models, but unfortunately it uses APIs that are no longer valid, as django changed a lot since v.1.2. I was thinking the project in this way: The user creates a Model instance (and as many Field instances as its model needs - each Field has a foreign key to Model). When a Model or a Field instance are saved/deleted the migrations are made and then applied using signals, so the database contains the schemas and the columns needed to store data. I created a dummy app (dynamic_models) and a real app (api_v1) that handle the storage of the data structure. The api_v1.models contains a Field and a Model models. Currently I was exploring the idea of using a customized flow of the makemigrations command and then a customized flow of the migrate command, called by a function called by a post_save signal sent by Model. Here some code I already wrote: api_v1.models.py from dynamic_models.dynamic_models import DynamicModel, makemigrations class FieldType(models.IntegerChoices): CharField = 1 # Requeires max_length TextField = 2 IntegerField = 3 DecimalField … -
How to display actual field with dropdowns instead of showing id?
I have two models and two serializers models: class P4R(models.Model): p4r_id = models.AutoField(primary_key=True) psc_id = models.ForeignKey(BePsc, on_delete=models.CASCADE, verbose_name='PSC Name') vbb_identifier = models.CharField(max_length=100, verbose_name='VBB Identifier') maturity = models.CharField(max_length=100) capex_opex = models.CharField(max_length=100, verbose_name='CAPEX/OPEX') budget_item = models.ForeignKey(BudgetItem, on_delete=models.CASCADE) paying_interest = models.DecimalField(max_digits=10, decimal_places=2) created_by = models.CharField(max_length=100, default='Admin', null=True) created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True) def __str__(self): return str(self.vbb_identifier) class P4RChangingFields(models.Model): p4r_variations_id = models.AutoField(primary_key=True) vbb_identifier = models.ForeignKey(P4R, on_delete=models.CASCADE, verbose_name='VBB Identifier') year_now = models.IntegerField(default=2023, verbose_name=f'Year {current_year}') year_1 = models.DecimalField(max_digits=35, decimal_places=25, verbose_name=f'Year {year_1_name}') year_2 = models.DecimalField(max_digits=35, decimal_places=25, verbose_name=f'Year {year_2_name}') year_3 = models.DecimalField(max_digits=35, decimal_places=25, verbose_name=f'Year {year_3_name}') year_4 = models.DecimalField(max_digits=35, decimal_places=25, verbose_name=f'Year {year_4_name}') year_5 = models.DecimalField(max_digits=35, decimal_places=25, verbose_name=f'Year {year_5_name}') created_by = models.CharField(max_length=100, default='Admin', null=True) created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True) class Meta: db_table = 'P4R_VARIATIONS' serializers: class P4RSerializer(serializers.ModelSerializer): class Meta: model = P4R fields = '__all__' class P4RChangingFieldsSerializer(serializers.ModelSerializer): vbb_identifier = serializers.CharField(source='vbb_identifier.vbb_identifier') # vbb_identifier = serializers.SlugRelatedField(slug_field='vbb_identifier', read_only=True) class Meta: model = P4RChangingFields fields = '__all__' As you can see, vbb_identifier is the field that connects between the two table. when user create new row using P4R model, they will need to enter vbb_identifier in the form of strings ("ABC123"). the only relationship both table has is vbb_identifier and its one to many. one P4R object may have multiple P4RChangingFields object related to … -
How to log missing template variable, showing location and context in Django?
I am following this tutorial ("With a logging filter that raises exceptions") to catch all invalid variable names in Django templates. myproject/mysite/logging.py: import logging class MissingVariableError(Exception): """ A variable was missing from a template. Used as an alternative to django.template.base.VariableDoesNotExist, because that exception has some meaning within the template engine. """ class MissingVariableErrorFilter(logging.Filter): """ Take log messages from Django for missing template variables and turn them into exceptions. """ ignored_prefixes = ( "admin/", ) def filter(self, record): if record.msg.startswith("Exception while resolving variable "): variable_name, template_name = record.args if not template_name.startswith(self.ignored_prefixes): raise MissingVariableError( f"{variable_name!r} missing in {template_name!r}" ) from None return False myproject/settings.py: LOGGING = { "version": 1, "disable_existing_loggers": False, "filters": { "missing_variable_error": { "()": "www.logging.MissingVariableErrorFilter", }, }, "handlers": { "console": { "class": "logging.StreamHandler", }, }, "root": { "handlers": ["console"], "level": "WARNING", }, "loggers": { "django": { "handlers": ["console"], "level": 'INFO', "propagate": False, }, "django.template": { "level": "DEBUG", "filters": ["missing_variable_error"], }, }, } When I load the main page I get this in the log Traceback (most recent call last): ... File "/install_dir/site/myproject/mysite/logging.py", line 27, in filter raise MissingVariableError( www.logging.MissingVariableError: 'exception_notes' missing in 'unknown' Problem 1: exception_notes does not appear in my site (see note below) Problem 2: this stack trace … -
Superuser active is turned to False, how can I login to my django admin
Superuser active is turned to False, how can I login to my django admin. I mistakenly turned my active to False as a superuser, now I can't login to my django admin. How can I get back superuser as active? I have tried login but couldn't access admin -
Error reversing django migrations with sql_safe_update mode set in MariaDB
I am running into issues when I try to reverse migrate one of the migrations in Django due to sql_safe_update mode is set in MariaDB. The exact sql statement it runs for reverse is: ALTER TABLE `user` DROP COLUMN `pin_code`; And the error that I get from django is: MySQLdb.OperationalError: (1175, 'You are using safe update mode and you tried to update a table without a WHERE that uses a KEY column') Now my database is in inconsistent state because the column has been dropped and failed migration was not rolled back as MySQL DDL statements are not run in transaction. Now even with --fake it shows the same error. Is there a way to tell django to run migrations with sql_safe_update=0 only for duration of migrations? Note that I cannot turn off sql_safe_update globally as DB admins are adamant on not removing it globally. Also it is not entirely clear why DROP column requires a WHERE statement? -
Query sum with distant foreign key relations in Django
Let's say I have models like this: class Product(models.Model): ... class Item(models.Model): product = models.ForeignKey(Product, related_name="items") quantity = models.IntegerField() class Order(models.Model): item = models.ForeignKey(Item, related_name="orders") quantity = models.IntegerField() I now want to get a list of Product annotated with the field total_supply. "Total supply" is defined for each product as: (sum of all of a product's items' quantity) - (sum of quantity on all of the Order objects associated with one of the product's items.) Here is what I have tried: Product.objects.annotate(actual_supply=Sum("items__quantity") - Sum("items__orders__quantity")) I am getting unexpected results. How am I supposed to write such a query? Thank you -
How to define individual service name for each type of Opentelemetry auto instrumentation in a python application?
We are currently using Datadog for monitoring and observability in our application, and we have integrated OpenTelemetry for distributed tracing. We have encountered one main issue Span Separation: Currently, all the spans from our application are being exported to Datadog under a single service. However, we would like to separate them into different services based on the type of instrumentation used (e.g., Django, Elasticsearch, requests, etc.). Manage.py configure_opentelemetry() #Auto Instrumentation of Django, Psycopg2, Pymemcache, Elasticsearch, URLLib3, Requests DjangoInstrumentor().instrument(request_hook=fix_django_req) PymemcacheInstrumentor().instrument() RequestsInstrumentor().instrument() ElasticsearchInstrumentor().instrument() Psycopg2Instrumentor().instrument(enable_commenter=True, commenter_options={}) URLLib3Instrumentor().instrument() configure_opentelemetry method def configure_opentelemetry(): otlp_exporter = OTLPSpanExporter(endpoint=os.getenv("OTEL_COLLECTOR_URL"), insecure=True) # Set the global TracerProvider with the OTLP exporter trace.set_tracer_provider(TracerProvider(resource=Resource.create({SERVICE_NAME: os.getenv("OTEL_SERVICE_NAME"), "env": os.getenv('OTEL_ENV')}))) # Create a BatchSpanProcessor and add the exporter to it span_processor = BatchSpanProcessor(otlp_exporter) trace.get_tracer_provider().add_span_processor(span_processor) tracer = trace.get_tracer(__name__) Collector Config: receivers: otlp: protocols: grpc: http: processors: batch: # batch metrics before sending to reduce API usage send_batch_max_size: 100 send_batch_size: 10 timeout: 10s memory_limiter: # drop metrics if memory usage gets too high check_interval: 1s limit_percentage: 65 spike_limit_percentage: 20 resourcedetection: detectors: [env, gcp] timeout: 2s override: false transform: error_mode: ignore trace_statements: - context: span statements: - set(attributes["resource.name"], name) exporters: datadog: api: site: ${DD_SITE} key: ${DD_API_KEY} extensions: health_check: service: extensions: [health_check] pipelines: traces: receivers: [otlp] processors: [memory_limiter, resourcedetection, … -
Django simple ModelForm not showing on page (I'm using class based-views), what could be the problem?
I'm trying to build a form to use it as a filter for my project search page, but the {{form}} shows nothing. Here is how everything is set up: The model I'm trying to use from models.py class Exemplar(models.Model): class Meta: verbose_name_plural = 'Exemplares' tipoDeExemplar = models.ForeignKey(TipoDeExemplar, on_delete=models.SET_NULL, blank=True, null=True, verbose_name="Tipo De Exemplar") numeroDeRegistro = models.CharField(max_length=255, verbose_name="Número Do Registro") especie = models.ForeignKey(Especie, on_delete=models.CASCADE, null=True) dataDoRegistro = models.DateField(blank=True, null=True, verbose_name="Data Do Registro") estadoDoExemplar = models.CharField(blank=True, null=True, max_length=255, verbose_name="Estado do Exemplar") tipoDeMaterial = models.CharField(blank=True, null=True, max_length=255, verbose_name="Tipo De Material") procedencia = models.CharField(blank=True, null=True, max_length=255, verbose_name="Procedência") remetente = models.CharField(blank=True, null=True, max_length=255, verbose_name="Remetente") armario = models.CharField(blank=True, null=True, max_length=255, verbose_name="Armário") gaveta = models.CharField(blank=True, null=True, max_length=255, verbose_name="Gaveta") complemento = models.CharField(blank=True, null=True, max_length=255, verbose_name="Complemento") amostraDeOrigem = models.CharFie fotoDoExemplar = models.ImageField(null=True, blank=True, upload_to='imagens/', verbose_name="Foto Do Exemplar") slug = models.SlugField(max_length=255, unique=True) def __str__(self): return self.numeroDeRegistro My forms.py file (very short) from django.forms import ModelForm from acervo.models import Exemplar class ExemplarForm(ModelForm): class Meta: model = Exemplar fields = '__all__' My view on views.py (seems to be working since I can open the page) class BuscaView(ListView): model = Exemplar template_name = 'busca.html' form_class = ExemplarForm Piece of the HTML template where I try to use the Django ModelForm <form action="" method="post"> … -
Django When I choose an account from the account tree using the check box
Django When I choose an account from the account tree using the check box, the account and its details are displayed on same template template acc.html template acc1.html view.py models.py