Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Preventing Data Tampering in HTTPS Requests: Safeguarding User-Initiated Donations
Could a Man-in-the-Middle (MITM) attack compromise the integrity of user-initiated transactions over HTTPS? Specifically, if a user selects an amount to donate on a website, is it possible for a hacker to intercept and modify the donation amount?If yes, what strategies can be implemented to safeguard against unauthorized alterations and ensure the security of transactions conducted over HTTPS? note: I'm using django in development. -
I get the admin id but when im logged in as a user i still get admin id when i try to fetch the user id
i created a function in my views.py file which lets you see different dashboards according to the role of the email which is logging in now when im trying to fetch the id of user im getting the id of the user which was loggod on the server before what chnages should i be doing for this.I tried clearing the session during logout but it's still not working and the code is fetching me the id of previous logged in admin. def determine_role(request): user = request.user # Get the authenticated user object role = user.role # Access the role attribute # Now you can use the role to perform further actions if role == 'admin': # If the user is an admin, do something return render(request, 'loginapp/admin_dashboard.html') elif role == 'user': # If the user is a regular user, do something else return render(request, 'loginapp/user_dashboard.html') -
Trouble Connecting Django Application to PostgreSQL Database Running in Docker Container
I'm currently working on a Django project where I'm using a virtual environment (venv) to run Django locally on my machine (Windows). Additionally, I have a PostgreSQL database running in a Docker container. I'm encountering issues trying to establish a connection between my Django application and the PostgreSQL database. Whenever I attempt to run python manage.py makemigrations, I get the following error: RuntimeWarning: Got an error checking a consistent migration history performed for database connection 'default': connection to server at "host.docker.internal" (141.31.78.207), port 5432 failed: Connection timed out (0x0000274C/10060) Is the server running on that host and accepting TCP/IP connections? warnings.warn( No changes detected Here are the relevant portions of my Django settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'SilverSurfer', 'USER': 'postgres', 'PASSWORD': "root", 'HOST': "host.docker.internal", 'PORT': '5432', } } And here's my Docker Compose file: version: "3.9" services: db: image: postgres:15.0 environment: POSTGRES_DB: SilverSurfer POSTGRES_USER: postgres POSTGRES_PASSWORD: root ports: - "5432:5432" volumes: - ./db.sql:/docker-entrypoint-initdb.d/db.sql It's worth noting that my Docker container for the database is running: CONTAINER ID IMAGE COMMAND CREATED STATUS 528ad4e3232f postgres:15.0 "docker-entrypoint.s…" 37 minutes ago Up 37 minutes PORTS NAMES 0.0.0.0:5432->5432/tcp 02_db-db-1 I've tried connecting to the PostgreSQL database using psql, but I receive … -
How to add field with its data from one model to another one in Django?
Django already has a User model, which has a username field; I also have a Profile model. What I want to achieve is to send the username from the User model along with the fields of the Profile model, So that I can access the username from the Profile model itself , as to the frontend I'm returning an object of the Profile model MODELS User= get_user_model() class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) id_user = models.IntegerField() department= models.CharField(max_length=50,blank=True) degree= models.CharField(max_length=20,blank=True) year= models.CharField(max_length=20,blank=True) bio = models.TextField(blank=True) profileimg= models.TextField(default=DEFAULT_IMAGE_DATA) def __str__(self): return self.user.username SERIALIZER class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields=['id','user', 'id_user', 'department', 'degree', 'year', 'bio','profileimg'] class ChatMsgSerializer(serializers.ModelSerializer): reciever_profile= ProfileSerializer(read_only=True) sender_profile= ProfileSerializer(read_only=True) class Meta: model = ChatMsg fields=['id','user', 'sender','sender_profile', 'reciever','reciever_profile', 'msg', 'is_read', 'date'] One Solution I though Was to make another fetch request from the frontend and make one more endpoint that returns the username , but idts it would work well when i need both sender and reciever username -
How to reuse a model crated for crate too many model in Django?
I have model in models.py in my app Django : class Personnel(models.Model): id = models.AutoField(primary_key=True) card_number = models.BigIntegerField() name = models.TextField(db_collation='C') family = models.TextField(db_collation='C') height = models.TextField(db_collation='C', blank=True, null=True) weight = models.FloatField(blank=True, null=True) job_type = models.BigIntegerField(db_column='Job_Type', blank=True, null=True) age = models.FloatField(db_column='age', blank=True, null=True) Superviser_score = models.FloatField(db_column='Superviser_score', blank=True, null=True) QC_score = models.FloatField(db_column='QC_score', blank=True, null=True) def __str__(self)-> str: return f'{self.card_number} - {self.family} - {self.name}' class Meta: managed = False db_table = 'personnel' And in admin.py: @admin.register(Personnel) class MyPersonelAdmin(admin.ModelAdmin): list_display = ['card_number','name','family','center','job_type'] How can I reuse personenel model for create too many model ? I try below code in models.py for crate another model but I get error: class SuperviserModel(Personnel): id=Personnel.id card_number = Personnel.card_number name = Personnel.name family = Personnel.family center = Personnel.center distance = Personnel.distance job_type = Personnel.job_type overtime = Personnel.overtime class Meta: managed = False db_table = 'personnel' Error: column personnel.personnel_ptr_id does not exist -
'Expected a value of type List<dynamic> but got one type _JsonMap'
The code below is displays my List<dynamic> casting method, yet when I preview my code, the info displayed is that 'Expected a value of type List<dynamic> but got one type _JsonMap'. My data is being retrieved from a django rest framework into a json format. I run server whenever I start the flutter app. // ignore_for_file: dead_code, prefer_const_constructors, prefer_const_literals_to_create_immutables, deprecated_member_use, avoid_print, non_constant_identifier_names import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; import 'dart:async'; Future<List<Data>> fetchData() async { var url = Uri.parse('http://127.0.0.1:8000/api/?format=json'); final response = await http.get(url); if (response.statusCode == 200) { // final jSon = "[${response.body}]"; List jsonResponse = (json.decode(response.body) as List<dynamic>); return jsonResponse.map((data) => Data.fromJson(data)).toList(); } else { throw Exception('Unexpected error occured!'); } } class Data { final int ID; final String visitor_name; final String visit_date; final String time_in; final String time_out; final String department; final String visitee_name; final String address; final String phone; final String purpose_of_visit; Data({required this.ID, required this.visitor_name, required this.visit_date, required this.time_in, required this.time_out, required this.department, required this.visitee_name, required this.address, required this.phone, required this.purpose_of_visit}); factory Data.fromJson(Map<String, dynamic> json) { return Data( ID: json['ID'], visitor_name: json['visitor_name'], visit_date: json['visit_date'], time_in: json['time_in'], time_out: json['time_out'], department: json['department'], visitee_name: json['visitee_name'], address: json['address'], phone: json['phone'], purpose_of_visit: json['purpose_of_visit'], ); } } class ViewRecord extends … -
Django: update one table based on another
I have two tables Table1 and Table2 with the same field hash_str. from django.db import models class Table1: data = JSONField(...) hash_str = CharField(...) class Table2: name = CharField(...) parsed = DateTimeField(...) hash_str = CharField(...) is_updated = BooleanField(...) # ... Sometimes i need to update Table2 instances based on Table1 instances with the same hash. But i want to use Table2.objects.bulk_update(...) for it. Because there is too much instances to update them one by one like this: # ... for t2_obj in Table2.objects.filter(is_updated=False): t1_obj = Table1.objects.get(hash_str=t2_obj.hash_str) t2_obj.name = t1_obj.data["name"] t2_obj.parsed = t1_obj.data["parsed"] t2_obj.is_updated = True t2_obj.save() # ... How can i do it properly? -
How to get realtime stdout from a celery task?
I have a Django project in which i'm running some background tasks with celery, one of my goal is to show real-time stdout of the running task so that the user can see the progress. the issue is that i get the stdout of the process only when it is finished executing (all is dumped at once). Views.py def run_script(request, file_type, file_id): run_features.delay(arguments) return Tasks.py @shared_task def run_features(arguments): process = subprocess.Popen(arguments, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) channel_layer = get_channel_layer() while True: output = process.stdout.readline() if output == '' and process.poll() is not None: break if output: print(output) async_to_sync(channel_layer.group_send)( 'output_group', { 'type': 'send_output', 'output': output.strip() } ) process.wait() return process.returncode Celery INFO -------------- celery@ritik v5.3.1 (emerald-rush) --- ***** ----- -- ******* ---- Linux-6.5.0-25-generic-x86_64-with-glibc2.35 2024-03-21 09:30:54 - *** --- * --- - ** ---------- [config] - ** ---------- .> app: Automation:0x7e2bb4073280 - ** ---------- .> transport: redis://localhost:6379/0 - ** ---------- .> results: disabled:// - *** --- * --- .> concurrency: 8 (prefork) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- -------------- [queues] .> celery exchange=celery(direct) key=celery Expectation - I get the stdout, line by line, while the task is running. Actual result - I … -
Invalid block tag on line 2: 'endblock'. Did you forget to register or load this tag?
{% extends "base.html" %} {% block title %} Home {% endblock %} {% block content %} {% endblock %} Seems correct to me, but it's showing this error. -
Update only specific fields in a models.Model vDjango
I have model in models.py: class SuperviserModel(models.Model): name = models.TextField(db_collation='C') family = models.TextField(db_collation='C') score = models.FloatField(db_column='score ', blank=True, null=True) # def __str__(self)-> str: return f' - {self.family} - {self.name}' class Meta: managed = False db_table = 'personnel' And in admin.py: @admin.register(SuperviserModel) class MySuperviserModelAdmin(admin.ModelAdmin): list_display = ['name','family','score'] sortable_by = ['name','family'] search_fields=['name', 'family'] I want when superviser user edit personnel just update score field, And cant update name and family field. How can I do? -
Image is not displayed/loaded in my django website which i deployed on Cpanel
details of my code, in my settings.py i have: BASE_DIR = Path(__file__).resolve().parent.parent STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') and this is how i tried to acces form the template: in very first page: % load static % to display image, <a class="navbar-brand" href="#"><img src="{% static 'images/main.png' %}" alt="imagetwo" width="100" height="50"></a> anyone who can help me please -
Having trouble configuring ssl for django apache2
I have two errors: 'AH00112: Warning: DocumentRoot [/etc/apache2/var/www/html] does not exist' while i runed this cmd: >>>> grep -r "DocumentRoot" /etc/apache2/ >>> /etc/apache2/sites-available/000-default.conf: DocumentRoot > var/www/html > >>> /etc/apache2/sites-available/amicom_com_vn.conf: DocumentRoot > /var/www/html > >>> /etc/apache2/sites-available/default-ssl.conf: DocumentRoot > /var/www/html when i run 'https://example.com' i see 'Apache2 Default Page' how can i fix this error, this is my config ssl <VirtualHost *:443> ServerAdmin webmaster@localhost ServerName example.com ServerAlias www.example.com DocumentRoot /var/www/html SSLEngine on SSLCertificateFile /etc/ssl/certs/ca-certificates.crt SSLCertificateKeyFile /etc/ssl/private/ssl-cert-snakeoil.key </VirtualHost> -
python exclude non accessible image with requests
i've written a really simple function with requests, wich with a giver url checks if it gets a response and if this response is an image. It actually works, but is crazy slow at times. i'm too inexperienced to understand why is that. How can i improve it or achieve the same thing in a better and faster way? def is_image_url(url): try: response = requests.get(url) status = response.status_code print(status) if response.status_code == 200: content_type = response.headers.get('content-type') print(content_type) if content_type.startswith('image'): return True return False except Exception as e: print(e) return False i'm using that function to exclude images who are not acessible, like images from instagram, facebook etc. i thoughtit could work fine because i actually need to check only 10 images that i get from google custom search api. for now i've excluded the function from the application, and tried do a similar thing with checking the image height or width to assure that it existed and was accessible without much success. -
Python Django dj-rest-auth AttributeError
I was trying the demo project ( https://dj-rest-auth.readthedocs.io/en/latest/demo.html ) and when I tried to login I got the error: Django 4.2.5 django-allauth 0.61.1 dj-rest-auth 5.0.2 PyJWT 2.8.0 Internal Server Error: /api/v1/social/google/login/finish/ Traceback (most recent call last): File "/Users/junu/Documents/venv/ratatouille_web/lib/python3.9/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/Users/junu/Documents/venv/ratatouille_web/lib/python3.9/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/junu/Documents/venv/ratatouille_web/lib/python3.9/site-packages/django/views/decorators/csrf.py", line 56, in wrapper_view return view_func(*args, **kwargs) File "/Users/junu/Documents/venv/ratatouille_web/lib/python3.9/site-packages/django/views/generic/base.py", line 104, in view return self.dispatch(request, *args, **kwargs) File "/Users/junu/Documents/venv/ratatouille_web/lib/python3.9/site-packages/django/utils/decorators.py", line 46, in _wrapper return bound_method(*args, **kwargs) File "/Users/junu/Documents/venv/ratatouille_web/lib/python3.9/site-packages/django/views/decorators/debug.py", line 92, in sensitive_post_parameters_wrapper return view(request, *args, **kwargs) File "/Users/junu/Documents/venv/ratatouille_web/lib/python3.9/site-packages/dj_rest_auth/views.py", line 48, in dispatch return super().dispatch(*args, **kwargs) File "/Users/junu/Documents/venv/ratatouille_web/lib/python3.9/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/Users/junu/Documents/venv/ratatouille_web/lib/python3.9/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/Users/junu/Documents/venv/ratatouille_web/lib/python3.9/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/Users/junu/Documents/venv/ratatouille_web/lib/python3.9/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "/Users/junu/Documents/venv/ratatouille_web/lib/python3.9/site-packages/dj_rest_auth/views.py", line 125, in post self.serializer.is_valid(raise_exception=True) File "/Users/junu/Documents/venv/ratatouille_web/lib/python3.9/site-packages/rest_framework/serializers.py", line 227, in is_valid self._validated_data = self.run_validation(self.initial_data) File "/Users/junu/Documents/venv/ratatouille_web/lib/python3.9/site-packages/rest_framework/serializers.py", line 429, in run_validation value = self.validate(value) File "/Users/junu/Documents/venv/ratatouille_web/lib/python3.9/site-packages/dj_rest_auth/registration/serializers.py", line 160, in validate login = self.get_social_login(adapter, app, social_token, token) File "/Users/junu/Documents/venv/ratatouille_web/lib/python3.9/site-packages/dj_rest_auth/registration/serializers.py", line 62, in get_social_login social_login = adapter.complete_login(request, app, token, response=response) File "/Users/junu/Documents/venv/ratatouille_web/lib/python3.9/site-packages/allauth/socialaccount/providers/google/views.py", line 82, in complete_login id_token = response.get("id_token") AttributeError: 'str' object has … -
I am running elastic search on 0.5-1 vCPU (1 shared core) GCP but the server is not able to handle how to fix this?
I am running Elasticsearch on 0.5-1 vCPU (1 shared core) with 1.7 GB of memory (GCP). When I start the elastic search service the server is crashed. How do we fix this issue? I am running Django with Postgres and Elasticsearch. -
Django NameError: name 'include' is not defined in urls.py
I'm encountering a NameError in my Django project's urls.py file. When I try to use the include () function to include URLs from another app, I get the following error: NameError: name 'include' is not defined Here's the relevant portion of my urls.py file: from django.contrib import admin from django.urls import include, path urlpatterns = [ path('admin/', admin.site.urls), path('hello/', include('hello.urls')) ] I've already imported include from django.urls, so I'm not sure why this error is occurring. Any insights on what might be causing this issue and how to resolve it would be greatly appreciated. Thank you! I attempted to include URLs from another Django app in my project's urls.py file using the include() function. I expected the include() function to work as intended and include the URLs from the specified app. However, when I tried to use the include() function, I encountered a NameError stating that 'include' is not defined, even though I had imported it from django.urls. -
WebSocket connection to 'ws://127.0.0.1:8000/ws/work/' failed:
I can't access the WebSocket while I follow this project : https://www.youtube.com/watch?v=SF1k_Twr9cg&t=2498s&ab_channel=CodeWithStein From 47:23 consumers.py import json from channels.generic.websocket import AsyncWebsocketConsumer from asgiref.sync import sync_to_async class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept async def disconnect(self): await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) routing.py from django.urls import path from . import consumers websocket_urlpatterns = [ path('ws/<str:room_name>/', consumers.ChatConsumer.as_asgi()), ] asgi.py import os from django.core.asgi import get_asgi_application from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter import room.routing os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'djangochat.settings') application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": AuthMiddlewareStack( URLRouter( room.routing.websocket_urlpatterns ) ) }) room.html {% block scripts %} {{ room.slug|json_script:"json-roomname" }} <script> const roomName = JSON.parse(document.getElementById("json-roomname").textContent); const chatSocket = new WebSocket( 'ws://' + window.location.host + '/ws/' + roomName + '/' ); chatSocket.onmessage = function (e) { console.log("onmessage"); } chatSocket.onclose = function (e) { console.log("onclose"); } </script> {% endblock %} -
type object ...... has no attribute 'replace'
I'm using Django 4.2 application this is my model: from django.db import models from django.utils.translation import gettext_lazy as _ class Category(models.Model): parent = models.ForeignKey('self', verbose_name=_('parent'), blank=True, null = True, on_delete=models.CASCADE) title = models.CharField(_('title'), max_length = 50) description = models.TextField(_('description'), blank=True) avatar = models.ImageField(_('avatar'), upload_to='categories/') enable = models.BooleanField(_('enable'), default = True) created_time = models.DateTimeField(_('created time'), auto_now_add = True) updated_time = models.DateTimeField(_('updated time'), auto_now=True) class Meta: db_table = 'categories' verbose_name = _('Category') verbose_name_plural = _('categories') when I run the server I get this error: type object 'Category' has no attribute 'replace' I think that it's because of the translation cause when I checked where 'replace' was I found this: def gettext(message): """ Translate the 'message' string. It uses the current thread to find the translation object to use. If no current translation is activated, the message will be run through the default translation object. """ global _default eol_message = message.replace("\r\n", "\n").replace("\r", "\n") if eol_message: _default = _default or translation(settings.LANGUAGE_CODE) translation_object = getattr(_active, "value", _default) result = translation_object.gettext(eol_message) else: # Return an empty value of the corresponding type if an empty message # is given, instead of metadata, which is the default gettext behavior. result = type(message)("") if isinstance(message, SafeData): return mark_safe(result) return … -
Django models field not getting generated in database
I am creating a basic Django project. I am using the default db sqlite3. I have created an app product inside my main folder. So, my folder structure is like this: -project -djangoproject -products -models.py -manage.py I am adding my new product model in models.py but when I am running python3 manage.py makemigrations I am checking my migration file. The model is getting created and there is an id field also in it but no other field of my product is coming in my migrations file. I also ran the command python3 manage.py migrations and checked my database. Only id field is present in the product table. I am not able to understand the cause of this problem. Here is the look at my migration file and models.py file: from django.db import models class Product(models.Model): name: models.CharField(max_length=200) price: models.FloatField() stock: models.IntegerField() image_url: models.CharField(max_length=2083) # Generated by Django 5.0.3 on 2024-03-21 04:46 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ('products', '0004_delete_offer_delete_product'), ] operations = [ migrations.CreateModel( name='Product', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ], ), ] Django version: 5 If anyone knows the reason then please comment or post your answer. It will be really … -
Configuring Alembic in Django Rest Framework with SQLAlchemy
I have a DRF project where I am using SQLAlchemy along with Django's built-in ORM. For configuring Alembic into my project I did this. Installed Alembic with pip install alembic Then I've run this command on my root project directory. alembic init alembic This command generated a folder called alembic and a file named alembic.ini in my root project directory. Inside that folder there are some files like (env.py, README, script.py.mako) and a folder named versions. Now, inside the alembic.ini file, I've added this line, sqlalchemy.url = sqlite3://db.sqlite3 This is how I configured. This is my models.py: from sqlalchemy import create_engine, Column, String, Integer, Float, ForeignKey from sqlalchemy.orm import declarative_base, sessionmaker, relationship from django.contrib.auth import models engine = create_engine('sqlite:///db.sqlite3') Base = declarative_base() class PlaceInfoModel(Base): __tablename__ = 'place_info' id = Column(Integer, primary_key=True, autoincrement=True) owner_id = Column(Integer,nullable=False) name = Column(String(60)) address = Column(String(300)) rating = Column(Float) type = Column(String(20)) image = Column(String) Base.metadata.create_all(engine) In my alembic/env.py I added these lines: from review.models import Base, PlaceInfoModel target_metadata = Base.metadata But, whenever I run this alembic revision --autogenerate -m "Created SQLAlchemy Model" I am getting this error. File "D:\SQLAlchemy Practice\env\Lib\site-packages\django\conf\__init__.py", line 69, in _setup raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not … -
Stripe doesn't work after deploying on Heroku by Django
*English is not my mother language,so if my English is not correct,please ignore. At Local, Stripe has worked well on Django. But after deploying Heroku, Stripe(subscription Service) doesn't work. When I click "Pay",everytime showed " Internet Error 500".I checked Heroku logs,but connect and service looks like okay. I've tried deployed again and again, but everytime the results are same. Showing "Internet Error 500". This is logs by Heroku logs --tail 2024-03-19T08:03:27.576123+00:00 heroku[router]: at=info method=POST path="/checkout/" host=nagoyameshi-marina-32890ff7fdd2.herokuapp.com request_id=40d9d9e5-8ebf-436f-9254-2e862dcada7e fwd="126.15.11.7" dyno=web.1 connect=2ms service=19ms status=500 bytes=459 protocol=https 2024-03-19T08:03:27.576163+00:00 app[web.1]: 10.1.20.255 - - [19/Mar/2024:17:03:27 +0900] "POST /checkout/ HTTP/1.1" 500 145 "https://nagoyameshi-marina-32890ff7fdd2.herokuapp.com/terms_of_service/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36" These are my settings.py and CheckoutView from views.py I deployed on Heroku. if "STRIPE_PUBLISHABLE_KEY" in os.environ and "STRIPE_API_KEY" in os.environ and "STRIPE_PRICE_ID" in os.environ: STRIPE_PUBLISHABLE_KEY = os.environ["STRIPE_PUBLISHABLE_KEY"] STRIPE_API_KEY = os.environ["STRIPE_API_KEY"] STRIPE_PRICE_ID = os.environ["STRIPE_PRICE_ID"] - CheckoutView stripe.api_key = settings.STRIPE_API_KEY class CheckoutView(LoginRequiredMixin,View): def post(self, request, *args, **kwargs): checkout_session =stripe.checkout.Session.create( line_items=[ { 'price':settings.STRIPE_PRICE_ID, 'quantity':1, }, ], payment_method_types=['card'], mode='subscription', success_url=request.build_absolute_uri(reverse_lazy("nagoyameshi:success")) + '?session_id={CHECKOUT_SESSION_ID}', cancel_url=request.build_absolute_uri(reverse_lazy("nagoyameshi:index")), ) print( checkout_session["id"] ) return redirect(checkout_session.url) checkout = CheckoutView.as_view() DB is " Heroku Postgres". -
Django and Keystrokes dynamics as authentication
How do i capture and use keystrokes dynamics as my second factor authentication in Django web application project? I have implemented the normal username and password authentication in Django and fails to know how i can use keystrokes to add it for authentication. -
Django ConnectionRefusedError [Errno 111] Connection refused facing issue how to solve it
I'm facing issue when send mail on django [Errno 111] Connection refused my setting.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' # Replace with your preferred backend EMAIL_HOSTS = 'smtp.gmail.com' # Replace with your email host EMAIL_PORT = 587 # Replace with your email port EMAIL_USE_TLS = config('EMAIL_USE_TLS', cast=bool) # Set to False if your email server doesn't use TLS EMAIL_HOST_USER = config('EMAIL_HOST_USER') # Replace with your email username EMAIL_HOST_PASSWORD = config('EMAIL_HOST_PASSWORD') # Replace with your email password view.py current_url = get_current_site(request) mail_subject = "Please activate your account." message = render_to_string('base/pass/account_verify.html',{ 'user':user, 'domain':current_url, 'uid':urlsafe_base64_encode(force_bytes(user.pk)), 'token':default_token_generator.make_token(user), }) to_email = email send_mail = EmailMessage(mail_subject, message, to=[to_email]) send_mail.send() i have check all mail setting.py but can't solve this error on local it's work but when i am production and host while it's not working and get this error -
Total counts not displaying in template:
the app im building requires asset management section which would display the total assets, total fixed, total onsite and total booked, however the blocks shows but the amounts does not. while debugging the print statement within the views prints to console and if i attempt to load the asset management html it displays but when including it into my base html the amounts does not display. My views: def asset_dashboard(request): total_assets_count = Asset.objects.count() onsite_assets_count = Asset.objects.filter(status='onsite').count() fixed_assets_count = Asset.objects.filter(status='fixed').count() booked_assets_count = Asset.objects.filter(status='booked').count() print("Total Assets Count:", total_assets_count) print("Onsite Assets Count:", onsite_assets_count) print("Fixed Assets Count:", fixed_assets_count) print("Booked Assets Count:", booked_assets_count) context = { 'total_assets_count': total_assets_count, 'onsite_assets_count': onsite_assets_count, 'fixed_assets_count': fixed_assets_count, 'booked_assets_count': booked_assets_count, } return render(request, 'asset_dashboard.html', context) My base.HTML: <!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>{% block title %}{% endblock %}</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous"> {% load static %} <link rel="stylesheet" href="{% static './css/main.css' %}"> <style> /* CSS to style the container */ .container { height: 200px; background-image: url('static/images/VOClogo.jpg'); background-size: contain; background-repeat: no-repeat; background-position: center; opacity: 0.2; color: white; font-size: 24px; text-align: center; padding-top: 10px; } </style> </head> <body> {% include 'navbar.html' %} <form class="d-flex" method="GET" action="{% url 'asset_search' %}"> <input class="form-control … -
Can I build a dynamic Web3 site using IPFS?
This is more of a general question. I would like to connect a dynamic site to a Web3 domain (.x) I have read that only static builds are possible using the IPFS protocol and Web3 platforms (such as Pinata, Fleek etc.). Just digging into Web3 development further. Appreciate any clarity, thoughts or pointers. And when I say dynamic, I mean full backend and frontend stack capabilities using frameworks such as Django.