Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django drf model viewset self documenting
Was hoping to create a custom ModelViewSet to inherit from, that creates generalized information on the different CRUD routes. Right now we have to overwrite methods that don't need change. Some views require almost every method to be overwritten or writing functions views etc, but others maybe have 1 or 0 changes from just a ModelViewSet. Using django spectacular this makes models way to huge, and hides relevant logic between a clutter of text. I'm hoping there is a smarter/better way to do this? Example Given the simple model NameTag that is beeing delivered in a test api: models.py from django.db import models class NameTag(models.Model): name = models.CharField(max_length=50) serializers.py from rest_framework import serializers from .models import NameTag class NameTagSerializer(serializers.Serializer): class Meta: model = NameTag api.py from rest_framework import viewsets from .models import NameTag from .serializers import NameTagSerializer class NameTagViewset(viewsets.ModelViewSet): serializer_class = NameTagSerializer model = NameTag using extend_schema the viewset becomes huge. documented_api.py from drf_spectacular.utils import extend_schema from rest_framework import serializers, viewsets class NameTagViewset(viewsets.ModelViewSet): serializer_class = NameTagSerializer model = NameTag @extend_schema( operation_id='New NameTag', description='Create a new NameTag', tags=['NameTags'] ) def create(self, request, *args, **kwargs): return super().create(request, *args, **kwargs) @extend_schema( operation_id='List of NameTags', description='All NameTags', tags=['NameTags'], ) def list(self, request, *args, **kwargs): … -
Problem with creating tables in sql python file
i got an Error when i'm trying to crate table and my sql server mycursor = mydb.cursor() mycursor.execute("CREATE TABLE countries (name VARCHAR(300), population size INTEGER(10), \ capital city VARCHAR(300))") mycursor.execute("SHOW TABLES") for tb in mycursor: print(tb) can anyone knows what is the problem with the syntax? -
Django Admin | Filter dropdown on Many to Many based on a foreign key relationship selection
I'm trying to figure out the best way to filter horizontally in Django Admin on a model that has a Many to Many relationship. The goal is in the Inline section when one dropdown is populated the dropdown next to it which has a foreign key relationship to the first dropdown will be filtered. There are TypeSets and TypeValues, a TypeSet has many TypeValues ex. if a TypeSet's type is "wood", the TypeValue types would be ["oak", "cherry", "walnut"] These TypeValues then form a ManyToMany Relationship with "Thing" ( along with the included TypeSet_id ) The goal is in the ThingTypeInline within Django Admin when creating a new Thing I can select the TypeSet from the dropdown which would then filter the TypeValue dropdown next to it. Would this be a custom Form? Models: class TypeSet(models.Model): """TypeSet to be used to describe data type""" id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) type = models.CharField(max_length=255, unique=True) ..... class TypeValue(models.Model): """TypeValue to be used to describe value in the TypeSet""" id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) type = models.CharField(max_length=255) type_set = models.ForeignKey( TypeSet, on_delete=models.CASCADE ) ....... class Thing(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) types = models.ManyToManyField( TypeValue, through='ThingType') .......... class ThingType(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, … -
Django ModelForm: search filter many to many field widget
I'm working with this model: class Sample(models.Model): id_sample = models.AutoField(primary_key=True) name = models.CharField(unique=True, max_length=20) sample_id_sex = models.ForeignKey(Sex, on_delete=models.CASCADE, db_column='id_sex', verbose_name='Sexe') pools = models.ManyToManyField(Pool, through='SamplePoolIndexCand', through_fields=('sample_id', 'pool_id'), blank=True, verbose_name="Pools") pools is a m2m field from this model: class Pool(models.Model): id_pool = models.AutoField(primary_key=True) name = models.CharField(unique=True, max_length=50, verbose_name="Pool") samples = models.ManyToManyField('Sample', through='SamplePoolIndexCand', blank=True, verbose_name="Mostres") I created this ModelForm: class FormulariMostra(ModelForm): class Meta: model = Sample fields = ("name", "sample_id_sex", "pools",) It works fine but the problem is that the pools field can contain thousands of values. A similar question was asked here: Django: Search many to many field while creating object I tried this widget recommended there https://github.com/ExoticObjects/django-better-filter-widget but it seems outdated... Is there any alternative? I know this can be done in the admin but I want to do it in the ModelForm. -
Images aren't loading from AWS S3 in Django
Answer in comments. My images and static files weren't loading from AWS S3 Buckets. And here is How I solved my issue, Check the comments -
django cassandra engine get last item
from cassandra.cqlengine import columns from django_cassandra_engine.models import DjangoCassandraModel from django.db import connections def get_tag(car_name, car_type): class Tag(DjangoCassandraModel): __table_name__ = car_name + "_" + car_type time = columns.Integer(primary_key=True, required=True) # unix time in seconds # noqa value = columns.Float(required=True) with connections['cassandra'].cursor() as cursor: cursor.execute("CREATE TABLE IF NOT EXISTS mydatabase." + __table_name__ + " (time INT PRIMARY KEY, value FLOAT);") # noqa def last(): with connections['cassandra'].cursor() as cursor: elem = cursor.execute("SELECT * FROM " + Tag.__table_name__ + " ORDER BY time DESC LIMIT 1;") # noqa return elem def __str__(self) -> str: return str(self.time) + "," + str(self.value) return Tag Usage in code: tag = get_tag(car_name, car_type) last_elem = tag.last() Produced error when calling tag.last(): cassandra.InvalidRequest: Error from server: code=2200 [Invalid query] message="ORDER BY is only supported when the partition key is restricted by an EQ or an IN." Hello. I have a dynamic Django model creation in Cassandra. (time, value) measurements. How to get the last element in the table based on time (primary key)? My implementation has an error. -
Get list of values from grandchildren records
I'm trying to access the grandchildren records in a list to avoid duplicate records. In this example, a tag can only be used once across articles for a given author. I will use the resulting list of grandchildren records in my clean function to return validation errors. class Article(models.Model): tag = models.ManyToManyField(Tag) author = models.ForeignKey(Author, on_delete=models.CASCADE) class Tag(models.Model): class Author(models.Model): Right now I can do this: print(author.articles.first().tag.first()) Travel I'd like to be able to use something like author.articles.tags.all() to return the list and check the submitted form against it to raise a ValidationError message to the user. How can this be done efficiently with the basic Many-to-Many setup without creating an intermediate table for the tag relationships? This is solely in the Admin interface, in case that matters at all. -
pymongo.errors.ServerSelectionTimeoutError [SSL: CERTIFICATE_VERIFY_FAILED]
I am using MongoDB(Mongo Atlas) in my Django app. All was working fine till yesterday. But today, when I ran the server, it is showing me the following error on console Exception in thread django-main-thread: Traceback (most recent call last): File "c:\users\admin\appdata\local\programs\python\python39\lib\threading.py", line 973, in _bootstrap_inner self.run() File "c:\users\admin\appdata\local\programs\python\python39\lib\threading.py", line 910, in run self._target(*self._args, **self._kwargs) File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\Lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\Lib\site-packages\django\core\management\commands\runserver.py", line 121, in inner_run self.check_migrations() File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\Lib\site-packages\django\core\management\base.py", line 486, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\Lib\site-packages\django\db\migrations\executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\Lib\site-packages\django\db\migrations\loader.py", line 53, in __init__ self.build_graph() File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\Lib\site-packages\django\db\migrations\loader.py", line 220, in build_graph self.applied_migrations = recorder.applied_migrations() File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\Lib\site-packages\django\db\migrations\recorder.py", line 77, in applied_migrations if self.has_table(): File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\Lib\site-packages\django\db\migrations\recorder.py", line 56, in has_table tables = self.connection.introspection.table_names(cursor) File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\Lib\site-packages\django\db\backends\base\introspection.py", line 52, in table_names return get_names(cursor) File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\Lib\site-packages\django\db\backends\base\introspection.py", line 47, in get_names return sorted(ti.name for ti in self.get_table_list(cursor) File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\Lib\site-packages\djongo\introspection.py", line 47, in get_table_list for c in cursor.db_conn.list_collection_names() File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\Lib\site-packages\pymongo\database.py", line 880, in list_collection_names for result in self.list_collections(session=session, **kwargs)] File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\Lib\site-packages\pymongo\database.py", line 842, in list_collections return self.__client._retryable_read( File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\Lib\site-packages\pymongo\mongo_client.py", line 1514, in _retryable_read server = self._select_server( File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\Lib\site-packages\pymongo\mongo_client.py", line 1346, in _select_server server = topology.select_server(server_selector) File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\Lib\site-packages\pymongo\topology.py", line 244, in select_server return random.choice(self.select_servers(selector, File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\Lib\site-packages\pymongo\topology.py", line 202, … -
Execute multiple celery tasks inside a celery task
im looking to execute multiple related celery tasks within another celery task. Is this even possible? Code below will give a better idea of what i am trying to accomplish @shared_task(ignore_result=True) def test_job(): try: another_test_job.delay() yet_another_test_job.delay() except Exception as e: logger.error(f'Something happened when collecting edr data ===> {e}') raise @shared_task(ignore_result=True) def another_test_job(): try: print('this is another test') except Exception as e: logger.error(f'Something happened when collecting edr data ===> {e}') raise @shared_task(ignore_result=True) def yet_another_test_job(): try: print('this is yet another test') except Exception as e: logger.error(f'Something happened when collecting edr data ===> {e}') raise My goal is to try to consolidate the amount of tasks i schedule essentially assigning my tasks under one task. I have tried executing my task manually using test_job.apply() results in In [2]: test_job.apply() 2021-09-30 13:57:49,196 amqp DEBUG Start from server, version: 0.9, properties: {'capabilities': {'publisher_confirms': True, 'exchange_exchange_bindings': True, 'basic.nack': True, 'consumer_cancel_notify': True, 'connection.blocked': True, 'consumer_priorities': True, 'authentication_failure_close': True, 'per_consumer_qos': True, 'direct_reply_to': True}, 'cluster_name': 'someclustername', 'copyright': 'Copyright (c) 2007-2020 VMware, Inc. or its affiliates.', 'information': 'Licensed under the MPL 2.0. Website: https://rabbitmq.com', 'platform': 'Erlang/OTP 22.3.4.11', 'product': 'RabbitMQ', 'version': '3.8.9'}, mechanisms: [b'PLAIN'], locales: ['en_US'] 2021-09-30 13:57:49,259 amqp DEBUG using channel_id: 1 2021-09-30 13:57:49,307 amqp DEBUG Channel open 2021-09-30 13:57:49,431 … -
Django merge QuerySet while keeping the order
i'm trying to join together 2 QuerySets. Right now, I'm using the | operator, but doing it this way won't function as an "append". My current code is: df = RegForm((querysetA.all() | querysetB.all()).distinct()) I need the elements from querysetA to be before querysetB. Is it even possible to accomplish while keeping them just queries? -
How can I replace a button with a message after once click on it in Django
I am trying to add a button('Add to your watchlist'), when user click on that the button will replaced with a text which will say 'Item is added to your watchlist'. How can I emplement this on my code? Is there no way (without JavaScript) adding this feature in my web application ? In urls.py: path('listing/<int:auction_id>', views.auction, name='auction'), path('listing/<int:auction_id>/wachlist', views.add_to_watchlist, name="add_to_watchlist") In views.py: def add_to_watchlist(request, auction_id): auction = AuctionListing.objects.get(pk=auction_id) user = User.objects.get(username=request.POST['username']) try: watch_key = Watchlist.objects.get(owner=user) except: watch_key = Watchlist.objects.create(owner=user) auction.watch_item.add(watch_key) return redirect('auction',auction_id=auction.id) In auction.html: <form action="{% url 'add_to_watchlist' auction.id %}" method="POST"> {% csrf_token %} <input type="hidden" name="username" value="{{ user.username }}"/> <input type="submit" class="btn btn-success" value="Add to your watchlist" style="float:right" /> </form> -
Sum of Integers error django.db.utils.ProgrammingError: function sum(jsonb) does not exist
I'm trying to aggregate Sum() to a queryset, the fields are simple IntegerField() but this error appears. Error: The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/usr/local/lib/python3.6/site-packages/django/views/generic/base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py", line 495, in dispatch response = self.handle_exception(exc) File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py", line 455, in handle_exception self.raise_uncaught_exception(exc) File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py", line 492, in dispatch response = handler(request, *args, **kwargs) File "/opt/companies/api/v2/views.py", line 86, in get ticket_closed_time=Avg(F("ticket_closed_time")), File "/usr/local/lib/python3.6/site-packages/django/db/models/query.py", line 379, in aggregate return query.get_aggregation(self.db, kwargs) File "/usr/local/lib/python3.6/site-packages/django/db/models/sql/query.py", line 489, in get_aggregation result = compiler.execute_sql(SINGLE) File "/usr/local/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1100, in execute_sql cursor.execute(sql, params) File "/usr/local/lib/python3.6/site-packages/django/db/backends/utils.py", line 99, in execute return super().execute(sql, params) File "/usr/local/lib/python3.6/site-packages/django/db/backends/utils.py", line 67, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "/usr/local/lib/python3.6/site-packages/django/db/backends/utils.py", line 76, in _execute_with_wrappers return executor(sql, params, many, context) File "/usr/local/lib/python3.6/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/usr/local/lib/python3.6/site-packages/django/db/utils.py", line 89, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "/usr/local/lib/python3.6/site-packages/django/db/backends/utils.py", line 84, in _execute return … -
How do I schedule objects to created for a model in django?
I have a notice model that creates s notice (it contains title, description and date). I would like to schedule notices to be created at certain dates. Basically, I mean using another model I want to schedule and create the notices at that date specified. How would I do this? What's the easier road to achieve this? All I can think of is rabbitmq and celery. And i don't even know how it would create s notice at a dynamic date. -
How to create a form with foreign key django
I'm working on a Django project and getting the Value error below. I think the problem is in the category field because if I will comment it in new.html, it adding a listing without the problem. However, I can't find where is the error. ValueError at /new The view auctions.views.add_listing didn't return an HttpResponse object. It returned None instead. This is my models.py: class Category(models.Model): name = models.CharField(max_length=64) def __str__(self): return self.name class Listing(models.Model): title = models.CharField(max_length=64) description = models.CharField(max_length=256) price = models.DecimalField(max_digits=24, decimal_places=2) photo = models.ImageField() bid = models.ForeignKey(Bid, on_delete=models.CASCADE, blank=True, null=True) user = models.ForeignKey(User, on_delete=models.CASCADE, default=1) category = models.ManyToManyField(Category, default=None, blank=True) def __str__(self): return self.title views.py: def add_listing(request): if request.method == "POST": form = ListingForm(request.POST, request.FILES) print('FORM CREATED') print(form.is_valid()) if form.is_valid(): print('FORM IS VALID') print(form.cleaned_data) new_listing = form.save(commit=False) return HttpResponseRedirect(reverse(listing, args={new_listing.pk,})) else: pass else: return render(request, "auctions/new.html",{ 'category':Category.objects.all() }) new.html: <form action="" method="POST" name="listing" enctype="multipart/form-data"> {% csrf_token %} <h4>Title</h4> <input type="text" name="title"> <h4>Choose category</h4> <select name="category" id=""> {% for type in category %} <option value="{{ type }}" name="category">{{ type }}</option> {% endfor %} </select> <h4>Description</h4> <input type="text" name="description"> <h4>Price</h4> <input type="number" name="price"> <h4>Photo</h4> <input type="file" accept="image/*" name="photo" id="file"> <!-- <p>Or provide URL of image</p> <input type="text" name="image_url"/> --> … -
Why use get_absolute_url function not work?
I am trying to use get_absolute_url to get an object (post_detail) from (post_list), but returns with no object and still in the same page (post_list) with no error. in views.py : # Object list using Function-based-views def post_list(request): post_list=Post.objects.all().order_by('-created_at') lastest=post_list.order_by('-created_at')[:4] last_post= post_list.order_by('-created_at')[0] context={ 'allpost':post_list, 'latest':lastest, 'lastpost':last_post } return render(request,'post/post_list.html',context) # Post_singl_object using DetailView class PostDetail(DetailView): model=Post context_object_name='post_detail' def get_context_data(self, **kwargs): context= super().get_context_data(**kwargs) context['slug']=super().get_context_data(**kwargs) return context urls.py : from django.urls import path from . import views app_name="allpost" urlpatterns = [ path('', views.post_list), path('<slug:slug>',views.PostDetail.as_view(),name='post_detail'), ] in my templates in page (post_list.html) i loop for list objects to get (title,headline, image, and author), but in a link i use ( def get_absolute_url(self): return reverse("post_detail", kwargs={'slug': self.slug} ) to redirect to post page, but that's not work and still in same page (post_list). in post_list.html : {% for post in allpost %} <a href="{{ post_detail.get_absolute_url }}" class="stretched-link">Continue reading</a> {% endfor %} any idea ? -
Django foreign key as primary key?
The question In Django, is it possible to use a foreign key as the primary key for a model? For example: Context Let's say that we have class Reporter that has many Articles, but if we remove our reporter from our database, we also want the articles that belonged to them to be deleted. The schema is a one-to-many relationship, where one reporter has many articles, and the existence of the article instances in the database relies on the reporter instance. What I am confused about specifically What kind of Django relationship would I need to achieve this business requirement? Unfortunately, I have read all of the Django documentation. Therefore, I cannot find which database relationship makes the most sense, and I hope someone with more experience than me in Django and PostgreSQL can help out. Bonus points Imagine that each article needs to be in a specific arbitrary order and that this is also a constraint of the database relationship. -
AWS S3 Lambda Trigger Not Working When Uploaded to Bucket Subfolder
I have a Lambda Python function that will resize images on upload. Everything is working correctly, but only when I upload directly to the bucket. When I upload files to the bucket/uploads/ folder, it would no longer trigger the resize function. I have tried the filtering options in the trigger settings uploads/ to no avail. Assuming it is related to my Lamda function and the folder should/must also be included? Here is my Lambda function: def lambda_handler(event, context): for record in event["Records"]: bucket = record["s3"]["bucket"]["name"] key = record["s3"]["object"]["key"] download_path = "/tmp/{}{}".format(uuid.uuid4(), key) upload_path = "/tmp/resized-{}".format(key) s3_client.download_file(bucket, key, download_path) -
pass value for two different submit buttons in same form methods in Django
Lets us consider my template.html as <form class="form-horizontal" id="adhoc-form" method="post" action="{% url 'contacts:add_item' item.id %}"> {% csrf_token %} <fieldset> <div class="control-group"> <label for="id_item_filename" class="control-label">Items <span class="text-error">*</span></label> <div class="controls"> <select placeholder="Item filename" name="item" id="id_item_filename" class="span3" required="required"> <option value="">---------</option> {% for i in items %} <option value="{{i.0}}">{{i.1}}</option> {% endfor %} </select> </div> </div> </fieldset> <div id="form-buttons-container" class="form-actions" style="padding-left: 0px;"> <div class="controls"> <input type="hidden" class="btn btn-primary btn-medium" id= 'i_id' name='i_id' value="{{data.0.id}}"> <input type="submit" class="btn btn-primary btn-medium" value="Submit"> <input type="submit" class="btn btn-primary btn-medium" value="Delete"> </div> </div> </form> my url.py is url(r'^stock/item/add/item_name/(?P<id>\d+)/$', login_required(UpdateBarcode.as_view()), name="add_item"), my views.py is class UpdateItem(View): def post(self, request, id): item_id = request.POST.get('item') items = Items.objects.get(id=item_id) try: JobItems.objects.filter(id=id).update(item_name=items.name) except: messages.error(request, 'Cannot update') return redirect(reverse("contacts:item_list")) Here when clicking the submit button we need to update item and we click delete button item should be deleted.please help me how can do both the submit and delete operations in the same view -
Django context processor not rendering from shell
Using Django 3.2 Have defined few global variables like app/context_processors.py from app.settings import constants def global_settings(request): return { 'APP_NAME': constants.APP_NAME, 'APP_VERSION': constants.APP_VERSION, 'STATIC_URL_HOST': constants.STATIC_URL_HOST } and in settings.py file TEMPLATES = [ { ... 'OPTIONS': { 'context_processors': [ ... 'app.context_processors.global_settings', ], }, }, ] Have used APP_NAME in the email template footer like templates/account/welcome_message.html Hi {{ username }}, Welcome to the application. {{ APP_NAME }} When the email is sent from the web portal, the APP_NAME is rendered fine, but when the email send is initiated from the Django shell python manage.py shell > from account.emails import welcome_email > welcome_email(user) Then the APP_NAME is not rendered in the email. How the context processor can be rendered from the shell as well? -
TypeError: Complex aggregates require an alias
I have this very normal Sum of various fields, but it always returns the error in the title, what is missing? ticket_history_aggregation = ticket_history_aggregation.aggregate( ticket_total=Sum("ticket_total", 0), ticket_queue=Sum("ticket_queue", 0), ticket_queue_expiring= Sum("ticket_queue_expiring", 0), ticket_processing_expiring =Sum("ticket_processing_expiring", 0), ticket_pending=Sum("ticket_pending", 0), -
error when trying to run "runserver" after reinstalling windows 10
So I reinstalled my computer but before that I backed up my code files and after that I installed python and and venv again. i was able to run the virtualenv but when i tried to do runserver this error pops up Python path configuration: PYTHONHOME = (not set) PYTHONPATH = (not set) program name = 'C:\coding\e-commerce/Scripts\python.exe' isolated = 0 environment = 1 user site = 1 import site = 1 sys._base_executable = 'C:\\coding\\e-commerce\\Scripts\\python.exe' sys.base_prefix = '' sys.base_exec_prefix = '' sys.executable = 'C:\\coding\\e-commerce\\Scripts\\python.exe' sys.prefix = '' sys.exec_prefix = '' sys.path = [ 'C:\\coding\\e-commerce\\Scripts\\python38.zip', '.\\DLLs', '.\\lib', 'c:\\users\\chp\\appdata\\local\\programs\\python\\python38-32', ] Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding Python runtime state: core initialized ModuleNotFoundError: No module named 'encodings' Current thread 0x000010f8 (most recent call first): <no Python frame> can anyone explain this error to me? thank you very much -
Why my generated docx in javascript from a blob is filled with [Object Object]?
I'm sending data to my Django backend through a POST request, the server then creates a docx using this data and sends it back to me where I'm trying to download it using the following code : axios.post(route, data).then((res) => { const filename = "report.docx" var blob = new Blob([res], { type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' }); var link = document.createElement('a'); var URL = window.URL || window.webkitURL; var downloadUrl = URL.createObjectURL(blob); link.href = downloadUrl; link.style = "display: none"; link.download = filename; document.body.appendChild(link) link.click() link.remove() }); The download of the file works but when I open it, it only contains [Object Object], what am I doing wrong here ? I checked the backend and the document is properly created as it has the right content when I'm saving it when it's generated in the server so it's either that i'm sending it badly or creating the file in the frontend badly. Here is how I send it from the backend : #Generating the doc properly before this... response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document') report_filename = 'graph-report-'+now.strftime('%Y-%m-%d_%H-%M-%S')+'.docx' response['Content-Disposition'] = 'attachment; filename=%s'%(report_filename) document.save(response) return response Thanks for helping me. -
lunch a modal after registration login if form in invalid , Django
i want to lunch a modal if the information put on the Form Is incorrect. Here is the view code : def ajouterClient(request): if request.method == "POST": form = ClientForm(request.POST) if form.is_valid(): form.save() return redirect('home') else: erreur = "erreur" return render(request, 'frontend/home.html' , locals()) And Here is the template code: {% if erreur == "erreur" %} <div class="modal fade" id="erreur" tabindex="-1" aria-labelledby="erreurLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header bg-dark text-white"> <h5 class="modal-title" id="loginLabel">Erreur</h5> <button type="button" class="btn-close bg-light" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body bg-light"> <h1>Veuillez remplir tous les champs correctement</h1> </div> <div class="modal-footer"> </div> </div> </div> </div> <script> $(document).ready(function(){ $('#erreur').modal('show') }); </script> {% endif %} <!-- End Erreur Modal ajout --> -
django orm filters and nested Prefetch
I need to get all users who have instances with the status of running or creating, and get instances for these users with the same filter, my query looks like queryset = User.objects.filter( Q(testinstance__status=TestInstance.RUNNING) | Q(testinstance__status=TestInstance.CREATING) ).order_by('first_name').prefetch_related(Prefetch( 'testinstance_set', queryset=TestInstance.objects.filter( Q(status=TestInstance.RUNNING) | Q(status=TestInstance.CREATING) ).order_by('-started_at') )).distinct() models: class TestInstance(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) Can I somehow avoid duplicate filters ? -
Rendering Grafana inside django website using API Key
I’m attempting to pass an API token for a user to grafana from our own internal website so that the main gui renders in an iframe. We don’t want the users to have to log into grafana after they have logged into our site, so we are creating their users in grafana, building an API token and attaching that to the user for our website. When the user goes to the page that has the grafana iframe, we are sending an ajax get request with the token so grafana renders the main dashboards with the users information. If we do just a standard iframe everything works fine and we render inside the frame. We can get to the login page and do everything we need to. When I add the token so we don’t need to authenticate nothing renders and I see no errors/logs on either grafana or the website. If I send an invalid token I see the expected “401 invalid Api key” error on both the website and the grafana logs. This is what I’m sending from the website… <div class="content"> <div class="container-fluid" id="container"> </div> </div> <script> $.ajax({ url: "{{url}}", type: "GET", beforeSend: function(xhr){ xhr.setRequestHeader('Accept', 'application/json'); xhr.setRequestHeader('Authorization', 'Bearer …