Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django background tasks - problem with process_tasks
I have a strange case and don't know how to solve it. Namely I have installed Django background tasks, made a migration and added to installed aps. I run python manage.py process_tasks in the terminal, open a second terminal and runserver. Everything is ok. In the admin panel I see: Completed Tasks and Tasks. The first terminal listens all the time for the execution of the task and when I let it go it works perfectly. However, if I enter Completed Tasks or Tasks in Admin while the task is running, the first terminal immediately stops listening and goes back to waiting for the prompt. Anyone perhaps know what this is all about? -
Django Rest Framework New User Registration with Admin activation
in the old Django times I was able to set the is_activated hidden field per registration of the user data to let the new user to registrate but not able tro login. An admin needed to activate the account - perfect. With the django rest framework I can't find a possibility to do the same action. Can I get a hind please .... thank you very much. Other maybe stupid question of this - how can I prevent the user from login without validation ( not Email validation ) Thanks a lot Greetings RR I tried successfully to add a user with all the methods I found online but always is_active was true Also it looked that the framework is always taking this field as true because its an admin feature to deactivate accounts - but this is the same I like to do. -
Django and extract IPTC from images
Maybe a stupid question, but how can I extract information from the image, such as description, headline and keywords using Django & Pillow? I have this now, but it dont work at all.. Can you help me to fix this or help me with a solution? I can see the IPTC information in photoshop and other software, but i cant see it if upload the images in my django project. def extract_iptc_data(image_file): print("Extracting IPTC data...") # Add this print statement # Open the image file img = PilImage.open(image_file) # Initialize title, description, and keywords title = None description = None keywords = [] # Extract XMP metadata xmp_data = img.info.get("xmp", b"") print("XMP Data:", xmp_data) # Print XMP metadata for debugging if xmp_data: # Parse XMP metadata xmp_tree = ET.fromstring(xmp_data) # Find headline (title), keywords, and description for elem in xmp_tree.iter(): if elem.tag.endswith("Headline"): title = elem.text elif elem.tag.endswith("Keywords"): keywords.extend(elem.text.split(",")) elif elem.tag.endswith("Description"): description = elem.text return title, description, keywords -
how to solve JSONDecodeError
def edit_post(request, post_id): if request.method == 'POST':` data = json.loads(request.body) post = Post.objects.get(pk=post_id) post.content = data['content'] post.save() return JsonResponse({"message": "Post edited successfully.", "data": data['content']}) getCookie = (name) => { const value = ; ${document.cookie}; const parts = value.split(; ${name}=); if (parts.length == 2) return parts.pop().split(';').shift(); } update = (id) => { const updatedValue = document.getElementById(`textarea_${id}`).value fetch(`/edit_post/${id}`, { method: "POST", headers: { "Content-type": "application/json", "X-CSRFToken": getCookie("csrftoken") }, body: JSON.stringify({ content: updatedValue }) }) .then(response => response.json()) .then(result => console.log(result) ) } path("edit_post/<int:post_id>", views.edit_post, name="edit_post"), The function is working fine because the post are updated when reloaded but when i click on post i am thrown to this error. JSONDecodeError at /edit_post/18 Expecting value: line 1 column 1 (char 0) Request Method: POST Request URL: ``http://127.0.0.1:8000/edit_post/18 Django Version: 5.0 Exception Type: JSONDecodeError Exception Value: Expecting value: line 1 column 1 (char 0) Exception Location: C:\Program Files\Python312\Lib\json\decoder.py, line 355, in raw_decode Raised during: network.views.edit_post Python Executable: C:\Program Files\Python312\python.exe Python Version: 3.12.0 // html {% if user.is_authenticated %} {% if user == post.user %} <a class="editButton btn btn-link"> Edit </a> <div class="editModal modal"> <div class="modal-content"> <!-- Add a close button --> <span class="ecloseButton" style="position: absolute; right: 20px; top: -8px;left: 530px; font-size: `your text`20px; cursor: … -
KeyError while using CreateView on Django
when im trying to create an objet 'Comprobante' throws me the error: KeyError at /caja_chica/comprobantes/crear/ 'comprobante' Request Method: POST Request URL: http://127.0.0.1:8000/caja_chica/comprobantes/crear/ Django Version: 3.2.5 Exception Type: KeyError Exception Value: 'comprobante' here is my model Comprobante: class Comprobante(models.Model): TIPO_A = 1 TIPO_B = 2 TIPO_C = 3 TIPO_T = 4 TIPO_X = 5 TIPO_CHOICES = ( (TIPO_A, 'A'), (TIPO_B, 'B'), (TIPO_C, 'C'), (TIPO_T, 'T'), (TIPO_X, 'X'), ) caja_chica = models.ForeignKey(CajaChica, on_delete=models.PROTECT) lote = models.ForeignKey(Lote, on_delete=models.DO_NOTHING, null=True, blank=True, related_name='lote_comprobantes') numero = models.CharField(max_length=13) tipo = models.PositiveSmallIntegerField(choices=TIPO_CHOICES, default=TIPO_T) ente = models.ForeignKey(Ente, on_delete=models.PROTECT) fecha = models.DateField() partida_presupuestaria = models.ForeignKey(PartidaPresupuestaria, on_delete=models.PROTECT) detalle = models.CharField(max_length=100) importe = models.DecimalField(max_digits=7, decimal_places=2) history = HistoricalRecords() def __str__(self): return self.numero #def save(self, *args, **kwargs): # super(Comprobante, self).save(*args, **kwargs) # self.caja_chica.disponible -= self.importe # self.caja_chica.save() def get_absolute_url(self): """ Devuelve la url para acceder a una instancia particular de Comprobante. """ return reverse('caja_chica:comprobante_update', args=[str(self.id)]) here is my form: class ComprobanteForm(forms.ModelForm): class Meta: model = Comprobante fields = ('__all__') my view using CreateView: class ComprobanteCreate(SuccessMessageMixin, CreateView): model = Comprobante fields = '__all__' success_url = reverse_lazy('caja_chica:comprobante_list') success_message = "%(comprobante)s fue creado exitosamente" and my template of comprobante_form: {% extends "caja_chica/base.html" %} {% block breadcrumbs %} <div class="breadcrumbs"> <a href="{% url 'caja_chica:inicio' %}">Inicio</a> > <a … -
Getting ReplicaSetNoPrimary error for M0 cluster when using Django with MongoEngine
I am using django with mongoengine. I am writing the following in the settings.py file: from mongoengine import connect URI = 'mongodb+srv://myusername:mypassword@cluster0.5apjp.mongodb.net/django?retryWrites=true&w=majority&ssl=false' connect(host=URI) After that, I have a model as follows: from mongoengine import Document, StringField class User(Document): first_name = StringField(max_length=50) last_name = StringField(max_length=50) meta = { 'collection': 'users' } I have a view as follows: def adduser(request): userDict = json.loads(request.body) newUser = User(first_name=userDict['firstName'],last_name=userDict['lastName']) newUser.save() return HttpResponse('user added') When this view function is called, I get an error as follows: ServerSelectionTimeoutError( pymongo.errors.ServerSelectionTimeoutError: cluster0-shard-00-02.5apjp.mongodb.net:27017: connection closed (configured timeouts: socketTimeoutMS: 20000.0ms, connectTimeoutMS: 20000.0ms),cluster0-shard-00-01.5apjp.mongodb.net:27017: connection closed (configured timeouts: socketTimeoutMS: 20000.0ms, connectTimeoutMS: 20000.0ms),cluster0-shard-00-00.5apjp.mongodb.net:27017: connection closed (configured timeouts: socketTimeoutMS: 20000.0ms, connectTimeoutMS: 20000.0ms), Timeout: 30s, Topology Description: <TopologyDescription id: 65c3bdc13c9136a1191890e1, topology_type: ReplicaSetNoPrimary, servers: [<ServerDescription ('cluster0-shard-00-00.5apjp.mongodb.net', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('cluster0-shard-00-00.5apjp.mongodb.net:27017: connection closed (configured timeouts: socketTimeoutMS: 20000.0ms, connectTimeoutMS: 20000.0ms)')>, <ServerDescription ('cluster0-shard-00-01.5apjp.mongodb.net', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('cluster0-shard-00-01.5apjp.mongodb.net:27017: connection closed (configured timeouts: socketTimeoutMS: 20000.0ms, connectTimeoutMS: 20000.0ms)')>, <ServerDescription ('cluster0-shard-00-02.5apjp.mongodb.net', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('cluster0-shard-00-02.5apjp.mongodb.net:27017: connection closed (configured timeouts: socketTimeoutMS: 20000.0ms, connectTimeoutMS: 20000.0ms)')>]> [07/Feb/2024 23:02:38] "POST /user/adduser HTTP/1.1" 500 115166 I am using a mongodb free M0 cluster with database named as 'django' and collection named as 'users'. If I use a non-SRV URI string like localhost:27017, it … -
How to run a one-off ECS task in CodePipeline using Terraform?
I'm trying to set up deployment for a Django web app using Code Build, Code Pipeline and Terraform but I can't figure out how to start a one off task in the pipeline to run the migrations. I've found this code snipper for the stage but it seems TaskDefinition is not a valid name in the config for aws_codepipeline. stage { name = "RunMigrations" action { name = "RunMigrationsAction" category = "Deploy" owner = "AWS" provider = "ECS" version = "1" input_artifacts = ["BuildOutput"] configuration = { ClusterName = var.ecs_cluster_name TaskDefinition = "django-migration-task" } } } resource "aws_ecs_task_definition" "django_migration" { family = "django-migration-task" network_mode = "awsvpc" requires_compatibilities = ["FARGATE"] execution_role_arn = aws_iam_role.ecs-task-execution-role.arn cpu = 256 memory = 512 container_definitions = jsonencode([ { name = "django-migration-container" image = aws_ecr_repository.ecr_repository.repository_url command = ["python", "manage.py", "migrate"] logConfiguration = { logDriver = "awslogs" options = { awslogs-group = "/ecs/logs" awslogs-region = var.aws_region awslogs-stream-prefix = "ecs" } } portMappings = [ { containerPort = 8000 } ] } ]) } -
"Given token not valid for any token type" error in django when i send header with Authorization: None
When I send request to my backend i got error: { "detail": "Given token not valid for any token type", "code": "token_not_valid", "messages": [ { "token_class": "AccessToken", "token_type": "access", "message": "Token is invalid or expired" } ] } I have this in views.py class ProblemViewSet(viewsets.ModelViewSet): queryset = models.Problem.objects.all() serializer_class = serializers.ProblemSerializer permission_classes = [] def retrieve(self, request, *args, **kwargs): print(request.META) instance = self.get_object() user = request.user if user is not None and not user.is_anonymous: interaction, created = models.InteractionUserProblem.objects.get_or_create(user=user, problem=instance) if created: interaction.is_viewed = True interaction.save() serializer = self.get_serializer(instance) return Response(serializer.data) and this in settings.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ["rest_framework_simplejwt.authentication.JWTAuthentication"], 'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend'], "TEST_REQUEST_DEFAULT_FORMAT": "json", 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 10, } from frontend come header with Authorization: Bearer none if user is not authenticated. I know solution to add authentication_classes = [], but i need authentication, to recognize user if he is authenticated. So how can i fix it, maybe i need to add some middleware? I tried to add authentication_classes = [], but this is not solution for me. I need to catch Authorization: Bearer none somehow and process it. -
Restrict output of fields in Django admin according to previous selection
I have this model.py: class Funder(models.Model): name = models.CharField(max_length=200) scheme = models.ManyToManyField('Scheme', blank=True) class Scheme(models.Model): name = models.CharField(max_length=200)) class Project(models.Model): title = models.CharField(max_length=200) funder = models.ManyToManyField(Funder) scheme = models.ForeignKey(Scheme, on_delete=models.SET_NULL) A funder can have 0, 1, or many schemes attached to it. I'd like to limit the choice of schemes that can be selected from the admin form for project to only the schemes that belong to a specific funder. Is that possible? Example: in 'new project', people select funder1, and only see scheme1, scheme3, scheme5 in the drop-down for scheme, because scheme2 and scheme4 are associated to funder2. Is this something that can be obtained with a QuerySet? My ModelAdmin: from import_export.admin import ImportExportModelAdmin class FunderAdmin(ImportExportModelAdmin): search_fields = ['name',] autocomplete_fields = ['scheme'] list_display = ("name",) -
How to implement HMTX with Django Class Based Views
I am trying to understand how to utilise htmx with Django Class Based Views. To provide some context, here is a reflection of the scenario in which I want to implement django class based views and htmx together: I have an initial view, which renders the main template and initial context. As part of this initial context, I am including a date form. I want to use htmx to post the data from this form to an APIView (let’s call it APIView1). I would like APIView1 to ingest the data which is posted to it via htmx, run a function on it, and then return data back as context, while rendering a partial template (let’s call it PartialTemplate1) which utilises that context. So from what I understand, I can do this within a get() function; so it may look a little like this: views.py Class InitialView(View): template_name = “initial_template.html” form_class = date_form def get(self, request, *args, **kwargs): … date_form=self.form_class() context = { 'date_form': date_form } return render(request, template_name, context) Class APIView1(APIView): template_name = “PartialTemplate1.html” def get(self, request, *args, **kwargs): date = request.POST.get(‘date’) timeslots = function(date) context = { ‘timeslots’: timeslots } return render(request, template_name, context). initial_template.html: <form hx-post='{% url "appname:apiview1_url" … -
Warning: Received `true` for a non-boolean attribute `crossOrigin` when using NextJS/React + Django Rest Framework
I've been receiving this warning but have little idea where it may originating from or how to solve it. It appeared seemingly out of nowhere. I went back a few commits and the warning still appeared, although I'm certain it was not present when I was initially working on those commits. I have some suspicions it may be related to CORS, or to my snake_case to camelCase converting middleware. I am using a NextJS/React frontend and a Django Rest Framework backend. Error message: app-index.js:35 Warning: Received `true` for a non-boolean attribute `crossOrigin`. If you want to write it to the DOM, pass a string instead: crossOrigin="true" or crossOrigin={value.toString()}. at link at head at html at RedirectErrorBoundary (webpack-internal:///(app-pages-browser)/./node_modules/next/dist/client/components/redirect-boundary.js:73:9) at RedirectBoundary (webpack-internal:///(app-pages-browser)/./node_modules/next/dist/client/components/redirect-boundary.js:81:11) at NotFoundErrorBoundary (webpack-internal:///(app-pages-browser)/./node_modules/next/dist/client/components/not-found-boundary.js:76:9) at NotFoundBoundary (webpack-internal:///(app-pages-browser)/./node_modules/next/dist/client/components/not-found-boundary.js:84:11) at DevRootNotFoundBoundary (webpack-internal:///(app-pages-browser)/./node_modules/next/dist/client/components/dev-root-not-found-boundary.js:33:11) at ReactDevOverlay (webpack-internal:///(app-pages-browser)/./node_modules/next/dist/client/components/react-dev-overlay/internal/ReactDevOverlay.js:84:9) at HotReload (webpack-internal:///(app-pages-browser)/./node_modules/next/dist/client/components/react-dev-overlay/hot-reloader-client.js:307:11) at Router (webpack-internal:///(app-pages-browser)/./node_modules/next/dist/client/components/app-router.js:181:11) at ErrorBoundaryHandler (webpack-internal:///(app-pages-browser)/./node_modules/next/dist/client/components/error-boundary.js:114:9) at ErrorBoundary (webpack-internal:///(app-pages-browser)/./node_modules/next/dist/client/components/error-boundary.js:161:11) at AppRouter (webpack-internal:///(app-pages-browser)/./node_modules/next/dist/client/components/app-router.js:536:13) at ServerRoot (webpack-internal:///(app-pages-browser)/./node_modules/next/dist/client/app-index.js:129:11) at RSCComponent at Root (webpack-internal:///(app-pages-browser)/./node_modules/next/dist/client/app-index.js:145:11) Django settings.py: CORS_ALLOWED_ORIGINS = [ "http://127.0.0.1:3000", "https://localhost:3000", ] INSTALLED_APPS = [ "core", "rest_framework", "corsheaders", "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "compressor", ] MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "corsheaders.middleware.CorsMiddleware", "djangorestframework_camel_case.middleware.CamelCaseMiddleWare", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", ] React Frontend API calls: import * as constants from '../constants/endpoints' … -
Django fields not saving
I want to receive a file from the client and perform some processing on the image in the corresponding model class before it is saved in the database. However, since the file is not saved until the end of the save() method, the directory where the file is stored is not created and I get the error FileNotFoundError: [Errno 2] No such file or directory: 'media/upload/vertical_image.jpg'. I'm actually looking for a way to do all the processing in the save method this is my Media model: title = models.CharField(max_length=255, null=True, blank=True) file = models.FileField(upload_to="upload/") filename = models.CharField(max_length=255, null=True, blank=True) mime_type = models.CharField(max_length=255, null=True, blank=True) thumbnail = models.JSONField(null=True, blank=True) size = models.FloatField(null=True, blank=True) url = models.CharField(max_length=300, null=True, blank=True) thumbhash = models.CharField(max_length=255, blank=True, null=True) is_public = models.BooleanField(blank=True, null=True) def save(self, *args, **kwargs): sizes = [(150, 150), (256, 256)] media_path = f"media/upload/{self.filename}" image = Image.open(media_path) mime_type = image.get_format_mimetype() format = mime_type.split("/")[1] if not os.path.exists("media/cache"): os.makedirs("media/cache") thumbnail = {} for i, size in enumerate(sizes): resized_image = image.resize(size) index = "small" if i == 0 else "medium" file_path = os.path.join( "media", "cache", f"{self.id}-resized-{self.filename}-{index}.{format}", ) resized_image.save(file_path, format=format) thumbnail["*".join(str(i) for i in size)] = file_path self.mime_type = mime_type self.size = os.path.getsize(media_path) self.thumbnail = thumbnail self.url = f"http://127.0.0.1:8000/media/upload/{self.filename}" … -
How to have multiple email backends in Django?
I would like to have both SMTP backend and console backend, so that I can send an email via SMTP while also printing the generated email to console. In my settings.py I would like to have something like this: EMAIL_BACKEND = ["django.core.mail.backends.smtp.EmailBackend", "django.core.mail.backends.console.EmailBackend"] -
how to change the django connection string with postgres in each request in order to have a record of changes
Good afternoon, I have a trigger in my database that records every change, inclusion or deletion in the tables, but instead of using the user ID connected to Postgres, I would like to pass the user ID of my application, as it is an application SASS, I will have "a user" for the database, and "n" for the application. Is there any way to pass this user to my connection? where can I retrieve it in the trigger by executing select * from pg_stat_activity? I know the solution may seem inelegant, but it provides a lot of reliability when auditing data in the database I'm using: Django 4.2 DRF 3.14.0 Postgres 16.1 I tried to change the DATABASE parameters of settings.py, before the connection and I even managed to change the application_name, but when two users execute their requests "at the same time", there is a conflict and the two connections have the same value in the application_name. -
raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model
raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'book.CustomUser' that has not been installed raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'book.CustomUser' that has not been installed -
Django rest social auth and simple-jwt: NoReverseMatch at /api/login/social/jwt-pair/
I was following the documentation on drf social auth https://github.com/st4lk/django-rest-social-auth/tree/master I've encountered an issue while working with Django-Rest-Social-Auth and Simple-JWT. The error message is as follows: NoReverseMatch at /api/login/social/jwt-pair/facebook/ 'http' is not a registered namespace I've registered my path in the root urls.py (located in the config folder) as follows: path("api/login/", include("rest_social_auth.urls_jwt_pair")) Despite referring to the documentation, I'm unable to resolve this error. If anyone has encountered a similar issue or has insights into what might be causing this problem. Could someone kindly assist? -
Issues with Database Router Configuration in Django for Handling Multiple Databases
I am working on a Django application that utilizes two databases: Primary Database: This is set as the default database and is primarily used for read-only operations, such as querying analytics data. It does not handle authentication or any write operations. Secondary Database (sqlserver_db): This database is used for write operations, including migrations and authentication-related tasks. I am encountering difficulties in configuring the database router in my settings.py to properly direct read and write operations to the appropriate database. Below is my current setup: I am struggling to set the database router in my settings.py file below is what I have done in settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.oracle', 'NAME': 'AAAA', 'USER': 'AAAA', 'PASSWORD': 'AAAA', 'HOST': 'AAAA', 'PORT': 'AAAA', 'OPTIONS': { 'threaded': True, }, }, 'sqlserver_db': { 'ENGINE': 'mssql', 'NAME': 'AAAA', 'USER': 'AAAA', 'PASSWORD': 'AAAAA', 'HOST': 'AAAAA', 'PORT': '', 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server', }, } } DATABASE_ROUTERS = ['MyApp.routers.AuthRouter'] and there in routers.py : class AuthRouter: """ A router to control all database operations on models in the auth and contenttypes applications. """ route_app_labels = {"auth", "contenttypes"} def db_for_read(self, model, **hints): """ Attempts to read auth and contenttypes models go to auth_db. """ … -
implement a search bar for searching company name in django
im very new to web development. Im not really familiar with django. I got alot of this code from chatgpt. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Stockipy</title> {% load static %} <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css"> <script> $(document).ready(function() { // Assuming you've set an ID for the input field, replace 'id_company_name' with the actual ID $('COMPANY_NAME').select2(); }); </script> <script type="text/javascript" src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js"></script> </head> <body> <h1>Stock Alert</h1> <form method = "post"> {% csrf_token %} <label for="{{ form.COMPANY_NAME.id_for_label }}">Enter Company Name:</label> {{ form.COMPANY_NAME }} <br> <label for="{{ form.PERCENTAGE_DIFF.id_for_label }}">Enter Percentage Difference:</label> {{ form.PERCENTAGE_DIFF }} <br><br> <input type="submit" value="Submit"> </form> this is the html for the page def company_autocomplete(request): term = request.GET.get('term', None) if term: # Make a request to Alpha Vantage API to get matching company names params = { "function": "SYMBOL_SEARCH", "keywords": term, "apikey": ALPHAVANTAGE_API, } response = requests.get(STOCK_ENDPOINT, params=params) data = response.json().get("bestMatches", []) # Extract company names from the API response company_names = [result["2. name"] for result in data] return JsonResponse(company_names, safe=False) return JsonResponse([], safe=False) this is the function im using in view.py. i got it from chatgpt. output image when i run this website, the Company Name text field shows up small as … -
Dj rest auth and allauth returning wrong email format
I'm building an API using DJ rest auth and allauth for registration and login. I customized the email format for registration using custom adapters. Whenever I test it out in localhost it returns the desired email format which is: Dear TestUser1, Welcome to Ekopages, your gateway to sustainable education! We're thrilled to have you join our community. To get started on your journey towards a greener future, please click the link below to confirm your email address: https://ekopages.com/registration/account-confirm-email/NTE:1rUpCQ:qimz8K0QFUD5ZM8WbMlmcBqq3HSzNp0vNSziMaJRV44/ Once confirmed, you'll have full access to ekopages.com, where learning meets sustainability. Thank you for choosing Ekopages. Let's embark on this educational adventure together! Green regards, The EkoPages Team. ekopages.com after I deploy it though it just returns a format that i didnt add Hello from ! Dear testuser, Welcome to Ekopages, your gateway to sustainable education! We're thrilled to have you join our community. To get started on your journey towards a greener future, please click the link below to confirm your email address: https://ekopages.com/registration/account-confirm-email/NjI:1rWQ5A:ZKz5BArUgGzhT8tP8KKIuV62vGdVzBQ3blPHALsxWAE/ Once confirmed, you'll have full access to ekopages.com, where learning meets sustainability. Thank you for using ! I customized the registration and adapters too so I dont know where the hello from! is coming from #models.py … -
create and send a XLSX file with Django
I need to create and send an XLSX file in Django. The problem is always I'm sending the data, the file can't be opened. I tried with openpyxl and xlsxwriter and nothing... The result is the same, or a file of 0 OR 3 bytes than can't be opened...} There is a way to made it? -
Flask or Django for a python program that process and present transmitted data?
I'm currently working on a python desktop program with the purpose of extracting data from a device, particularly a sensor and hopefully wirelessly, to process and present it on the program as a tool for an investigation group. I'm considering on using CSS, HTML, and JS fro the front-end (if that's recommendable) and Python for the back-end. I'm curious to know if there any framework necessary for its development. Any advice? From what I have found, Flask and Django are good options but I'm not sure which is more applicable. They say Django is for more complex applications while Flask is for more simpler ones. My program is designed as a desktop app that can primarily work on Windows and will have a less busy UI, so I'm conflicted on which can suit better. -
I am running webODM after customizing some code that uses opencv library, however after restarting the dockerfile I get an error
I am customizing the WebODM and added my own plugin which includes opencv, matplotlib libraries. I am running the webODM as a docker file so after building the images to register the plugin I get: WARNING Failed to instantiate plugin diagnostic: No module named 'cv2' If I comment the import cv2 I in-turn get No module named 'matplotlib'. But in the environment I am running the django app, I can safely import cv2 in the python shell without issues. I suspect the issue is the dockerfile is sort of using some other python environment that causes it not to recognize cv2. How can I resolve this issue? -
Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment .how to solov
when i runserver give. ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? it is coming.and when i want to see the pip version #(venv) F:\pmis\pmis>pip --version Traceback (most recent call last): File "C:\Users\HP\AppData\Local\Programs\Python\Python310\lib\runpy.py", line 196, in _run_module_as_main return _run_code(code, main_globals, None, File "C:\Users\HP\AppData\Local\Programs\Python\Python310\lib\runpy.py", line 86, in run_code exec(code, run_globals) File "F:\pmis\pmis\venv\Scripts\pip.exe_main.py", line 4, in File "F:\pmis\pmis\venv\lib\site-packages\pip_internal\cli\main.py", line 9, in from pip._internal.cli.autocompletion import autocomplete File "F:\pmis\pmis\venv\lib\site-packages\pip_internal\cli\autocompletion.py", line 10, in from pip._internal.cli.main_parser import create_main_parser File "F:\pmis\pmis\venv\lib\site-packages\pip_internal\cli\main_parser.py", line 8, in from pip._internal.cli import cmdoptions File "F:\pmis\pmis\venv\lib\site-packages\pip_internal\cli\cmdoptions.py", line 23, in from pip._internal.cli.parser import ConfigOptionParser File "F:\pmis\pmis\venv\lib\site-packages\pip_internal\cli\parser.py", line 12, in from pip._internal.configuration import Configuration, ConfigurationError File "F:\pmis\pmis\venv\lib\site-packages\pip_internal\configuration.py", line 20, in from pip._internal.exceptions import ( File "F:\pmis\pmis\venv\lib\site-packages\pip_internal\exceptions.py", line 13, in from pip._vendor.requests.models import Request, Response File "F:\pmis\pmis\venv\lib\site-packages\pip_vendor\requests\models.py", line 20, in from pip._vendor.urllib3.util import parse_url ImportError: cannot import name 'parse_url' from 'pip._vendor.urllib3.util' (unknown location) ## it is showing -
Make link to foreign key object in admin screen
I have class like this which has the ForeignKey class MyLog(SafeDeleteModel): user = models.ForeignKey(CustomUser,on_delete=models.CASCADE) then I is listed user of MyLog in admin page. class MyLogAdmin(admin.ModelAdmin): list_display = ["id","user"] class UserAdmin(admin.ModelAdmin): list_display = ["id","username"] Now I want to make link in user of MyLogAdmin page to UserAdmin, Is it possible? I think some framework(such as php symfony) administrator system does this automatically. However is it possible to do this by django admin? -
Django csrf verification failed despite all tokens being present
I have a django website with forms. It works fine in debug mode on localhost but when a form is posted on a real server I get an csrf verification failed error. The form contains a csrf middleware token generated by {%csrf_token%} and the csrf token from the cookie is also sent with the request. The form is sent from subdomain.example.com/path to the same address. How can I fix this error?