Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I create a RESTful API using Python and a web framework like Flask or Django?
I'm looking to develop a RESTful API using Python, and I'm considering using web frameworks such as Flask or Django to facilitate the process. The primary goal is to expose a set of endpoints that allow clients to interact with my application over HTTP in a RESTful manner. -
How to deploy Django run with Docker compose to Cloud linux server cpanel use set app python?
I tried to deploy Django admin use Docker and Postgres Database to my cpanel use set app python but the project not run, can any body help with the process of how cam make this deployment? Also I could not able to install the Django site-packages use pip instal in venv. -
program gets stuck when sending email via gmail
I have the following python function: import smtplib, ssl port = 465 # For SSL password = "valid password" context = ssl.create_default_context() def sendEmail(to_email, subject, content): from_email = "valid_email@zaliczenie.pl" message = (f"Tresc zadania: {content}",) try: print("connecting") with smtplib.SMTP_SSL("smtp.gmail.com", port, context=context) as server: print("connected") server.login("tmp_email@gmail.com", password) print("logged") server.sendmail( to_addrs=to_email, from_addr=from_email, msg=message, ) print("sent") except Exception as e: print(e.message) And here are the logs: connecting connected logged So it connects, logs into google mail, but gets stuck when trying to send an email. What am I missing? I allowed the less safe applications and password is the one generated from google security 2FA tab (App passwords). -
Why am I getting a CSRF token missing error when the token is there?
I have a Vue app and I am making requests to a Django Rest Framework endpoint, well a few. It was working fine yesterday and I was able to submit and save content. Today I keep getting the same error CSRF Failed: CSRF token missing. But if I look in the dev tools I see this: |csrftoken|“wzWBo6N66F1HTp2To67We5GppNWfbXdm”| |sessionid|“1vq4vj73b1b6l80gt2ckba6zwxqj8wwu”| So how is it missing if it is right there? Second question: What is the use of this setting if no matter what it still gives you a CSRF error? CORS_ORIGIN_WHITELIST = (“localhost:8080”,“127.0.0.1:8080”) CSRF_TRUSTED_ORIGINS = [“http://localhost:8080”, “http://*.127.0.0.1”, “http://127.0.0.1:8080”,“http://192.168.1.44:8080”,] -
Django: rendering a model object as an image/icon
I have the following two Django models: class ProjectType(models.Model): name = models.CharField("Name", max_length=300, unique=True) class Project(models.Model): name = models.CharField("Name", max_length=300, unique=True) project = models.ForeignKey("ProjectType", on_delete=models.CASCADE) The ProjectType object would be things like: "research", "outreach", "administrative", etc. What I'd like to do is render ProjectType as a standardized icon (ex.: a little beaker representing "research" projects). Perhaps using a method? For instance, having the following line in an HTML template: {{ projet.project_type.as_icon }} And rendering it as: <img src="images/beaker_icon.png"/> Is this possible? Can I give the class method instructions on how to render images? If so, would this be a best practice? -
Form with hidden field not submitting
I have the following form in django forms.py class CtForm(ModelForm): class Meta: model = Contact fields = ["cid", "name", "email"] widgets = {'cid': HiddenInput()} models.py class Contact(models.Model): cid = models.ForeignKey(Cr, on_delete=models.CASCADE) name = models.CharField(max_length=255, null=False) email = models.EmailField(max_length=255, null=False) I have the form displayed in a template, and everything displays good and no issues there, the issue is when i submit the form, i get the following error: (Hidden field cid) This field is required. But if i remove the widgets = {'cid': HiddenInput()} from the forms.py it works perfect, any way to make this work without displaying the cid in the template? -
Django channels: Save messages to database with duplicates when two or more tabs opened
I'm using this solution for save messages to DB Django channels: Save messages to database But I have a problem with duplicates (in DB) when the user (message's author) has two or more tabs opened in the browser with same chat room. What's wrong? Please help! import json from channels.db import database_sync_to_async from channels.generic.websocket import AsyncWebsocketConsumer from .models import Message class ChatConsumer(AsyncWebsocketConsumer): @database_sync_to_async def create_chat(self, msg, sender): return Message.objects.create(sender=sender, msg=msg) 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, close_code): await self.channel_layer.group_discard(self.room_group_name, self.channel_name) async def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] sender = text_data_json['sender'] await self.channel_layer.group_send(self.room_group_name, { 'type': 'chat_message', 'message': message, 'sender': sender }) async def chat_message(self, event): message = event['message'] sender = event['sender'] new_msg = await self.create_chat(sender, message) # It is necessary to await creation of messages await self.send(text_data=json.dumps({ 'message': new_msg.message, 'sender': new_msg.sender })) -
Django Forms - Many to Many relationships with quantity in form
I have three models: 'Product,' 'Vehicle,' and 'VehicleStock.' I'm attempting to create a form for adding a new 'Vehicle.' This form should allow the specification of the 'registry,' 'brand,' and 'stock' (which is a ManyToMany field). Additionally, I'd like to specify the quantity of products associated with the vehicle. I've already tried using 'inlineformset_factory,' but it's not meeting my requirements. It creates a widget where you need to specify every product in the database. Instead, I want a widget that functions like 'add product,' enabling the addition of multiple product widgets for the same vehicle. How can I achieve this?" models.py class Product(models.Model): name = models.CharField(max_length=50) SKU = models.CharField(max_length=20, unique=True) price = models.DecimalField(max_digits=10, decimal_places=2) stock = models.IntegerField() def __str__(self): return f'{self.name}' class Vehicle(models.Model): registry = models.CharField(max_length=20, unique=True) brand = models.CharField(max_length=50) total_kilometers = models.IntegerField() stock = models.ManyToManyField(Product, through='VehicleStock') def __str__(self): return f'{self.registry}' class VehicleStock(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) vehicle = models.ForeignKey(Vehicle, on_delete=models.CASCADE) quantity = models.IntegerField() forms.py class VehicleForm(forms.ModelForm): class Meta: model = Vehicle exclude = ["total_kilometers"] registry = forms.CharField( label='Veic registry', widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Enter Registry'}), required=True, error_messages={'required': 'Please enter a Registry.'} ) brand = forms.CharField( label='Veic Brand', widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Enter Brand'}), required=True, error_messages={'required': 'Please enter a brand.'} ) base.html … -
auto move to cart function
We are trying to figure how to move the auction item to the cart. We have our program removing the auction from the auction listing page, however we haven't gotten it to to move to the highest bidders cart. Here is our auction_details function, mycart function auctions_details def auction_details(request, auction_id): auction = get_object_or_404(Auction, id=auction_id) if request.method == 'POST': bid_form = BidForm(request.POST) if bid_form.is_valid(): bid_amount = bid_form.cleaned_data['bid_amount'] if bid_amount > auction.current_bid: # Update the auction details auction.current_bid = bid_amount auction.highest_bidder = request.user Bid.objects.create(bidder=request.user, auction=auction, amount=bid_amount) messages.success(request, f'Your bid successfully is placed at {timezone.now()}!') messages.success(request, f'The auction will expire at {auction.end_date}!') messages.success(request, f'Expired? {auction.end_date <= timezone.now()}!') if auction.end_date <= timezone.now(): auction.ended = True cart_item, created = CartItem.objects.get_or_create(user=auction.highest_bidder, auction=auction) cart_item.quantity = 1 cart_item.save() auction.save() return redirect('auction_details', auction_id=auction.id) else: messages.error(request, 'Bid must be higher than the current bid.') else: bid_form = BidForm() return render(request, 'auctions/auction_details.html', {'auction': auction, 'bid_form': bid_form}) mycart fuction - def mycart(request): if request.user.is_authenticated: cart_items = CartItem.objects.filter(user=request.user) else: cart_items = [] total_amount = 0 # Initialize total amount to zero for item in cart_items: total_amount += item.auction.current_bid * item.quantity context = { 'cart_items': cart_items, 'total_amount': total_amount, # Pass the total_amount to the template } return render(request, 'auctions/mycart.html', context) We think there is … -
trying to add vote feature to my projcet & i'm adding 1 vote, how can check user already added or not and how can i save their data into database
Here is my model : class Vote(models.Model): answer = models.ForeignKey(Answer, on_delete=models.CASCADE, blank=False) author = models.ForeignKey(User, on_delete=models.CASCADE, blank=False) def __str__(self): return str(self.answer) here is my serializer : class VoteSerailizer(serializers.ModelSerializer): class Meta: model = Vote fields = '__all__' here is my views : @api_view(['POST']) @permission_classes([IsAuthenticated]) def upvote(request, pk): answer = get_object_or_404(Answer, id=pk) if answer['author'] == request.user: return Response({ 'error':"You cannot vote twice." }) answer.votes += 1 answer.save() return Response({ 'details':'Vote added' }, status.HTTP_202_ACCEPTED) It shows error "TypeError: 'Answer' object is not subscriptable" in my views loop. and i need to add author and answer in my database ie. model, how can i do that -
How to check for data entered on a form, on a website in the admin interface when using django
I can't seem to see the data entered in the form on my website when I am logging into the Django admin interface. I am expecting the information entered in the form to show in the admin interface or to at least see where the data is being saved. -
Modal bootstrap5 is not working in django app
i want to display the information of contents that retrieved from the database as table in django template, so i used modal bootstrap, the template below: **template.html: ** <!DOCTYPE html> <html dir="rtl" lang="ar"> <head> {% load static %} <title>الواردة المركزية</title> {% load bootstrap5 %} {% bootstrap_css %} <script src= "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700" rel="stylesheet"> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.5.0/css/all.css" integrity="sha384-B4dIYHKNBt8Bc12p+WXckhzcICo0wtJAoU8YZTY5qE0Id1GSseTk6S+L3BlXeVIU" crossorigin="anonymous"> <script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script> </head> <body> <table id="tblToExcl" class="table table-striped table-bordered table-sm"> <thead class="thead-dark"> <tr> <th>رقم الكتاب</th> <th>تاريخ</th> <th>تاريخ الاضافة</th> <th>ملاحظات</th> <th>اﻻجراء</th> </tr> </thead> <tbody> {% for doc in docs %} <tr> <td>{{ doc.number }}</td> <td>{{ doc.date }}</td> <td>{{doc.created_at}}</td> <td>{{ doc.note }}</td> <td>{{ doc.status }}</td> <td> <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#item-modal" data-item-id="{{ doc.id }}">View details</button> </td> </tr> {% endfor %} </tbody> </table> <script> $(document).ready(function() { $('#item-modal').modal({ show: false, }); $('#item-modal').on('show.bs.modal', function(event) { var itemId = $(event.relatedTarget).data('item-id'); $.ajax({ url: '/item-modal/' + itemId, success: function(data) { $('#item-modal .modal-body').html(data); }, }); }); }); </script> </body> </html> and modal.html: <div class="modal fade" id="item-modal" tabindex="-1" role="dialog" aria-labelledby="item-modal-label" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="item-modal-label">Item Information</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <div class="row"> <div class="col-6"> <p>Item name:</p> <p>{{ item.name }}</p> </div> <div class="col-6"> <p>Item … -
Debug forever pending Celery task calling OptaPy
I try running OptaPy in a Celery task from within a Django application using Redis as a broker. The task is received by the Celery worker, but remains PENDING forever and returns no result. If I set CELERY_TASK_ALWAYS_EAGER = True for debugging, the code runs fine, but synchronously. What could be the issue? Which steps can I take to find out? As OptaPy is a Python wrapper for a Java library, I suspect that Celery might not handle the additional thread well, but I don't know how to debug or fix this. This is the Celery task in question, additional code can be provided on request: @shared_task() def schedule_task(): solver_config = optapy.config.solver.SolverConfig() \ .withEntityClasses(Lesson) \ .withSolutionClass(TimeTable) \ .withConstraintProviderClass(define_constraints) \ .withTerminationSpentLimit(Duration.ofSeconds(30)) solution = solver_factory_create(solver_config) \ .buildSolver() \ .solve(generate_problem()) return str(solution) -
The window for selecting a Google account does not open
I made my site in Python Django and did authentication through django social auth (googleOauth2) and made a webView application for my site in Android Studio, when authenticating through the WebView application, the window with the choice of account does not open (Select an account), it asks for credentials as login and password. How can I make a window open to select an account? -
Django-allauth and subdomains
I have a website site.com with many subdomains (a.site.com ... z.site.com), all this subdomains are handled without using Django Sites framework. I want to add django-allauth for all my domains. Now I have only one Site entry in database (domain: site.com, name: My Site). If users is in a subdomain x.site.com and tries to reset password or link his facebook account, will allauth use my current subdomain in redirects, callback url, restore password links etc or will it use default url from Sites framework? I just hope that I don't have to create separate Site entry for each subdomain. Or will I have to? -
react + django deployment, the problem is static files 404 error
I've tried to deploy django project using react as front-end. I did 'npm run build' in react and i moved all the files builded to 'client' folder in django project like this enter image description here And i changed all the 'href' in 'link' and 'script' tags to ./ like <link rel="icon" href="./favicon.ico" /> <link rel="manifest" href="./manifest.json" /> <script defer="defer" src="./static/js/main.a1de6b00.js"></script> in index.html in 'client' folder. in the setting.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'client')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] I changed dirs of templates and STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'client/static') ] DEBUG = False I also changed static root and staticfiles_dirs and debug and in mysite/url.py from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from django.views.generic import TemplateView urlpatterns = [ path('',TemplateView.as_view(template_name="index.html"), name='index'), path('admin/', admin.site.urls), path('api/', include('api.urls')) ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I added a line of code for '' But when i run 'python manage.py runserver', it seems there is still problems to load static files like enter image description here Can you guys let me know what to solve the … -
How do I make database calls asynchronous inside Telegram bot?
I have a Django app that runs a Telegram chatbot script as a command. I start the Django app with python manage.py runserver. I start the telegram client with python manage.py bot. I want to list the entries from the Animal table within the async method that is called when a user types "/animals" in the telegram chat. My code works if I use a hard-coded list or dictionary as a data source. However, I'm not able to get the ORM call to work in async mode. File structure: |Accounts--------------------- |------| models.py------------ |Main------------------------- |------| Management----------- |---------------| Commands---- |-----------------------bot.py Animal model: class Animal(models.Model): id = models.AutoField(primary_key=True) user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=255) I removed a lot from the file, leaving only the relevant bits. bot.py # removed unrelated imports from asgiref.sync import sync_to_async from accounts.models import Animal class Command(BaseCommand): help = "Starts the telegram bot." # assume that the token is correct TOKEN = "abc123" def handle(self, *args, **options): async def get_animals(): await Animal.objects.all() async def animals_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: async_db_results = get_animals() message = "" counter = 0 for animal in async_db_results: message += animal.name + "\n" counter += 1 await update.message.reply_text(message) application = Application.builder().token(TOKEN).build() application.add_handler(CommandHandler("animals", animals_command)) … -
how to cancel a xhr request
i am trying to upload a file to django server backend.i added a progress bar by using javascript,xhr and ajax method also i added a cancel button to cancel the upload the progress bar is working properly but the cancel is not working. i used xhr.abort() method to cancel the xhr request,when i clicking the cancel button it stops the progress and again starts to upload from zero.(the cancel button seems like stops the progress but the file again starts to upload. -
Issue with S3 Uploads in Dockerized Django App on ECS
I'm facing an issue with S3 uploads in my Dockerized Django application running on AWS ECS. The setup includes RDS and S3, and I've successfully tested file uploads locally using docker run and Postman. However, when I create a task definition, launch an ECS EC2 cluster with a load balancer and a target group, and attempt to upload a file to S3, I'm encountering a 504 Gateway Timeout error. In the logs, I see the message 'Loading s3:s3,' and the service breaks, then reloads. for IAM i add S3FullAccess to all IAM related to my ecs in security groups i allow all traffic (inbound, outbound) in security groups i allow all traffic (inbound, outbound) Added the AmazonS3FullAccess policy to the ecsTaskExecutionRole IAM role associated with ECS tasks. Confirmed IAM role changes have propagated. Checked the trust relationship of the ecsTaskExecutionRole to allow ECS to assume the role. -
How can I run swagger in docker container with Python 3.12 and Django?
i've docker file and docker-compose for my api in Python. I want when the container runs, it starts the api with swagger. I tried with the own swagger and with the drf-yasg but i can't run the container, can anyone help me? Now, I'm trying with the drf-yasg but this error pops up: Creating network "api-cardiotech_default" with the default driver Creating api-cardiotech ... done Creating django ... done Attaching to django, api-cardiotech django exited with code 0 api-cardiotech | Watching for file changes with StatReloader api-cardiotech | Exception in thread django-main-thread: api-cardiotech | Traceback (most recent call last): api-cardiotech | File "/usr/local/lib/python3.11/threading.py", line 1045, in _bootstrap_inner api-cardiotech | self.run() api-cardiotech | File "/usr/local/lib/python3.11/threading.py", line 982, in run api-cardiotech | self._target(*self._args, **self._kwargs) api-cardiotech | File "/usr/local/lib/python3.11/site-packages/django/utils/autoreload.py", line 64, in wrapper api-cardiotech | fn(*args, **kwargs) api-cardiotech | File "/usr/local/lib/python3.11/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run api-cardiotech | autoreload.raise_last_exception() api-cardiotech | File "/usr/local/lib/python3.11/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception api-cardiotech | raise _exception[1] api-cardiotech | File "/usr/local/lib/python3.11/site-packages/django/core/management/init.py", line 394, in execute api-cardiotech | autoreload.check_errors(django.setup)() api-cardiotech | File "/usr/local/lib/python3.11/site-packages/django/utils/autoreload.py", line 64, in wrapper api-cardiotech | fn(*args, **kwargs) api-cardiotech | File "/usr/local/lib/python3.11/site-packages/django/init.py", line 24, in setup api-cardiotech | apps.populate(settings.INSTALLED_APPS) api-cardiotech | File "/usr/local/lib/python3.11/site-packages/django/apps/registry.py", line 91, in populate api-cardiotech | … -
SASS/SCSS django
PHOTO - show mistake(https://i.stack.imgur.com/wXCf5.png) Why got red underline (photo) as some problem in code, is there are some mistake? But it work properly... And the same question to sass in link... What to do for remove this "mistake". {% load sass_tags %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="{% sass_src 'css/main.scss' %}" rel="stylesheet" type="text/css"/> <title>Django Sass</title> </head> <body> <h1>WORK</h1> </body> <html> -
name is not passing through a function to another function in django
i am trying to pass a variable called name to pass to a function which is present in another function. I want to pass the variable name to the function plane and check if the values are matching with any of the names in my database. my views.py is from django.shortcuts import render,redirect from django.contrib.auth.forms import AuthenticationForm from .models import Logs,Plane from .forms import Login from django.contrib import messages from django.contrib.auth import authenticate, login ,logout from django.contrib.auth.models import User from django.shortcuts import get_object_or_404 from django.http import HttpResponse import json from django.http import JsonResponse # Create your views here. def loger(request): global name formy = AuthenticationForm() c=[] a=Logs.objects.all() if request.method == 'POST': formy = AuthenticationForm(data=request.POST) name=request.POST.get('username') password = request.POST.get('password') obj=Logs() obj.get_special_combination_value for b in a: if name == b.name and password == b.password: return redirect('ticket',pk=b.id) return render(request,'project/loger.html',{'formy':formy,'a':a}) def homepage(request): form=Login() if request.method=='POST': form=Login(request.POST) if form.is_valid(): user=form.save() plane_instance = Plane(name=user.name, password=user.password) plane_instance.save() return redirect('ticket',pk=user.pk) return render(request,'project/homepage.html',{'form':form}) def ticket(request,pk): tic=Logs.objects.get(id=pk) return render(request,'project/ticket.html',{'tic':tic}) def forgor(request): a=Logs.objects.all() if request.method=='POST': username=request.POST.get('name') password=request.POST.get('password') obj=Logs() obj.get_special_combination_value Logs.objects.filter(name=username).update(password=password) return redirect('homepage') return render(request,'project/forgor.html',{'a':a}) def plane(request): print(name) a=Logs.objects.all() b=Plane.objects.all() for c in b: if name==c.name: log_instance=Plane.objects.get(id=c.id) plane_instance=Plane.objects.get(id=c.id) for d in a: if name==d.name: plane_instance1=Logs.objects.get(id=d.id) if request.method == 'POST': checkbox_dict_json = request.POST.get('checkboxDict') … -
Python Dramatiq - how can I get environment variables?
I'm trying to get environment variables using dramatiq: @dramatiq.actor def create_instance(): subscription_id = os.environ["AZURE_SUBSCRIPTION_ID"] credential = DefaultAzureCredential() But I get this error: KeyError: 'AZURE_SUBSCRIPTION_ID' I think this means dramatiq can't get my environment variables. I tried to get them before calling the function and passing them as arguments: subscription_id = os.environ["AZURE_SUBSCRIPTION_ID"] credential = DefaultAzureCredential() create_instance.send(subscription_id, credential) @dramatiq.actor def create_instance(subscription_id, credential): ... But the problem is the credential can't be passed as an argument: Object of type DefaultAzureCredential is not JSON serializable Is there any solution? Thanks -
Django/Wagtail Language Redirection not working for 3 letter language code (kri)
I have set up Wagtail (latest) for multi-language. Works fine with Portuguese (pt), but I'm trying to work for Krio, which has a 3 character language code: kri. I have had to add Krio manally to LANG_INFO etc, and this works fine in the Wagtail UI, allowing me to set up alternate homepages for pt and kri, but when it comes to do the language redirecting, it fails to redirect to the kri translation. Is it possible I have missed a setting? Can the redirection logic handle 3 letter codes? My language settings: WAGTAIL_I18N_ENABLED = True USE_L10N = True LANGUAGES = [ ('en-GB', "English (Great Britain)"), ('en-US', "English (United States)"), ('en-CA', "English (Canada)"), ('pt', "Portuguese"), ('kri', "Krio (Sierra Leone Creole)"), ] WAGTAIL_CONTENT_LANGUAGES = [ ('en-GB', "English (British)"), ('kri', "Krio (Sierra Leone Creole)"), ('pt', "Portuguese"), ] EXTRA_LANG_INFO = { "kri" : { 'bidi': False, 'code': 'kri', 'name': 'Sierra Leonean Creole (Krio)', 'name_local': 'Krio', }, } LANG_INFO = dict(django.conf.locale.LANG_INFO, **EXTRA_LANG_INFO) django.conf.locale.LANG_INFO = LANG_INFO My middleware: MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.locale.LocaleMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", "allauth.account.middleware.AccountMiddleware", "wagtail.contrib.redirects.middleware.RedirectMiddleware", ] My urls patterns: urlpatterns = [ # path('django-admin/', admin.site.urls), path('cms/', include(wagtailadmin_urls)), path('documents/', include(wagtaildocs_urls)), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # Translatable URLs # These will … -
Problem accessing server through .onion domain
I tried to access a django server I was running on my virtual machine (Ubuntu 22.04.3) through an onion domain from my host OS(Windows 11) First I installed tor and edited my torrc file and added these lines: HiddenServiceDir /var/lib/tor/hidden_service/ HiddenServicePort 8002 127.0.0.1:8002 then I saw my host name in /var/lib/tor/hidden_service/hostname. root@soroush-VirtualBox:/home/soroush/Desktop/dw# cat /var/lib/tor/hidden_service/hostname jn46lvmv4uu7bjfveoax.............rxv6ljid.onion then I started a django project and edited settings.py to allow all host names ALLOWED_HOSTS = ['*'] then I started a django server on my 8002 port python manage.py runserver 127.0.0.1:8002 then I tried to access my django server using the onion link. I copied the url in my tor browser on my host OS. but nothing loaded. I didn't even get any requests in my django server. I even tried using tor browser on my phone with a different network but that didn't work neither. the tor service is running and my django server works ok when I use my locan IP (127.0.0.1:8002). but when I try to access it through onion domain I can't. what am I doing wrong? I tried to access my django server through an onion domain but I couldn't