Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
1 min delay in Vue.js rendering
So i have an application which has django as backend and vue.js on the frontend. This app intereacts with a source with websocket connection and this source continuosuly sends values to the application. whenever these values exceed any nominal state, those exceeded values are added in the symtomslist and the main page displays the updated values instantly, as the watch function of the page is set to watch on symptomslist. So the problem i have is, when we logged in and started the simulation, the app has been rendering the new values instantly when the values were changed, but after somrtime, even if the values were changed, the page has been rendering them after 1 min(even though different people logged in at different times, the lag in rendering started to all of us at the same time). we timed it multiple times and it measured 1 min each time. but when we logout and log back in, the state is again being rendered instantly. can you tell what might be causing this issue The console is logged every second. Maybe this is the issue? -
Pagination within Django - combining two projects
I am working off of two different projects. I have the Example By 5 and a YT series that I previously used to get started with Django. I liked the Pagination from the yt series so I decided to use that method, however in the Example By process, we moved from the Class base view to a function and now the pagination does not show up. I have added what I thought was needed in the view and html page but still getting nothing. VIEW code: def post_list(request, tag_slug=None): post_list = Post.published.all() tag = None if tag_slug: tag = get_object_or_404(Tag, slug=tag_slug) post_list = post_list.filter(tags__in=[tag]) paginator = Paginator(post_list, 3) # 3 posts in each page page_number = request.GET.get('page') # Get the page number page_obj = paginator.get_page(page_number) context = {'page_obj': page_obj,'is_paginated': page_obj.has_other_pages()} # Check if pagination is needed try: posts = paginator.page(page_number) except PageNotAnInteger: posts = paginator.page(1) except EmptyPage: posts = paginator.page(paginator.num_pages) return render(request, 'blog/post/list.html', {'posts': posts, 'context' : context, 'tag': tag}) Here is the Pagination section of the html: {% if is_paginated %} {% if page_obj.has_previous %} <a class="btn btn-outline-info mb-4" href="?page=1">First</a> <a class="btn btn-outline-info mb-4" href="?page={{ page_obj.previous_page_number }}">Previous</a> {% endif %} {% for num in page_obj.paginator.page_range %} {% if page_obj.number … -
Best Approach for Text Chunking in AI Chat Agent using React and Django (Langchain) without Sockets?
I’m currently building an AI chat agent that needs to handle text chunking and display responses word by word in real-time. My setup involves a React (frontend) and Django Langchain (backend) integration. I want to achieve this without relying on sockets to stream data and instead use an approach that can fetch and display responses as they are generated, ensuring the user sees a continuous flow of words. Here's a breakdown of my current setup: Frontend: React (with or without Redux) Backend: Django integrated with Langchain for handling the AI logic What I’m Looking For: Text chunking: Best practices for chunking AI responses (word by word or partial sentences) and updating the UI in React. Real-time updates: How to fetch and display this data incrementally (e.g., fetching a stream or chunks) without using sockets. Efficient handling: Strategies for making the experience smooth for users, especially on the frontend with React. I prefer not to use WebSockets and want to stick with traditional HTTP requests if possible. Looking for an approach that handles data/response chunking seamlessly so users get real-time updates without long waits. If anyone has experience with Langchain in this context or can share ideas on how to achieve … -
"Sign In Via Google" intermediary step in django-allauth
I am implementing Google OAuth into my Django project. I set up settings.py and everything, I got this <a href="{% provider_login_url 'google' %}">Continue with Google </a> link, but when I click it, it takes me to "http://127.0.0.1:8000/accounts/google/login/" page which looks like this: Only after clicking continue button I am redirected to the correct page when I can choose Google profile I want to log in with: How can I get rid of the intermediary step and go directly to selecting a Google profile after clicking the link? -
The list of urlpatterns should not have a prefix string
In Django 5.0 I get the error: The list of urlpatterns should not have a prefix string. My code is: from django.conf.urls import url from django.urls import path, include from django.contrib import admin app_name = 'AppServer_test' # specified as string literal rather than a variable urlpatterns = [ path('admin/', admin.site.urls), path('api/v1.0/user/', include('user_accounts.urls')), path('api/v1.0/notifications/', include('notifications.urls')), path('api/v1.0/feedback/', include('feedback.urls')), # path('', include('AppServer_test.urls')), # check that AppServer_test.urls is a valid and accessible module ] I've got the same code working in Django 3.2, the error only occurs in a system using 5.0 I've tried using round brackets instead of square as in this post: Django 1.11 url pattern error, how to solve? -
How to fix path lines order error in Django/Python?
I have strange error with urls.py file two lines: path('<slug:postcategory_slug>/<slug:slug>', post_detail, name='post_detail'), path('<slug:category_slug>/<slug:slug>', product_detail, name='product_detail'), If line with post_detail stands first view.product_detail render with error 404: No Post matches the given query. Request Method: GET Request URL: http://127.0.0.1:8000/pryamye-shlifmashiny/pnevmoshlifmashina-s150z66a Raised by: apps.blog.views.post_detail And view.post_detail works well But if line with product_detail stands first, like path('<slug:category_slug>/<slug:slug>', product_detail, name='product_detail'), path('<slug:postcategory_slug>/<slug:slug>', post_detail, name='post_detail'), view.product_detail works well But view.post_detail render with 404 error No Post matches the given query. Request Method: GET Request URL: http://127.0.0.1:8000/posts/pnevmaticheskij-udarnyj-gajkovert-at-238 Raised by: apps.store.views.product_detail Other config looks well, and URLS works PLS help me figure out what the problem is I do not know what the problem is, all the other files are fine, -
Issue in executing Django Server using python manage.py runserver
The following are the steps that I followed on my windows machine. pls let me know what the issue could be. And help me run my django server. Thanks a lot, Bhaskar Gundu PS C:\Windows\system32> .\MyVEnv2\Scripts\activate (MyVEnv2) PS C:\Windows\system32> django-admin startproject puddle django-admin : CommandError: 'C:\Windows\system32\puddle' already exists At line:1 char:1 + django-admin startproject puddle + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (CommandError: '... already exists:String) [], RemoteException + FullyQualifiedErrorId : NativeCommandError (MyVEnv2) PS C:\Windows\system32> cd puddle (MyVEnv2) PS C:\Windows\system32\puddle> ls Directory: C:\Windows\system32\puddle Mode LastWriteTime Length Name ---- ------------- ------ ---- d----- 10/17/2024 4:26 PM puddle -a---- 10/17/2024 4:27 PM 131072 db.sqlite3 -a---- 10/17/2024 4:26 PM 684 manage.py (MyVEnv2) PS C:\Windows\system32\puddle> python manage.py makemigrations No changes detected (MyVEnv2) PS C:\Windows\system32\puddle> python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions Running migrations: No migrations to apply. (MyVEnv2) PS C:\Windows\system32\puddle> python manage.py runserver python : Watching for file changes with StatReloader At line:1 char:1 + python manage.py runserver + ~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (Watching for fi...th StatReloader:String) [], RemoteException + FullyQualifiedErrorId : NativeCommandError I tried executing following the required steps and am expecting to have a successful running of my Django Server. -
Django Summernote plugin upload image by userid
I am using the Summernote plugin for Django and my target is to allow users to upload media inside the server. At the moment files are organized (by default) in a folder named with the upload date. Something like: "ProjectName/media/django-summernote/2024-10-11/989d2f98-ad3c-47d6-9c07-e5f6d0c731e6.png" "ProjectName/media/django-summernote/2024-10-17/13d646b8-d7cd-4e04-a76a-804a1ee0d090.jpg". Is it possible to change the path and include the user_id in the path? Something like "ProjectName/media/django-summernote/User100/989d2f98-ad3c-47d6-9c07-e5f6d0c731e6.png" "ProjectName/media/django-summernote/User200/13d646b8-d7cd-4e04-a76a-804a1ee0d090.jpg". What I have done I made these edits in the settings.py file # Summernote plugin def summernote_upload_to(request, filename): user = request.user # Create the dynamic path upload_path = f'user_upload/{user}' return os.path.join(upload_path) SUMMERNOTE_CONFIG = { 'attachment_upload_to': summernote_upload_to, 'summernote': { 'attachment_filesize_limit': 200 * 1000 * 1000, # specify the file size 'width': '100%', 'height': '480', } } but, when I upload an image, I get an error AttributeError: 'Attachment' object has no attribute 'user' -
SMTP AUTH extension not supported by server in Django
Im being building an project using django framework and for now i wanted to test wether i can send emails to any users locally. So wrote this code in settings.py and got the error saying that SMTP AUTH extension not supported by server. So i researched everything but didnt find why this error has been raised and do smtp needs authentication? Please let know how i can solve this problem settings.py EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" EMAIL_HOST = config('EMAIL_HOST',cast=str, default = 'smtp.gmail.com') EMAIL_PORT = config('EMAIL_PORT',cast=str,default="587") EMAIL_USE_TSL = config('EMAIL_USE_TSL',cast=bool,default=True) EMAIL_USE_SSL = config('EMAIL_USE_SSL',cast=bool,default=False) EMAIL_HOST_USER = config('EMAIL_HOST_USER',cast=str,default=None) EMAIL_HOST_PASSWORD = config('EMAIL_HOST_PASSWORD',cast=str,default=None) ADMIN_USER_NAME = config('ADMIN_USER_NAME',default = "Admin user") ADMIN_USER_EMAIL = config('ADMIN_USER_EMAIL',default = None) MANAGERS = [] ADMINS = [] if all([ADMIN_USER_NAME, ADMIN_USER_EMAIL]): ADMINS += [ (f'{ADMIN_USER_NAME}', f'{ADMIN_USER_EMAIL}') ] MANAGERS = ADMINS Error im getting is this : Traceback (most recent call last): File "C:\Indraneel_coding\Django\Saas\src\manage.py", line 22, in <module> main() File "C:\Indraneel_coding\Django\Saas\src\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Indraneel_coding\Django\Saas\venv\Lib\site-packages\django\core\management\__init__.py", line 442, in execute_from_command_line utility.execute() File "C:\Indraneel_coding\Django\Saas\venv\Lib\site-packages\django\core\management\__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Indraneel_coding\Django\Saas\venv\Lib\site-packages\django\core\management\base.py", line 413, in run_from_argv self.execute(*args, **cmd_options) File "C:\Indraneel_coding\Django\Saas\venv\Lib\site-packages\django\core\management\base.py", line 459, in execute output = self.handle(*args, **options) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Indraneel_coding\Django\Saas\venv\Lib\site-packages\django\core\management\commands\sendtestemail.py", line 46, in handle mail_admins(subject, "This email was sent to the site admins.") File "C:\Indraneel_coding\Django\Saas\venv\Lib\site-packages\django\core\mail\__init__.py", line … -
Django `squashmigrations` leaving lots of RemoveField
I am trying to use Django manage.py squashmigrations to reduce the number of migration files and migration operations, after years of accumulation. Django should supposedly optimize the migrations and it does so to some extent. Other cases, that should be obvious optimization are missed though, for example below where a simple AddField+RemoveField field is not. Only the AddField gets inlined into the CreateModel, but then the RemoveField still remains, instead of completely leaving out the field from CreateModel. Ideally, there shouldn't be a single RemoveField left after a squash, if I'm not mistaken. Migration 1: Add the model class Migration(migrations.Migration): dependencies = [("data", "0104")] operations = [ migrations.CreateModel( name="MyModel", fields=[... ] ) ] Migration 2: Add a field to the model class Migration(migrations.Migration): dependencies = [("data", "0107")] operations = [ migrations.AddField( model_name="mymodel", name="process_name", field=models.CharField(default=None, max_length=300, null=True), ), ] Migration 3: Remove the same field from the model class Migration(migrations.Migration): dependencies = [("data", "0121")] operations = [migrations.RemoveField(model_name="mymodel", name="process_name")] Resulting squashed migration: class Migration(migrations.Migration): replaces = [...] initial = True operations = [ migrations.CreateModel( name="MyModel", fields=[ ( "process_name", # Should be possible to leave out ??? models.CharField(default=None, max_length=300, null=True), ), ], ), migrations.RemoveField(model_name="mymodel", name="process_name"), # ??? ] Is this expected or what … -
Issue Displaying All Colors of a Product Variant in Django Template
I'm working on a Django application where I have a Product model with a many-to-many relationship with a Color model. I want to display all colors associated with a product variant on its detail page. However, when I click on a specific color (e.g., white), the page only shows that color instead of all available colors for the product variant. Here’s the relevant code: Models: class Color(models.Model): code = models.CharField(max_length=7) # Hex color code image = models.ImageField(upload_to='colors/') # Image field for color representation product_varients = models.ManyToManyField('Product', related_name='color_variants', blank=True) class Product(models.Model): pid = ShortUUIDField(length=10, max_length=100, prefix="prd", alphabet="abcdef") user = models.ForeignKey(CustomUser , on_delete=models.SET_NULL, null=True) category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, related_name="category") color = models.ManyToManyField(Color, blank=True) View Function: def product_varient_detail_view(request, pid): try: product_variant = Product.objects.get(pid=pid) except Product.DoesNotExist: return render(request, "core/error_page.html") wishlist = wishlist_model.objects.filter(user=request.user) if request.user.is_authenticated else None sub_category = SubCategory.objects.all() categories = Category.objects.prefetch_related('subcategories').order_by('?')[:4] nav_category = Category.objects.filter(special_category=True).prefetch_related('subcategories').order_by('?')[:4] # Initialize variables colors = product_variant.color_variants.all() # Get the colors of the product variant linked_colors = set() # Use a set to avoid duplicates # Get linked colors for color in colors: for linked_product in color.product_varients.exclude(id=product_variant.id): # Exclude current product linked_colors.update(linked_product.color_variants.all()) # Update the set with linked product colors # Convert linked_colors back to a list for the … -
How to Implement Model Versioning in Django Without Affecting Transactional Data
MODELS Transaction Model class TransactionOrders(models.Model): product = models.ForeignKey(Product, on_delete=models.DO_NOTHING) customer = models.ForeignKey(Customer, on_delete=models.DO_NOTHING) ... class Product(models.Model): name = models.CharField(max_length=55, unique=True) title = models.TextField() ... class Customer(models.Model): customer_id = models.CharField(max_length=55, primary_key=True) name = models.CharField(max_length=100) # there might be more models Imagine we have some entries in transaction model now admin updated or soft deleted some entries in product | customer models issue: Old data modified either with new value or showing ids (whose entries are updated | deleted respectively) Requirement: How can I avoid so above issue so that when user creating new order updated value reflected & when user visit history order then it show's entries which has values at that time Note: If I haven't able to clarify let me know I try to put more data to make my query understandable -
Django: Unable to display colors of linked products
I'm having trouble displaying the colors of linked products in my Django template. I have a Product model with a many-to-many relationship with a Color model, and I want to display the colors of the linked products. Here is my view: def product_varient_detail_view(request, pid): # ... colors = [] linked_colors = [] if product_variant.color.exists(): colors = product_variant.color.all() if product_variant.color.exists(): for color in product_variant.color.all(): for linked_product in color.product_varients.all(): if linked_product != product_variant: linked_colors.extend(linked_product.color.all()) context = { # ... 'colors': colors, 'linked_colors': linked_colors, } return render(request, "core/product_varient_detail.html", context) And here is my template: {% if colors %} {% for c in colors %} <div class="color__radio"> <input type="radio" id="color_{{ c.id }}" name="color" data-image-url="{{ c.image.url }}" class="color-input" data-url="{% url 'core:product_varient_detail' c.product_varients.first.pid %}?color={{ c.coid }}"> <label class="color__radio-label" for="color_{{ c.id }}" style="background-color: {{ c.code }};"></label> </div> {% endfor %} {% endif %} {% if linked_colors %} {% for c in linked_colors %} <div class="color__radio"> <input type="radio" id="color_{{ c.id }}" name="color" data-image-url="{{ c.image.url }}" class="color-input" data-url="{% url 'core:product_varient_detail' c.product_varients.first.pid %}?color={{ c.coid }}"> <label class="color__radio-label" for="color_{{ c.id }}" style="background-color: {{ c.code }};"></label> </div> {% endfor %} {% endif %} However, the colors of the linked products are not being displayed. I've tried debugging the code, but I'm not … -
Where do I put Django Debug Terminal in middleware
Django Debug Terminal's documentation says The order of MIDDLEWARE is important. You should include the Debug Toolbar middleware as early as possible in the list. However, it must come after any other middleware that encodes the response’s content, such as GZipMiddleware. But this can be a bit tricky. For example, in my settings.py I have MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', ] In this situation is the best place to put debug_toolbar.middleware.DebugToolbarMiddleware right after django.middleware.common.CommonMiddleware since that uses force_text while AuthenticationMiddleware, SessionMiddleware and MessageMiddleware don't seem to encode anything? -
Why does Django Rest Framework Pagination work with Django.http JsonResonse() and not rest_framework.response Response()
I've followed the tutorial on enabling/creating custom pagination for ModelViewSets in Django Rest Framework (DRF). But the custom pagination doesn't show up as part of the content of the response. I only get my results split according to the 'PAGE_SIZE' setting in an object labeled data with no count, or page_size as defined in my custom pagination class. I added the following lines in my setting.py file: REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'core.pagination.CustomPagination', 'PAGE_SIZE': 2, ... } Custom pagination class: from rest_framework import pagination from rest_framework.response import Response class CustomPagination(pagination.PageNumberPagination): page_size = 2 def get_paginated_response(self, data): return JsonResponse({ 'page_size': self.page_size, 'count': self.page.paginator.count, 'results': data }) My ModelViewSet class PersonViewSet(viewsets.ReadOnlyModelViewSet): """ A simple ViewSet for listing or retrieving and creating people. """ queryset = Person.objects.all() permission_classes = (IsAuthenticated,) serializer_class = PersonSerializer pagination_class = CustomPagination I have tried changing the ModelViewSet to various other types such as genericViewSet and defining my list() functions etc. The results from the list API endpoint I expected: { "page_size": 2, "count": 2548, "results": [ { "type": "Person" }, { "type": "Person" } ] } The results from the list API endpoint I got: { "data": [ { "type": "Person" } }, { "type": "Person" } } ] … -
Encountering 500 Internal Server Error on Django API POST request
I am encountering a 500 Internal Server Error when trying to send a POST request to a Django API to create an object. I have checked my code but cannot identify the source of the issue. Here’s the code I’m using: Serializer class DeliverableSerializer(serializers.ModelSerializer): class Meta: model = Deliverable fields = ("num", "project", "reviewer", "deliverable_type", "description", "due_date", "id", "draft") Views class DeliverableAPIView(APIView): def post(self, request, format=None): serializer = DeliverableSerializer(data=request.data) if serializer.is_valid(): instance = serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def put(self, request, pk, format=None): try: deliverable = Deliverable.objects.get(pk=pk) serializer = DeliverableSerializer(deliverable, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) except Exception as e: return Response({"error": "An unexpected error occurred."}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) URLs path('api/deliverables/', DeliverableAPIView.as_view(), name='deliverable-list'), # For POST path('api/deliverables/<int:pk>/', DeliverableAPIView.as_view(), name='deliverable-detail'), # For PUT POST Request in My Script def post_data(endpoint, data): """Send data to the API via POST request.""" try: response = requests.post(API_URL + endpoint, json=data, timeout=10) response.raise_for_status() # Raises an HTTPError for bad responses return response.json() # Return the JSON response if needed except requests.exceptions.HTTPError as err: raise Exception(f"HTTP error occurred while posting to {endpoint}: {err}") # For HTTP errors except requests.exceptions.RequestException as err: raise Exception(f"Error posting data to {endpoint}: {err}") When I try to … -
Simple JWT TokenRefreshView: response has two types
I'm having trouble accessing the data attribute on a Response object in Django Rest Framework after refreshing the access token. factory = APIRequestFactory() new_request = factory.post( "/api/token/refresh/", {"refresh": refresh_token}, format="json", ) new_request.META["CONTENT_TYPE"] = "application/json" refresh_view = TokenRefreshView.as_view() refresh_response = refresh_view(new_request) print(type(refresh_response)) refresh_response.data["message"] = "Token refresh successful" When I run this code, the print statement correctly outputs <class 'rest_framework.response.Response'>. However, Pylint is complaining that I cannot access the data attribute. Cannot access attribute "data" for class "HttpResponse" Attribute "data" is unknownPylancereportAttributeAccessIssue -
my ide doesnt recognize django-admin it says django is already installed
so basically iam currently using vscode as my ide and i try to install django and it says the requirements already satisfied however when i try to run django-admin and start a project it doesnt recognize it and gives an error saying: django-admin : The term 'django-admin' is not recognized as the name of a cmdlet, function, script file, or operable program. i tried the same thing on pycharm and it works perfectly and im looking for solutions everywhere i have tried uninstalling django but it didnt work -
Where remove or set initial rows for database in Django?
I store some temporary data in a database linked to a web socket. After a server reboot, the web sockets die and I want to delete all data from the corresponding table. Tell me where ideologically this should be done or such data should not be stored in the database at all? I tried putting this block in AppConfig.ready but the console warning says it's the wrong place. from django.apps import AppConfig class GameConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'game' def ready(self) -> None: LobbySetting = self.get_model('LobbySetting') LobbySetting.objects.all().delete() Warning in console: RuntimeWarning: Accessing the database during app initialization is discouraged. To fix this warning, avoid executing queries in AppConfig.ready() or when your app modules are imported. warnings.warn(self.APPS_NOT_READY_WARNING_MSG, category=RuntimeWarning) -
Web Socket connection failed
On my website i am using Django, the WebSocket works fine on localhost but when i push it to VPS (Virtual private server) i get the error of WebSocket connection to wss://domain_name/ws/admin/pending/products/ failed. this is my asgi.py: import os import django from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from django.core.asgi import get_asgi_application import api.routing os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Naviguih_backend.settings") django.setup() application = ProtocolTypeRouter( { "http": get_asgi_application(), "websocket": AuthMiddlewareStack(URLRouter(api.routing.websocket_urlpatterns)), } ) and my routing.py: from django.urls import path from .consumers import AdminNotificationConsumer, NotificationConsumer websocket_urlpatterns = [ path("ws/notifications/", NotificationConsumer.as_asgi()), path("ws/admin/pending/products/", AdminNotificationConsumer.as_asgi()), ] I read some solutions that says you need to configure the Nginx to forward port and here is my configuration: server { server_name domain_name; client_max_body_size 25M; location / { proxy_pass http://127.0.0.1:8000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } location /ws/ { proxy_pass http://127.0.0.1:8000; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "Upgrade"; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/domain_name/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/domain_name/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host = domain_name) { return 301 … -
Python django model not pulling the table name, returning the project name instead
I have created both a django and a python project directory structure is analysis db_router models settings urls wsgi settings compareTemplates apps models tests utils views My model looks like this class Plans(models.Model): PROJECT_NAME = models.TextField() class Meta: db_table = 'schema.table' # specify the schema and table name managed = False # Prevent Django from managing the table schema def __str__(self): return self.PROJECT_NAME I have the database set up properly in the settings file and I am trying to see if my model can connect to it I ran: python manage.py shell from compareTemplate.models import Plans print(Plans._meta.db_table) the value returned is "compareTemplate_plans" I was not expecting that, I was looking for "schema.Table" This is my first real app in django, but I cannot figure out why the result is the project name. Thanks -
Unsupported lookup 'phone_number' for ForeignKey or join on the field not permitted on Multi Table inherited django models
I've 2 models here, BaseTransaction and AccountTransaction. Each of them are seperate model. But I've created AcccountTransaction model by inheriting BaseTransaction. Each of them has tables. Problem is when I add any field of BaseTransaction to AccountTransaction admin and try to search it's returning error below in title. class BaseTransaction(mixins.DeviceForTransactionMixin): """ Base class for transactions. """ # Choices: Debit (income) or Credit (expense) # NOTE: Income means the transactions to wallet transaction_type = models.CharField( choices=choices.TransactionType.choices, max_length=6, default=choices.TransactionType.CREDIT, db_index=True, ) # Choices: Auto or Manual # Auto: Automatically transfer the money to the GasMeter by cron job # Manual: Manually transfer the money to the GasMeter by user transfer_type = models.CharField( choices=choices.TransferType.choices, max_length=6, default=choices.TransferType.MANUAL, db_index=True, ) # Choices: Pending, On hold, Success, Failed, Canceled # Pending: The transaction is pending (on created) # On hold: The transaction is on hold (on hold) # Success: The transaction is successful (success) # Failed: The transaction is failed (failed) # Canceled: The transaction is canceled (canceled) status = models.CharField( choices=choices.TransactionStatus.choices, max_length=8, default=choices.TransactionStatus.PENDING, db_index=True, ) # To find out where the money came from # Choices: Card, Wallet source = models.CharField( choices=choices.TransactionSource.choices, max_length=8, db_index=True, ) # To find out where the money went # Choices: … -
Adding inlines to existing User model changes User admin pages
I have Domain model with a many-to-many user field to the existing User model. I want a Domain select field when I Add or Change a User on these User Admin pages. I used admin.TabularInline to achive this. The attached images show how changed the Add page after add inlines to the code. The minimal fieldset extended to a full fieldset what Django uses when someone edits an existing user, and the fieldsets completely mixed compared to the original page without inlines. Original Add User page The changed Add User page This is the actual code I tried, and the image above shows the working inlines with the Domain field, but I don't want to change the rest of the page. I'm satisfied with the existing Django User model and templates, I don't want a Custom User model and templates either, if I can avoid that. # model.py from django.db import models from django.contrib.auth.models import User from django.utils.translation import gettext as _ class Domain(models.Model): domain = models.CharField(_('Domain name'), max_length=100) master_dns_server = models.CharField(_('Master DNS server'), max_length=100, blank=True, default='') updatekey_secret = models.CharField(_('Key'), max_length=255, blank=True, default='') updatekey_name = models.CharField(_('Key name'), max_length=50, blank=True, default='') updatekey_algorythm = models.CharField(_('Key algorythm'), max_length=50, blank=True, default='') last_transfer = models.DateTimeField(_('Last … -
how can I save and continue if WebDriverWait did not find the class
I want that if WebDriverWait didn’t find what it was looking for, continue the cycle and save it in the database, I tried giving the src_iframe variable and checking if not src_iframe but it didn’t help ` try: drivers.get(film_url) iframe = WebDriverWait(drivers, 8).until( ec.presence_of_element_located((By.ID, "cinemaplayer-iframe")) ) src_iframe = WebDriverWait(drivers, 8).until( lambda d: iframe.get_attribute('src') != '' ) if not src_iframe: film_instance.is_completed2 = True film_instance.save() continue ` -
Large file download fails on slow network using HTTP/2 and AWS ALB
Given the following architecture: client <-> AWS ALB <-> uwsgi <-> Django The client fails to download a 12MB file when using HTTP/2 (the default), but works using HTTP/1.1. The file is streamed through Django for authentication purposes (it's fetched from a third party service). Here is an example of failure (I'm using a Socks proxy to limit bandwidth): $ curl -x socks5://localhost:1080 https://example.com/file.pdf --output "file.pdf" % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 79 12.6M 79 10.0M 0 0 61254 0 0:03:36 0:02:51 0:00:45 64422 curl: (92) HTTP/2 stream 1 was not closed cleanly: PROTOCOL_ERROR (err 1) However the same command with the flag --http1.1 works fine. This fails when I limit downloads to 512kbps - it works at 1024Kbps. I've not looked for the sweet spot, it's not important. Notes: This also fails with a browser, it's not a curl issue Using curl with -v doesn't give any additional information. uwsgi does not output any errors. As far as it's concerned it did it's job. This is the output: [pid: 44|app: 0|req: 2603/9176] [ip] () {34 vars in 639 bytes} [Wed Oct 16 09:29:29 2024] GET /file.pdf => …