Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
dj-rest-auth with JWT (problem with login functionality)
I have problem with login functionality, when the first time I log in it returns csrf_token, access_token and refresh_token . and it works fine till the expiration time. I know when the access token is expired I should get new one through refresh token but it should also work when I directly use the login route and giving username and password but I get 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" } ] } and when I see the cookies part the previous values are still there shouldn't they be vanished? I think the problem origins from here. when i manually delete them it works fine. and even when the refresh token expires I get the same error, how does it work? -
Using Django Debug Toolbar With DRF, Simple JWT Auth
django-debug-toolbar needs its output to be html, but i am using apis with jwt authentication (djangorestframework-simplejwt). So i am unable to use debug toolbar. I have all the settings of IPs, Middlewares everything correct as per documentation. All my APIs have Authentication and Authorization. All my libraries, modules are in latest versions. I have tried these methods Using django spectacular and creating an Swagger Documentation for my APIs, but it is not generating correct documentation (my apis work on many models, so unable to generate correct schema), Many Schemas are missing and also i dont know why extend_schema is not working. Used django-debug-panel by changing the errors with views.py, urls.py, middleware.py in django-debug-panel and also installed the chrome extension but i dont understand how to use it. Used django-silk but i want to use debug toolbar. Is there anyway i can use django debug toolbar somehow? I want to try again with any new ideas or changing anything in those methods i mentioned -
At least one element of a list and not all element of a list must match for a many to many relationship query in django
Here i have a list of place and tags for a reservation : And i would like a query where at least one of the list of places and at least one of the tags need to match the query slot, and not all places and not all tags need to match for the slot reservation. here is my solution : tags = Tag.objects.filter(name__in=tags) print("tags", tags) places = PartnerPlace.objects.filter(zip_code__in=cps) print("places", places) #slots is a queryset slots = Slot.objects.filter() for place in places: for tag in tags: slots = slots | Slot.objects.filter( tag=tag, place=place, ) It works but i think it's not elegant nor optimal if anyone have a better solution. Regards -
Django for loop not working in HTML in Django 4.2
HELP: There is some issue with for loop in my code. I cannot find the problem. This problem is not displaying data from backend. Can you help me with it? Whole code and process is given below. Models: from django.db import models class ImageGallery(models.Model): Title=models.CharField(max_length=1000, blank=True, null=True) Image=models.ImageField(upload_to='uploaded/photography') Description=models.CharField(max_length=1000, blank=True, null=True) Company=models.CharField(max_length=1000, blank=True, null=True) Admin: from django.contrib import admin from .models import * admin.site.register(ImageGallery) Views: # Galaries wala page def gallery_all(request): img_all = ImageGallery.objects.all() return render(request, 'gallery-all.html',{ 'img_all':img_all, }) HTML: <!-- Main --> <div id="main"> {% for imgraphy in img_all %} <!-- Each Image in gallery --> <article class="thumb"> Test Text <a href="{{imgraphy.Image.url}}" class="image"><img src="{{imgraphy.Image.url}}" alt="" /></a> <h2>{{imgraphy.Title}}</h2> <p>{{imgraphy.description}}</p> </article><!-- Each Image in gallery ends--> {% endfor %} </div> Django Admin: (Image showing data is entered) As you can see, data entered from backend is showing in the admin page but as shown below, there is blank space, why isn't data passing? Please help! Image and text not showing inside loop: -
Razorpay Integration in Django Project payment is not getting completed
I am integrating razorpay in django project. I am creating order through OrderPostApi. This is creating my order and my order_is getting saved in database. But when I call the payment_page view with order id generated in browser I am getting the pay button and when I click on that and after filling details(razorpay test cards for testing), my payment is not getting confirmed. It is showing "Your payment is being processed" for hours. And I am unable to generate the razorpay_payment_id and razorpay_signature in my database. I want when I make the payment, my payment should be completed and I will be able to get the razorpay_payment_id and razorpay_signature in my database. This is what I have done. OrderPostApi: class OrderPostApi(APIView): permission_classes = [AllowAny] Serializer = OrderSerializer def post(self, request, format=None): serializer = self.Serializer(data=request.data) if serializer.is_valid(): #save the order order = serializer.save() #create razorpay client client = razorpay.Client(auth=(settings.RAZORPAY_KEY_ID, settings.RAZORPAY_KEY_SECRET)) #create razorpay order razorpay_order = client.order.create({ 'amount': int(order.total_amount * 100), #amount in paise 'currency':'INR', 'payment_capture':'1' }) #update order with razorpay details order.razorpay_order_id = razorpay_order['id'] order.save() response_data= serializer.data response_data['razorpay_order_id'] = razorpay_order['id'] return Response(response_data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) OrderPaymentStatusApi: class OrderPaymentStatusApi(APIView): permission_classes= [AllowAny] def post(self, request, format=None): data = request.data #verify the … -
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb8 in position 57: invalid start byte ERROR when using Django and Postgresql
Hi I'm a newbie developer trying to make a webpage with django and postgresql db. I made a project and app and connected with settings.py to postgresql db. When I run python manage.py makemigrations, this error UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb8 in position 57: invalid start byte keeps popping up and I cannot go further into developing my project. psql is running well and psycopg2 is installed into my venv psql version 16 PLEASE HELP!! Check UTF8 encoding in postgresql db. Re-made by db with direct utf8 encoding to my db. Even made new project but still the same problem appears. It does not happen when I use built in sqlite3. -
Automate Deployment to GitHub Pages with Django Collectstatic [GitHub Actions Beginner]
I have two workflows for GitHub Actions. One has the task of deploying the static assets of the prod branch, while the other one has the task of running the Django collectstatic command. I want to merge both processes for the automatic deployment of new static elements, so I don't have to run collectstatic each time before pushing changes. The problem is that I don't have any idea how. Workflow for deploying static assets # Simple workflow for deploying static content to GitHub Pages name: Deploy static content to Pages on: # Runs on pushes targeting the default branch push: branches: ["prod"] pull_request: branches: ["prod"] # Allows you to run this workflow manually from the Actions tab workflow_dispatch: # Sets permissions of the GITHUB_TOKEN to allow deployment to GitHub Pages permissions: contents: read pages: write id-token: write # Allow only one concurrent deployment, skipping runs queued between the run in-progress and latest queued. # However, do NOT cancel in-progress runs as we want to allow these production deployments to complete. concurrency: group: "pages" cancel-in-progress: false jobs: # Single deploy job since we're just deploying deploy: environment: name: github-pages url: ${{ steps.deployment.outputs.page_url }} runs-on: ubuntu-latest steps: - name: Checkout uses: actions/checkout@v4 … -
Can someone check what is wrong with my code in Django?
So, I just made a CRUD in Django and now I want to test it and the Create and Delete test is working with these commands in cmd: CREATE curl -X POST http://localhost:8000/user/ -H "Content-Type: application/json" -d "{"username": "john_doe", "email": "john@example.com", "first_name": "John", "last_name": "Doe"}" DELETE curl -X DELETE http://localhost:8000/user/john_doe/ But the problem is when I try these: GET curl -X GET http://localhost:8000/user/john_doe/ PUT curl -X PUT http://localhost:8000/user/john_doe/ -H "Content-Type: application/json" -d "{"email": "john.new@example.com"}" I get a huge error. So firstly this is my views.py code: import json import pymongo from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt client = pymongo.MongoClient('mongodb://localhost:27017/') database = client['PoseTrack_Database'] users = database['users'] @csrf_exempt def create_user(request): if request.method == 'POST': user_data = json.loads(request.body) users.insert_one(user_data) return JsonResponse({'status': 'success', 'message': 'User created successfully!'}, status=201) @csrf_exempt def delete_user(request, username): if request.method == 'DELETE': users.delete_one({'username': username}) return JsonResponse({'status': 'success', 'message': 'User deleted successfully!'}, status=200) @csrf_exempt def view_user(request, username): if request.method == 'GET': data = users.find_one({'username': username}) return JsonResponse(data) @csrf_exempt def update_user(request, username): if request.method == 'PUT': new_data = json.loads(request.body) users.update_one(username, {'$set': new_data}) And this is my urls.py: from django.urls import path from . import views urlpatterns = [ path('user/', views.create_user), path('user/<username>/', views.delete_user), path('user/<username>/', views.view_user), path('user/<username>/', views.update_user), ] So I tried … -
How to get Django's makemessages to use existing app translations instead of duplicating them?
How do I get makemessages to ignore already-translated strings? In Django 5, I am running ./manage.py makemessages -l fr I have also copied templates/registration/registration_form.html from the "registration" app (django-registration-redux), so that I can modify it to extend the base.html from my project. Now, every translated string in my copy of registration_form.html is making its way into my locale/fr/LC_MESSAGES/django.po file for translation. However, those strings are already translated in the app directory. The docs says: [Django] looks for and uses if it exists a locale directory in each of the installed apps listed in INSTALLED_APPS That is a correct and fine behavior. The translations are fine. So, I don't want all those strings in my file, looking like they need to be translated again. I tried each of the following: ./manage.py makemessages -l fr -i registration/locale ./manage.py makemessages -l fr -i .venv/lib/python3.11/site-packages/registration/locale/ to no effect. -
PostgresSQL Select Statement Optimisation
Please see below a PostgreSQL SELECT statement. This presently returns around 300k rows, which is the grouped result of several million underlying rows. The dataset is only going to get larger. Using the ANALYSE EXPLAIN function the cost of this select is 111847 units. This select statement is being used in a Django ORM query set model. So the results are queried and mapped into an object. Due to the time taken for the SELECT to complete my Django application is timing out. The underlying data is made of up daily times series data, but I don't need the whole history. I am using the dataset for current day, MTD, QTD, YTD, ITD grouped values. How can I optimise this? I have been investigating indexing but am struggling to apply here, and so am not using any indexes. SELECT exposures_data.position_date, exposures_data.enfusion_id, exposures_data.book_id, exposures_data.base_lmv, book_tags.book, book_tags.portfolio, book_tags.analyst, pnl_data.base_daily_pnl, disasters_data.disaster_5_pnl FROM ( SELECT daily_exposures_holding_scenario.enfusion_id, daily_exposures_holding_scenario.position_date, daily_exposures_holding_scenario.book_id, sum(daily_exposures_holding_scenario.base_lmv) AS base_lmv FROM daily_exposures_holding_scenario GROUP BY daily_exposures_holding_scenario.position_date, daily_exposures_holding_scenario.enfusion_id, daily_exposures_holding_scenario.book_id) exposures_data LEFT JOIN book_tags ON exposures_data.book_id = book_tags.book_id FULL JOIN ( SELECT gl_daily_pnl.position_date, gl_daily_pnl.enfusion_id, gl_daily_pnl.book_id, sum(gl_daily_pnl.palliser_base_pnl) AS base_daily_pnl FROM gl_daily_pnl GROUP BY gl_daily_pnl.position_date, gl_daily_pnl.enfusion_id, gl_daily_pnl.book_id) pnl_data ON exposures_data.position_date = pnl_data.position_date AND exposures_data.enfusion_id::text = pnl_data.enfusion_id::text AND exposures_data.book_id … -
Configuring two different django-cookie-cutter generated projects to run on the same server
How can i run two different django-cookie-cutter generated projects on the same server. The projects are generated using Docker. I guess we should change the ports to avoid collisons. But as there are so many configuration files any help is appreciated. -
Access to fetch at *** from origin *** has been blocked by CORS policy: No 'Access-Control-Allow-Origin' - Microsoft ADFS with Django
I am trying to integrate Auth ADFS with Django App and Angular and I keep getting CORS error. I tried everything but nothing seems to be working. Access to XMLHttpRequest at 'https://login.microsoftonline.com/{your-tenant-id}/oauth2/v2.0/authorize?client_id={your-client-id}&response_type=token&redirect_uri={your-redirect-uri}=openid' (redirected from 'http://localhost:8080/api/base/login/') from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. My setting.py ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'base_app', 'django_crontab', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'corsheaders', 'customer_account', 'upload_data', 'project', 'django_auth_adfs', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'corsheaders.middleware.CorsPostCsrfMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django_auth_adfs.middleware.LoginRequiredMiddleware', ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'django_auth_adfs.rest_framework.AdfsAccessTokenAuthentication', 'rest_framework.authentication.TokenAuthentication', ), # 'DEFAULT_PERMISSION_CLASSES': ( # 'rest_framework.permissions.IsAdminUser' # ), 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer', ), # 'EXCEPTION_HANDLER': 'rest_framework.views.exception_handler' 'EXCEPTION_HANDLER': 'utils.exceptionhandler.custom_exception_handler' } CORS_ALLOW_HEADERS = default_headers + ( 'Access-Control-Allow-Origin', ) CORS_ALLOW_METHODS = [ 'GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS', ] CORS_ORIGIN_ALLOW_ALL = True ...... AUTH_ADFS = { 'AUDIENCE': CLIENT_ID, 'CLIENT_ID': CLIENT_ID, 'CLIENT_SECRET': CLIENT_SECRET, 'CLAIM_MAPPING': { # 'first_name': 'given_name', # 'last_name': 'family_name', 'email': 'upn', }, 'GROUPS_CLAIM': 'roles', 'MIRROR_GROUPS': True, 'USERNAME_CLAIM': 'upn', 'TENANT_ID': TENANT_ID, 'RELYING_PARTY_ID': CLIENT_ID, } Django API: @api_view(['GET']) def loginAPI(request): return JsonResponse({"message": "Login Page Successful"}) Angular Function: export class LoginPageComponent implements OnInit { private apiUrl = … -
How to remove all clear Django_migrations table WITHOUT losing out on any data in PROD?
Very mainstream problem :- I've a production database in postgres that's connected with my django projects which has multiple apps. I've 2 aspects to look at :- 2.1. I need to delete the migrations folder and get rid of actually 100's of migrations files in the apps. 2.2. I need to delete the migrations that django creates in the database as well in the django_migrations table. I want to make sure that Production data is not lost in any case! Finally I should have only 1 migration file or 2 that 0001/2_initial.py that's created by Django AND in the django_migrations table as well I need to make sure that all older migrations are deleted and it too has the newer initial ones created by django. I tried to delete all migrations folder and delete the django_migration table and then i ran python manage.py makemigrations python manage.py migrate but it gave me error saying that 'X' table already exists! luckily I had the dump and restored the data. -
Keep getting error while uploading Django project in vercel
while i am deploying my Django project using vercel i am keep getting this error Error: No Output Directory named "staticfiles_build" found after the Build completed. You can configure the Output Directory in your Project Settings I tried many things to resolve the error but nothing is working. This is my setting.py code # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/5.0/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles_build', 'static') i wanted to deploy my project online with the help of Versel but i am keep getting the error -
while making a change in a price ecommerce app by selecting the different size i get error in unsupported operand type,please resolve this problem
unsupported operand type(s) for +: 'int' and 'str' Internal Server Error: /product/t-shirts/ Traceback (most recent call last): File "C:\Python311\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Python311\Lib\site-packages\django\core\handlers\base.py", line 204, in _get_response self.check_response(response, callback) File "C:\Python311\Lib\site-packages\django\core\handlers\base.py", line 332, in check_response raise ValueError( ValueError: The view products.views.get_product didn't return an HttpResponse object. It returned None instead. [20/Jul/2024 12:48:11] "GET /product/t-shirts/?size=XL HTTP/1.1" 500 68697 unsupported operand type(s) for +: 'int' and 'str' Internal Server Error: /product/t-shirts/ Traceback (most recent call last): File "C:\Python311\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Python311\Lib\site-packages\django\core\handlers\base.py", line 204, in _get_response self.check_response(response, callback) File "C:\Python311\Lib\site-packages\django\core\handlers\base.py", line 332, in check_response raise ValueError(ValueError: The view products.views.get_product didn't return an HttpResponse object. It returned None instead. [20/Jul/2024 12:48:11] "GET /product/t-shirts/?size=XL HTTP/1.1" 500 68697 "this is my products.models page" from django.db import models from base.models import BaseModel from django.utils.text import slugify class Category(BaseModel): category_name=models.CharField(max_length=100) slug=models.SlugField(unique=True ,null=True , blank=True) category_image=models.ImageField(upload_to="categories") def save(self,*args,**kwargs): self.slug=slugify(self.category_name) super(Category,self).save(*args,**kwargs) def __str__(self) ->str: return self.category_name class ColorVariant(BaseModel): color_name= models.CharField(max_length=100) price= models.CharField(max_length=100) def __str__(self) ->str: return self.color_name class SizeVariant(BaseModel): size_name= models.CharField(max_length=100) price= models.CharField(max_length=100) def __str__(self) ->str: return self.size_name class Product(BaseModel): product_name=models.CharField(max_length=100) slug=models.SlugField(unique=True ,null=True , blank=True) categorys=models.ForeignKey(Category, on_delete=models.CASCADE,related_name="products",blank=False, null=True) price=models.IntegerField() products_description=models.TextField() color_variant=models.ManyToManyField(ColorVariant, blank=True) size_variant=models.ManyToManyField(SizeVariant, blank=True) def save(self,*args,**kwargs): self.slug=slugify(self.product_name) … -
SSL handshake issue
I have a code that sends api request to an api endpoint, and prints data. It works well in my local machine. But when I deploy it to my ec2, it stucks after sending request to api endpoint. My ec2 is api backend service, its front end is hosted in S3 as a static website. https : // mydomain.com navigates to S3 and linked with my angular frontend. https : // backend.mydomain.com is linked with my backend django EC2 api. which works fine, there is no https connection problem. Only problem is that I cannot send api request inside my ec2 django(which i can send in my local django dev without problem). Here is related code: import requests tcmb_api_key = 'xxxxxxxxx' headers = {'key':tcmb_api_key} url = 'https://evds2.tcmb.gov.tr/service/evds/series=TP.DK.EUR.A-TP.DK.EUR.S&startDate=19-07-2024&endDate=19-07-2024&type=json' try: response = requests.get(url, headers=headers, timeout=10) response.raise_for_status() # Check for HTTP errors data = response.json() print(data) except Exception as e: print('General error:', str(e)) And when executed, it stucks for some time (it can wait for minutes if there is no timeout limit), and then error: (venv) ubuntu@ip-172-31-27-16:~/transfertakip$ python3.11 ~/transfertakip/tcmb.py tcmb_api_key: jdtd2LAgBH headers: {'key': 'jdtd2LAgBH'} url: https://evds2.tcmb.gov.tr/service/evds/series=TP.DK.EUR.A-TP.DK.EUR.S&startDate=19-07-2024&endDate=19-07-2024&type=json Timeout error: HTTPSConnectionPool(host='evds2.tcmb.gov.tr', port=443): Read timed out. (read timeout=10) and here is detailed error: (venv) ubuntu@ip-172-31-27-16:~/transfertakip$ python3.11 … -
azure app service headache...cant' deploy app
`I'm not even sure where to begin. Been stuck on this for weeks. azure support no help tried deploying my webapp via the az webapp up --runtime PYTHON:3.9 --sku B1 --logs command as per the tutorial. did not work tried so many things and troubleshooting steps BUT then downgrading to python 3.9 seemed to fix it. closed the web app as just wanted to test deployment Lo and behold time to deploy again and even with 3.9 it's not working. Very similar error to before. Everything seems fine until you go to the site and it shows the default page. " Hey, Python developers! Your app service is up and running. Time to take the next step and deploy your code. " Please I am so stuck. I have no idea what to do. The logs more or less seem fine. The only exception is probably this line: `2024-07-20T05:59:44.2790642Z No framework detected; using default app from /opt/defaultsite Full log from docker.log file: 2024-07-20T05:55:00.3902714Z _____ 2024-07-20T05:55:00.3986130Z / _ \ __________ _________ ____ 2024-07-20T05:55:00.3986446Z / /_\ \\___ / | \_ __ \_/ __ \ 2024-07-20T05:55:00.3986509Z / | \/ /| | /| | \/\ ___/ 2024-07-20T05:55:00.3986564Z \____|__ /_____ \____/ |__| \___ > 2024-07-20T05:55:00.3986623Z … -
Saving an Apache Echart causes tainted canvas error
Saving the chart via the toolbox.feature.saveAsImage causes an error that says Tainted Canvas may not be exported. However, saving the image manually via right-clicking on the chart itself works just fine. I was wondering if there are any work-around on this? For deeper context, I've added images to the axis labels of the chart which may have caused it to become "tainted" I've already tried using html2canvas together with the on render event handler of apache echart and it still doesn't work. I've tried forwarding my port publicly and it also doesn't work -
In Django CI, githubactions try to another database for testing
This configuration refers to portfolio_db when running the server normally, and refers to test_portfolio_db during testing. DATABASES = { "default": { "ENGINE": "django.db.backends.mysql", "NAME": "portfolio_db", "USER": "python", "PASSWORD": "python123", "HOST": "localhost", "PORT": "3306", "TEST": {"NAME": "test_portfolio_db"}, } } However, when I actually run it through CI, for some reason it refers to portfolio_db. This is because githubactions assumes test_portfolio_db. Does anyone know why it refarences at portfolio_db and how to properly run the test? In addition, the test in the local environment passes https://github.com/duri0214/portfolio/actions/runs/10016990263/job/27690629902?pr=42 -
Django Bootstrap Carousel Responsive
I'm working on a multiple-item carousel that is responsive using Bootstrap with Django, the carousel needed a row for each slide and but I don't know how to check if the screen is large, medium or small. <div class="container py-4"> <div id="carouselCategory" class="carousel slide" data-bs-ride="carousel" aria-label="Category Carousel"> <div class="carousel-inner" role="listbox"> {% for kategori in kategoris %} {% if forloop.counter|add:"-1"|divisibleby:"6" %} <div class="carousel-item {% if forloop.counter == 1 %}active{% endif %}" style="transition: transform 2s ease"> <div class="row"> {% endif %} <div class="col-6 col-md-3 col-lg-2"> <!- item card --> <a class="card" style="width: 195px; text-decoration: none;" href="{% url 'dashboard:kategori' kategori.kategori %}" role="option" aria-selected="false"> <img src="{% static 'images/image1.jpeg' %}" alt="image-kategori" class="img-fluid rounded-top" style="height: 120px; border-radius: 5px 5px 0 0;"> <div class="card-body rounded-bottom" style="border: 1px solid grey; border-radius: 0 0 5px 5px;"> <h6 class="card-text fw-bold" style="text-align: center;">{{ kategori.kategori }}</h6> </div> </a> </div> {% if forloop.counter|divisibleby:"6" or forloop.counter == forloop.length %} </div> <button class="carousel-control-prev" type="button" data-bs-target="#carouselCategory" data-bs-slide="prev" style="background-color: #0f9ff4; color: #fff; border-radius: 50%; width: 40px; height: 40px; position: absolute; top: 50%; transform: translateY(-50%); z-index: 1000;"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="visually-hidden">Previous</span> </button> <button class="carousel-control-next" type="button" data-bs-target="#carouselCategory" data-bs-slide="next" style="background-color: #0f9ff4; color: #fff; border-radius: 50%; width: 40px; height: 40px; position: absolute; top: 50%; transform: translateY(-50%); z-index: 1000;"> <span class="carousel-control-next-icon" … -
HTML chat form is not stable - Django site
I have a django site which has a chatapp on it. the problem is the chat-content form in the chat app is not stay in the bottom of the chat page and user should send a lot of messages to come down the form in the app. How to set the "chat_content" input to stay fixed in the bottom of the chatapp page? HTML: <!--HTMLcode--> <div id="chat-right-bottom-box"> <form action="{% url 'chat_single' current_reciever.user.username %}" method="POST"> {% csrf_token %} <input type="text" name="chat_content" placeholder="Start a new message" id="chat-content" /> <input type="file" name="chat_file" id="chat-file" /> <input type="submit" name="chat_send_submit_btn" value="send" id="chat-send-submit-btn" /> </form> </div> </div> CSS: #chat-right-bottom-box { bottom: 0; left: 0; right: 0; height: auto; } #chat-right-bottom-box form { width: 95%; margin: 0 auto; margin-top: 10px; margin-bottom: 10px; } #chat-content { display: inline-block; width: 78%; border: 1px solid #1DA1F2; border-radius: 25px; padding: 8px 10px; } #chat-content:focus { outline: none; } #chat-send-submit-btn { display: inline-block; width: 17%; color: white; background-color: #1DA1F2; border: 1px solid #1DA1F2; font-weight: 700; border-radius: 25px; padding: 8px 10px; } #chat-send-submit-btn:hover { cursor: pointer; transition: 0.2s; background-color: #1991DA; border-color: #1991DA; } #chat-right-bottom-box { position: sticky; margin-bottom: 50px; } the form should work correctly. -
How can i create an event after a redirection with htmx?
If I have a code snippet like this:: response = HttpResponse(status=204) response["HX-Redirect"] = request.build_absolute_uri('/perfil/') response['HX-Trigger'] = 'useredited' return response How can I capture the 'useredited' event after the redirection occurs? When I try, the event is triggered before the redirection. Thanks for your help! -
Django is saving UUID without dashes in MySQL
I'm creating a Django application that uses UUID in some models. While i was using a MySQL database locally django was creating the UUID and saving it without dashes. Everything was working. Now i'm using a DB hosted in Hostinger. The problem is that the authentication is no longer working. The response i get if i try to access the API endpoints: "{"detail":"Usuário não encontrado","code":"user_not_found"}". Furthermore, in the remote DB django is saving the UUID with dashes. enter image description here I tried to create some users using the remote DB, the UUID are saved with dashes, and the django seems not to know how to deal with it: File "C:\Python311\Lib\uuid.py", line 178, in init raise ValueError('badly formed hexadecimal UUID string') ValueError: badly formed hexadecimal UUID string -
issue with post_detail view in django
hi there i am doing a project for my fullstack course but have come across an issue I am trying to make a detailed post view put once I added it to my URLs.py I get this error Reverse for 'post_detail' with arguments '('DEAD-BY-DAYLIGHT’S-MYTHIC-TOME-EXPLORES-YUI-KIMURA-AND-THE-SPIRIT',)' not found. 1 pattern(s) tried: ['(?P[-a-zA-Z0-9_]+)/\Z'] and it is saying this line is giving me that error <a href="{% url 'post_detail' post.slug %}" class="post-link black-text"> but when I delete this from my urls.py path('<slug:slug>/', views.post_detail, name='post_detail'), my page loads again how do I fix it i do not even know how to explain what ive tried but i have tried everything i cant think of ive even tried deleting the post that is in the error but it just gives me another post in it -
Banner is not displaying at the top and css is not working
I have html like following, in my Django project <!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Index Page</title> <link rel="icon" type="image/png" sizes="16x16" href="{% static 'favicon.png' %}"> <link rel="stylesheet" href="{% static 'style.css' %}"> </head> <body> <div id="error-banner" class="error-banner" style="display: none;"></div> <header> <div class="header-content"> <!--some header contents--> </div> </header> <div> <!--some other divs--> </div> <script> function showErrorBanner(message) { var banner = document.getElementById('error-banner'); banner.textContent = message; banner.style.display = 'block'; setTimeout(function() { banner.style.display = 'none'; }, 10000); // 10 seconds } {% if error_message %} showErrorBanner("{{ error_message }}"); {% endif %} </script> </body> </html> My signin_view is like following: def signin_view(request): if request.method == 'POST': form = AuthenticationForm(request, data=request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('login') # Change 'home' to the name of your homepage URL pattern else: error_message = "Invalid username or password." else: error_message = "Invalid form submission." else: form = AuthenticationForm() error_message = None return render(request, 'login.html', {'login_form': form, 'error_message': error_message}) and entire style.css is like following body { font-family: Arial, sans-serif; margin: 0; padding: 0; background-image: url('resources/background.jpg'); background-size: cover; background-position: center; background-repeat: no-repeat; background-attachment: fixed; display: flex; …