Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django StreamingHttpResponse streams locally but not in production
I am posting this question after a lot of research but didn't get any solution working for me. I don't know what am I doing wrong, as I am new to Django Following is my code base for stream.py import json from django.http import StreamingHttpResponse from decimal import Decimal class DecimalEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, Decimal): return str(obj) # or float(obj) return super(DecimalEncoder, self).default(obj) class StreamResponseMixin: def stream_response(self, queryset, serializer_class, gen_message_func=None): def generate_stream(): for item in queryset: serializer = serializer_class(item) yield self.gen_message(serializer.data, gen_message_func) response = StreamingHttpResponse(generate_stream(), content_type='text/event-stream') response['X-Accel-Buffering'] = 'no' # Disable buffering in nginx response['Cache-Control'] = 'no-cache' # Ensure clients don't cache the data response['Transfer-Encoding'] = 'chunked' return response def gen_message(self, data, gen_message_func=None): if gen_message_func: return gen_message_func(data) return '{}\n'.format(json.dumps(data, cls=DecimalEncoder)) # Default behavior if no custom message generator is provided Views.py class PackageViewSet(viewsets.ModelViewSet, StreamResponseMixin): queryset = Package.objects.all().order_by('-created_at') def get_serializer_class(self): if self.action in ['list', 'modified']: return PackageListSerializer return PackageDetailSerializer def get_queryset(self): user = self.request.user package_queryset = Package.objects.all().order_by('-created_at') package_queryset = package_queryset.select_related('customer', 'creator').prefetch_related( Prefetch('products', queryset=Product.objects.all()), ) try: customer = Customer.objects.get(user=user) package_queryset = package_queryset.filter(customer=customer) except ObjectDoesNotExist: pass return package_queryset @action(detail=False, methods=['GET'], url_path='stream-packages') def get_stream(self, *args, **kwargs): packages = self.get_queryset().iterator(chunk_size=50) return self.stream_response(queryset=packages, serializer_class=PackageListSerializer) nginx.conf server { listen 443 ssl; server_name abc.api.ai; ssl_certificate /etc/letsencrypt/live/abc.api.ai/fullchain.pem; … -
How to add css and bootstrap in python django
When I try to load css file along with bootstrap, my css file doesn't work but bootstrap works fine. I don't know what went wrong and it annoys me the fact that something that supposed to take minutes to work takes me days to make it work for me enter image description here <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Bootstrap demo</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous"> <link rel="stylesheet" href="https://unpkg.com/bootstrap@5.3.3/dist/css/bootstrap.min.css"> <link rel="stylesheet" href="https://unpkg.com/bs-brain@2.0.4/tutorials/buttons/button-1/assets/css/button-1.css"> <link rel = "stylesheet" href = "css/style.css"> </head> <body> {% block content %} {% endblock %} </div> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz" crossorigin="anonymous"></script> </body> </html> -
Django CORS and CRSF Issues
The Issue I am at my wits end with CORS and CSFR issues. When I fix something I feelk like I am playing wack-a-mole when I fix something another element i not rendering. I am using django-cors-headers library. I have reviewed other Django CORS Questions, and tried to modify the suggestions but still getting inconsistent loading. I tried to make the most permissive configruations possible Source Code and Output The element that is not renderig is from docuseal, console output is Access to image at 'https://docuseal.s3.amazonaws.com/se9pbobli54k4y03zqliyh91ssyj?response-content-disposition=inline%3B%20filename%3D%220.jpg%22%3B%20filename%2A%3DUTF-8%27%270.jpg&response-content-type=image%2Fjpeg&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAQXOPSUYTZ5CT2YNP%2F20240611%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20240611T121805Z&X-Amz-Expires=14400&X-Amz-SignedHeaders=host&X-Amz-Signature=faded6e47a7668b5832bca56fe88b62454133cbe89f644cf1f06fcf0798c076a' from origin 'http://127.0.0.1:9555' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Here are my CORS & CSFR related settings: REFERRER_POLICY = "strict-origin-when-cross-origin" CSRF_COOKIE_NAME = "nhhc-csrf" CSRF_FAILURE_VIEW = "nhhc.urls.permission_denied_handler" SESSION_COOKIE_NAME = "nhhc-session" CSRF_HEADER_NAME = "X_CSRFToken" # CORS_ALLOWED_ORIGIN_REGEXES = [ # r"^null$", # r"^http://localhost:[0-9]+$", # r"^http://127\\.0\\.0\\.1:[0-9]+$", # r"^https://localhost:[0-9]+$", # r"^https://127\\.0\\.0\\.1:[0-9]+$", # r"^https://docuseal.s3.amazonaws.com/*" # ] CSRF_COOKIE_SECURE = False CORS_ALLOW_PRIVATE_NETWORK = True CSRF_COOKIE_DOMAIN = None SESSION_COOKIE_SECURE = False CORS_ORIGIN_ALLOW_ALL = True SESSION_COOKIE_HTTPONLY = False CORS_ALLOW_CREDENTIALS = True CSRF_TRUSTED_ORIGINS = ["http://localhost"] The Ask Can someone offer input or resources on what I need to do to get this docseal element to render. If i have coinflicting settings. -
Django PasswordResetForm Not Sending Emails with Custom Domain
I'm encountering an issue with Django's PasswordResetForm where emails are not being sent when a custom domain is specified. Below is the save method within my custom form: class PasswordResetForm(auth_forms.PasswordResetForm): """ This form takes the same structure as its parent from :py:mod:`django.contrib.auth` """ def save(self, *args, domain_override=None, request=None, **kwargs): """ Generates a one-use only link for resetting password and sends to the user. """ site = get_current_site(request) if domain_override is not None: site.domain = site.name = domain_override for user in self.get_users(self.cleaned_data["email"]): self.send_password_reset_email(site, user, request) def send_password_reset_email(self, site, user, request=None): extra_context = { "user": user, "site": site, "reset_url": get_password_reset_url(user), "request": request, } CustomerDispatcher().send_password_reset_email_for_user(user, extra_context) I tried to retrieve the domain from the request using domain = request.get_host() but still facing the issue. Additional Context: When the domain_override parameter is provided with a custom domain, emails are not being sent to users. The get_current_site function is being used to fetch the current site based on the request. The custom domain is correctly retrieved and assigned to the site variable, but emails are still not being sent. The send_password_reset_email method is responsible for sending the password reset email to the user with the correct reset link. Question: How can I ensure that emails … -
How to change the root directory of a Python project?
I have a simple Django project (namely the one from this tutorial). The main part of the tree looks like this: . ├── env ├── proj │ ├── proj │ │ ├── __init__.py │ │ ├── settings.py │ │ ├── urls.py │ │ └── wsgi.py │ ├── api │ │ ├── __init__.py │ │ ├── serializers.py │ │ ├── urls.py │ │ └── views.py │ ├── base │ │ ├── __init__.py │ │ ├── admin.py │ │ ├── apps.py │ │ ├── models.py │ │ ├── tests.py │ │ └── views.py | ├── __init__.py │ └── manage.py └── README.md In the tutorial the outer proj folder is the root. In api/views.py is the following import: from base.models import Item When I print sys.path in settings.py, it contains /path/to/wrapper/proj. But I would like my root folder to be one level higher. This is what I did: go to Settings > Project structure and change content root to /path/to/wrapper append another .parent to BASE_DIR in settings.py(now BASE_DIR = Path(__file__).resolve().parent.parent.parent) prepend proj. to imports(now from proj.base.models import Item) But that does not work: ModuleNotFoundError: No module named 'proj.base' When I print sys.path in settings.py, it still contains /path/to/wrapper/proj. Where does that actually come … -
Django channels function group_send causing problems
Context: I'm making a messaging application on the web, in which I'm implementing Django for the backend. For concurrency I am using websockets (channels). Well, for the user group management (channel layer) I'm using the following logic. There will be two types of groups, ‘chats’ and ‘notifications’. The notifications groups are groups of 1 user and 1 channel_name, they are used to track the user's connection, they have the following form: {user_id} : [‘{channel_name}’] Example: ‘30’: [‘specific.363469477d6745289c5bc679b7947790!d813479fc71448d49592711a7f823e06’] On the other hand, chat groups will be used to track the presence of users in chats, and report events such as ‘writing’, ‘connecting or disconnecting’, ‘updating’, ‘new messages’, etc ... At group level they have the following form: {id_minor}-{id_major} : [‘{channel_of_id_1}, {channel_of_id_2}’] Example: ‘1-30’: [‘specific.363469477d6745289c5bc679b7947790!d813479fc71448d49592711a7f823e06’] Note : in group chats there can be a maximum of 2 members, i.e. if user 1 joins the chat with 2, the structure would be like this... 1-2‘ : [’{channel_name_of_1}"]. If 2 enters the chat with 1, the structure would be like this ... ‘1-2’ : [‘{channel_name_of_2}’] And if both are in the chat ... ‘1-2’ : [‘{channel_name_of_2}, {channel_name_of_1}’] Problem: in the django application I have the following function ... logger = logging.getLogger('django.channels') async def broadcast_connection_inform(user_id, … -
Model manager queryset doubles the sum for sets of amounts
I want to return the sums of items and payments for an invoice using a model manager. It works correctly if there is only one record in the payment and item models, if I add more I can no longer chain the results. In the shell I tried the following >>> Invoixe.objects.with_aggregates().last().tot Decimal('60') >>> Invoixe.objects.with_totals().last().tot Decimal('30') with_aggregates returns the wrong total(tot) value (The correct total is 30) The SQL looks like this SELECT "task_invoixe"."id", "task_invoixe"."name", (CAST(SUM("task_ixem"."amount") AS NUMERIC)) AS "tot", (CAST(SUM("task_paxment"."amount") AS NUMERIC)) AS "pay", (CAST(((CAST(SUM("task_ixem"."amount") AS NUMERIC)) - (CAST(SUM("task_paxment"."amount") AS NUMERIC))) AS NUMERIC)) AS "bal" FROM "task_invoixe" LEFT OUTER JOIN "task_ixem" ON ("task_invoixe"."id" = "task_ixem"."invoixe_id") LEFT OUTER JOIN "task_paxment" ON ("task_invoixe"."id" = "task_paxment"."invoixe_id") GROUP BY "task_invoixe"."id", "task_invoixe"."name" ORDER BY "task_invoixe"."id" ASC LIMIT 1 Here is the code ChatGPT believes this code should work I can create the same error by chaining managers like so >>> Invoixe.objects.with_totals().with_payments().last().tot Decimal('60') >>> Invoixe.objects.with_totals().last().tot Decimal('30') Which also give the wrong amount from django.db import models from django.db.models import Sum, F class InvoixeQueryset(models.QuerySet): def with_totals(self): return self.annotate(tot=Sum(F('ixem__amount'))) def with_payments(self): return self.annotate(pay=Sum(F('paxment__amount'))) def with_aggregates(self): return self.annotate( tot=Sum('ixem__amount'), pay=Sum('paxment__amount'), ).annotate(bal=F('tot') - F('pay')) class InvoixeManager(models.Manager): def get_queryset(self): return InvoixeQueryset(self.model, using=self._db) def with_aggregates(self): return self.get_queryset().with_aggregates() def with_totals(self): return self.get_queryset().with_totals() … -
Django javascript hide functionality not working
What I basically want is for there only to be the "This product has variations" checkbox, then if the user checks that box, then the Size and Colour checkboxes will show up. If the user clicks size, the size variation value box will show up. Same with colour. Right now although I am trying with my script to achieve this functionality, I can't. What am I doing wrong here? Thanks in advance! My models.py: class Product(models.Model): name = models.CharField(max_length=100) product_slug = models.SlugField(unique=True, blank=True) description = models.TextField() price = models.DecimalField(max_digits=10, decimal_places=2) image = models.ImageField(upload_to='products/') image2 = models.ImageField(upload_to='products/', null=True, blank=True) business = models.ForeignKey(Business, on_delete=models.CASCADE, related_name='products') in_stock = models.BooleanField(default=True) is_popular = models.BooleanField(default=False) is_best_seller = models.BooleanField(default=False) min_delivery_time = models.PositiveIntegerField(null=True, help_text="Minimum estimated delivery time in business days") max_delivery_time = models.PositiveIntegerField(null=True, help_text="Maximum estimated delivery time in business days") has_variations = models.BooleanField(default=False) def __str__(self): return f'{self.business.business_name}, {self.name}' def get_json_data(self): data = { 'id': self.id, 'name': self.name, 'price': float(self.price), 'description': self.description, 'images': [self.image.url, self.image2.url] if self.image and self.image2 else [], 'min_delivery_time': self.min_delivery_time, 'max_delivery_time': self.max_delivery_time, } return json.dumps(data) def save(self, *args, **kwargs): if not self.product_slug: self.product_slug = slugify(self.name) super().save(*args, **kwargs) @property def overall_review(self): avg_rating = self.reviews.aggregate(Avg('rating'))['rating__avg'] return round(avg_rating, 1) if avg_rating else 0 def star_rating_percentage(self, star): total_reviews = self.reviews.count() … -
How to change font in Django form?
I'm writing a website in django, using a built-in form, but the font is not at all like in the example. I can't make the text smaller my site looks like this forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class SignUpForm(UserCreationForm): phone_number = forms.CharField(max_length=15, required=True, help_text='Номер телефона в формате +7 9XX XXX XX XX') password1 = forms.CharField( label='Password', strip=False, widget=forms.PasswordInput(attrs={"autocomplete": "new-password"}),) class Meta: model = User fields = ('username', 'phone_number', 'email', 'password1', 'password2', ) views.py from django.contrib.auth import login, authenticate from django.shortcuts import render, redirect from .forms import SignUpForm from .models import Profile def registration(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): user = form.save() Profile.objects.create(user=user, phone_number=form.cleaned_data.get('phone_number')) raw_password = form.cleaned_data.get('password') user = authenticate(username=user.username, password=raw_password) login(request, user) return redirect('/') else: form = SignUpForm() return render(request, 'users/signup.html', {'form': form}) main.html (template) {% load static %} {{ '<' }}{{ '!DOCTYPE html>' }} <html lang="ru"> <head> <meta charset="UTF-8"> <title>{% block title %}{% endblock %}</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous"> <link href="{% static 'main/css/main.css' %}" rel="stylesheet"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css" integrity="sha512-SnH5WK+bZxgPHs44uWIX+LLJAJ9/2PkPKZ5QiAj6Ta86w+fsb2TkcmfRyVX3pBnMFcV7oQPJkl9QevSCWr3W6A==" crossorigin="anonymous" referrerpolicy="no-referrer" /> </head> <body> <div id="header"> <span class="logo">Greenhouse</span> </div> <div id="content"> {% block content %} {% endblock %} </div> </body> </html> signup.html (login page) {% extends … -
python django floadformat doesn't work with arabic langauge
I am working on an ecomerece site, In django template i want to render value with float value 2 like that {{product.tax_price|floatformat:2}} it return correct value when language in english as soon as i change into arabic it render value like 120,00 instead of 120.00. can you please specify the issue i am having thanks in advance I have try syntax describe in django formating documentation {{ product.tax_price|floatformat:"3u" }} -
Syncing offline app with lots of data with server
Hi fellow stackoverflowers, We have an electron app, with a JSON DB for persisting the app's state while offline. When the app syncs (to submit new actions & fetch new data), a new JSON is created from the server(Django), which replaces the one previously being used from the electron app. All good up to now, the app has had lots of usage, until one of the features started exploding the size of the JSON response. For additional context, serialising the response object to a JSON object on the server can take up to ~30sec, which will grow even more given that data adds up. At the moment we were thinking that our best bet is to introduce websockets, move the JSON generation in the background, and send a message to the app once its completed. Since i'm not very experienced with offline apps i wonder, is this a legit solution? Are we on the right path or at there alternatives? Isn't there a standard pattern of handling this type of issues? We've also thought about a diff sync, which would only include a small portion of the JSON DB every time in the response (e.g by updated_at) but then what … -
Django PasswordResetForm Not Sending Emails to Users with Unusable Passwords
enter image description here In my Django application, I am using the PasswordResetForm to allow users to reset their passwords. However, I noticed that users with unusable passwords do not receive password reset emails. The get_users method in PasswordResetForm filters out these users. The Django documentation states: The get_users method in the PasswordResetForm also filters out users with an unusable password, so those users don’t get emails either. You’ll have to either assign some type of password to those users or override that method in the form to not filter out by that condition. Additionally, I receive a "200 OK" response and see the log entry GET /password-reset/done/ HTTP/1.1" 200 6626, but the emails are not being sent. How can I resolve this issue? Specifically, how can I either: Assign a usable password to users who have an unusable password. Override the get_users method in PasswordResetForm to include users with unusable passwords. -
Razor Pay Not Calling CallBack URL Python Django
So basically, razorpay popup is opening, payment being success but the callback url isn't getting called: var options = { "key": data.razorpay_key, "amount": data.amount, "currency": data.currency, "name": "BusinessCard4U", "image": "{{websitelogo.image.url}}", "description": "Payment for digital card subscription", "order_id": data.razorpay_order_id, "callback_url": "{% url 'PaymentSuccess' %}", "handler": function (response){ // Handle Razorpay success callback }, "theme": { "color": "#5EB9F0" }, }; This is data i am passing... it has callback url as you can see... but neither anything is getting printed, nor it's being called. I tried using redirect: true variable to see if that works but that made the payment failed. Thank You! -
Regex Pattern to allow alphanumeric and square brackets with text insde it
i am using regex to allow alphanumeric, underscore, hyphen and square brackets in a text box. regex i am using to validate input is r'^[a-zA-Z0-9_\-\[\] ]*$. i need to modify the regex such that if empty brackets are given it should return false. Sample cases "Your message here" - Valid "Your [text] message here" - Valid "your_text_message [text]" - valid "Your [] message here" - Invalid "[] message" - Invalid -
django-simple-history How display related fields in the admin panel?
I use django-simple-history.I keep the historical table of the product and the price, the price is associated with the product and an inlane is added to the admin panelю I want to display in the admin panel in the product history records of the stories of related models (price). How can I do this? And that the fields changed would be displayed my model class Product(models.Model): article = models.PositiveIntegerField() history = HistoricalRecords() class Price(models.Model): prod = models.OneToOneField( Product,) price_supplier = models.FloatField() history = HistoricalRecords() my admin class PriceInline(admin.TabularInline): model = Price class ProductAdmin(SimpleHistoryAdmin): inlines = [ PriceInline,] admin.site.register(Product, ProductAdmin) enter image description here enter image description here I tried to set it up via history_view() and get_history_queryset() to receive objects of another model and I received them, but I do not understand how to embed them in the render so that both changes in the product model and changes in the price model would be reflected, and at the same time the fields that changed were corresponding to their models. or is there another method to achieve this result -
How can I paginate by month in vue.js?
I write a project in django and vue.js. In vue.js I have this: <div class="row"> <div class="col-xl-4 col-sm-6 mb-3" v-for="object in personWorkingScheduleData" :key="object.id"> <div class="card mb-5 h-100" style="border:1px solid #eff2f7; padding: 12px; height: 300px;"> <div class="card-body"> <div class="row"> <div class="col-lg-3"> <div class="text-lg-center"> <div class="mt-3"> <label>Night time</label> <b-form-checkbox :checked="object.is_night_shift" @input="object.is_night_shift = $event" :disabled="!object.can_change" class="mb-3 custom-checkbox" plain></b-form-checkbox> </div> </div> </div> <div class="col-lg-9"> <div> <div class="mt-3"> <label>Days</label> <multiselect :disabled="!object.can_change" required :options="weekdayOptions" :value="extractWeekdays(object.weekdays)" track-by="id" label="weekday" multiple placeholder="Choose days" selectLabel="Choose day" selectedLabel="selected" :max-height="200" @input="handleMultiselectChange($event, object)"> </multiselect> </div> <div> <ul class="list-inline mb-0"> <li class="list-inline-item me-3"> <h5 class="font-size-14" data-toggle="tooltip" data-placement="top" title="From" > <label class="mt-3">From*</label><br> <i class="bx bx-calendar me-1 text-muted"> <b-form-input class="no-border" :value="object.start_date" :disabled="!object.can_change" @input="object.start_date = $event" id="example-input" type="date" placeholder="YYYY-MM-DD" autocomplete="off"></b-form-input> </i> </h5> </li> <li class="list-inline-item me-3"> <h5 class="font-size-14" data-toggle="tooltip" data-placement="top" title="To" > <label class="mt-3">To*</label><br> <i class="bx bx-calendar me-1 text-muted"> <b-form-input class="no-border" :value="object.end_date" :disabled="!object.can_change" @input="object.end_date = $event" id="example-input" type="date" placeholder="YYYY-MM-DD" autocomplete="off"></b-form-input> </i> </h5> </li> </ul> </div> <ul class="list-inline mb-0" v-if="object.start_time && object.end_time"> <li class="list-inline-item me-3"> <h5 class="font-size-14" data-toggle="tooltip" data-placement="top" title="From" > <label>Start time</label> <br /> <i class="bx bx-time me-1 text-muted"> <b-form-input class="no-border" :value="object.start_time" :disabled="!object.can_change" @input="object.start_time = $event" format="HH:mm" value-type="format" type="time" placeholder="hh:mm"></b-form-input> </i></h5> </li> <li class="list-inline-item me-3"> <h5 class="font-size-14" data-toggle="tooltip" data-placement="top" title="From" > <label>End time</label> <br /> <i class="bx … -
Testing concurrency ability of a Django app
Let's suppose I have a Django app named MyApp in which I have a Django model called MyModel. This model has a method called process. The database is Postgresql so it allows concurrent queries. What I need to do is to test if the MyModel.process() method can run simultaneously without problem. So, in my tests, when I do class test_smtg(TestCase): def setup(self): self.my_model = MyModel() self.my_model.save() def test_single_processing(self): self.my_model.process() It processes successfully. However, when I do this instead: import threading class test_smtg(TestCase): def setup(self): self.my_model = MyModel() self.my_model.save() def test_concurrent_processing(self): thread = threading.Thread(target=self.my_model.process) thread.start() It immediately reports me an error, such that the ID of my_model cannot be found in table myapp_mymodel. Why is that? Why is the program not able to see the object in the database while running on a separated thread? And what can I do to still test if the concurrency works whitout crashing my tests? -
How to fetch data with the given order from the database ? (django)
I have a model in which there are different fields of data, and a field of "section-order" is given. now i want to fetch that data into the bootstrap accordians with respect to the "section-order". **MODELS ** model.py image VIEWS views.py code on the home page, once the user clicks on any link it reidrects to the casestudy page. -
Undoing a migration for a duplicate field
We have had a duplicate field added to of our Django Wagtail models which has confused the migration system. The following was added to one of the models while back along with a migration that added a singular instance of the field: stream = fields.StreamField( who_fund_blocks, blank=True, verbose_name="Additional content", ) stream = fields.StreamField( who_fund_blocks, blank=True, verbose_name="Additional content", ) This all seemed to be fine, and the project continued with new fields and migrations being added elsewhere without any problem. Then the duplicate field was spotted and removed from the models page. Now, if we try to add a field on some model and a migration for it, the migration is created but doesn't complete, although there are no errors that directly imply it has failed: (.venv) development ➜ app 🐟 manpy migrate /root/.cache/pypoetry/virtualenvs/.venv/lib/python3.10/site-packages/wagtail/utils/widgets.py:10: RemovedInWagtail70Warning: The usage of `WidgetWithScript` hook is deprecated. Use external scripts instead. warn( System check identified some issues: WARNINGS: ?: (urls.W005) URL namespace 'freetag_chooser' isn't unique. You may not be able to reverse all URLs in this namespace ?: (urls.W005) URL namespace 'pagetag_chooser' isn't unique. You may not be able to reverse all URLs in this namespace ?: (urls.W005) URL namespace 'sectiontag_chooser' isn't unique. You may not … -
Gunicorn Error: ModuleNotFoundError - No module named 'weatherapp.wsgi'
I'm having some trouble deploying my Django application on Heroku using Gunicorn, and I could really use some assistance. Here's some background information about my project: Project Name: weatherapp Procfile web: gunicorn weatherapp.wsgi:application --log-file - wsgi.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'weatherapp.settings') application = get_wsgi_application() Error Message Traceback (most recent call last): File "/app/.heroku/python/lib/python3.12/site-packages/gunicorn/arbiter.py", line 609, in spawn_worker ... ModuleNotFoundError: No module named 'weatherapp.wsgi' Relavent code in settings.py WSGI_APPLICATION = 'content_aggregator.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),) django_heroku.settings(locals()) MEDIA_URL = '/imgs/' MEDIA_ROOT = BASE_DIR / 'imgs' It seems like Gunicorn is unable to locate the weatherapp.wsgi module during the deployment process. I've double-checked my project structure and everything seems to be in order. Could anyone please provide some guidance on what might be causing this issue and how I can resolve it? Any help would be greatly appreciated. Thanks in advance! Started the Gunicorn server with the command gunicorn weatherapp.wsgi:application --log-file -. But no changes -
Mulitple summernote instances
I have a web page were I have multiple summernote instances in it. I have 4 textareas with different ids. I run $("textarea").each(function () { $(this).summernote({ height: 240, toolbar: [ ['font', ['bold', 'underline', 'clear']], ['para', ['ul', 'ol']], ['insert', ['link']], ['view', ['help']] ] }); }); code to convert textareas to summernote instances. Now I want to access code of a specific one. How to do so? For further information my backend is django and textarea's are generated by multiple forms. The only difference is the form I have will not send the request to the backend using a regular html form. Instead I'm trying to send the request using axios. Note when I try to access textarea's value using it's id: let description = $("#{{ form_invoice.description.auto_id }}").val(); or let description2 = $("#{{ form_brand.description.auto_id }}").val(); I always get the first form's description on the page. -
Django Allauth Google Sign-In not working
I am trying to get a custom form to work with Google via the django-allauth[socialaccount] package but when clicking on the Google Sign-In button, I am getting the ?process=login query string appended to the URL, but nothing else. I have followed the examples available in the official repo and in particular this partial template that I copied in part in my own template: {% load i18n %} {% load allauth %} {% load socialaccount %} {% get_providers as socialaccount_providers %} {% if socialaccount_providers %} {% if not SOCIALACCOUNT_ONLY %} {% element hr %} {% endelement %} {% element h2 %} {% translate "Or use a third-party" %} {% endelement %} {% endif %} {% include "socialaccount/snippets/provider_list.html" with process="login" %} {% include "socialaccount/snippets/login_extra.html" %} {% endif %} My template: {% extends "base.html" %} {% load allauth socialaccount %} {% load i18n %} {% block body_class %}bg-white rounded-lg py-5{% endblock %} {% block content %} <div class="flex justify-center items-center min-h-screen"> <div class="card w-96 bg-base-100 shadow-xl"> <div class="card-body"> {% get_providers as socialaccount_providers %} {% if socialaccount_providers %} {% include "socialaccount/snippets/provider_list.html" with process="login" %} {% include "socialaccount/snippets/login_extra.html" %} {% endif %} </div> </div> </div> {% endblock content %} views.py from django.shortcuts import render from … -
Heroku Postgres database error: "server does not support SSL, but SSL was required"
I am trying to enable pgbouncer to experiment with managing number of connections to my app. I followed this guide, but am seeing the following error when the app hits the database. connection to server at "127.0.0.1", port 6000 failed: server does not support SSL, but SSL was required My Procfile is as follows: web: bin/start-pgbouncer-stunnel gunicorn backend.wsgi release: python manage.py migrate The error does not appear when I omit the bin/start-pgbouncer-stunnel part In settings.py, I have my DATABASES variable configured like this: if env.get("DJANGO_DEVELOPMENT"): DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql", "OPTIONS": { "service": env.get("DATABASE_SERVICE"), }, } } else: DATABASES = { "default": dj_database_url.config( conn_max_age=500, ssl_require=True ) } However, I notice that the error page lists the DATABASES variable, and this includes sslmode': 'require: DATABASES {'default': {'ATOMIC_REQUESTS': False, 'AUTOCOMMIT': True, 'CONN_HEALTH_CHECKS': False, 'CONN_MAX_AGE': 600, 'ENGINE': 'django.db.backends.postgresql', 'HOST': '127.0.0.1', 'NAME': 'db1', 'OPTIONS': {'sslmode': 'require'}, 'PASSWORD': '********************', 'PORT': 6000, 'TEST': {'CHARSET': None, 'COLLATION': None, 'MIGRATE': True, 'MIRROR': None, 'NAME': None}, 'TIME_ZONE': None, 'USER': 'zvchpwwqszbgax'}} Have I configured something incorrectly? I assume that Heroku enables SSL for the attached Postgres database, and see it as "required" seems like the correct setting is enabled. -
Cannot access LoadBalancer service of Django deployment on EKS cluster
I have a containerized Django application that was successfully deployed (imperatively) to an EKS cluster. I've used the following commands: kubectl create deployment announcements --port=127 --image=public.ecr.aws/x7a1r0o7/announcements-dev --port=127 [gunicorn exposes the container on port 127. If I exec into the pod, it works, and a curl for localhost:127 gives me the html of the page] Then I create the service using kubectl expose deployment/announcements --type=LoadBalancer --port-127 I tried different ports like 80 and 8000 when exposing the deployment. I've also verified that the Pod has the files and the internal curl shows the application is running. For some reason, when I kubectl get svc and use the external IP (an AWS ELB web address) I am unable to see the application. Nothing is served. Any insight would be appreciated. -
django not showing RAW SQL with sqlmigrate
I'm trying to get the RAW SQL from a migration and it only prints begin and commit. I'm modify a model, adding the middle_name field class User(AbstractBaseUser): email = models.EmailField(max_length=200, blank=False, unique=True) first_name = models.CharField( max_length=200, blank=False, verbose_name="nombre" ) middle_name = models.CharField( max_length=200, blank=True, verbose_name="segundo nombre" ) It creates the migration 0007_user_middle_name.py # Generated by Django 3.2.23 on 2024-06-10 16:15 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('biglifeapp', '0006_biglifesetting_new_field'), ] operations = [ migrations.AddField( model_name='user', name='middle_name', field=models.CharField(blank=True, max_length=200, verbose_name='segundo nombre'), ), ] but when I run python manage.py sqlmigrate my_app 0007 --database=default it only prints `BEGIN; -- -- Add field middle_name to user -- COMMIT; this should print something like `BEGIN; -- -- Add field middle_name to user -- alter table user add column middle_name (...) COMMIT; I saw 2 questions on stackoverflow, but none of those was the case for this case, the db does indeed change, I'm adding a new column to it For some migrations, why `sqlmigrate` shows empty, or the same SQL both directions? in this case, the --database argument is being provided Django sqlmigrate not showing raw sql