Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
TypeError: User_info() got unexpected keyword arguments: 'is_staff'
I defined a table named User_info which inherited AbstractBaseUser and PermissionsMixin,when i tried to create superuser in terminal,it ocurred error...Here are my relative codes: I have scrutinized settings.py to insure the database and AUTH_USER_MODEL is correct from django.db import models from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager # Create your models here. class CustomUserManager(BaseUserManager): def create_user(self, account, password=None, **extra_fields): if not account: raise ValueError('用户账户必须被设置') user = self.model(account=account, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_staffuser(self, account, password=None, **extra_fields): # 创建staff用户的逻辑 extra_fields.setdefault('is_staff', True) extra_fields['is_superuser'] = False # 确保staff用户不是超级用户 return self.create_user(account, password, **extra_fields) def create_superuser(self, account, password=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('超级用户必须拥有is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('超级用户必须拥有is_superuser=True.') return self.create_user(account, password, **extra_fields) class User_info(AbstractBaseUser, PermissionsMixin): name = models.CharField(max_length=32) usr_id = models.CharField(max_length=20) number = models.CharField(max_length=12) account = models.CharField(max_length=20,unique=True) gender = models.CharField(max_length=1, choices=[('M', '男'), ('F', '女')], default='M') balance = models.DecimalField(max_digits=10, decimal_places=2, default=0) #is_admin = models.BooleanField(default=False) objects = CustomUserManager() USERNAME_FIELD = 'account' REQUIRED_FIELDS = ['name', 'usr_id', 'number', 'gender'] # 除了密码和用户名之外的必填字段 def __str__(self): return self.account -
Add CSS Class for each tr Element if it contains specific value
I'm trying to add a class to an tr element in a form when the target value is "New Target". So far only the first Element will add the class, but not every other element where the target value is "New Target". This is my HTML-side: <table id="epoch_forms_table" class="epoch_forms_table"> <tr class="title_row"> <th>{% autoescape off %}{% trans "Target name" %}{% endautoescape %}</th> ... <th class="last"></th> </tr> <tr class="value_row{% if epoch_form.errors %} error{% endif %}"> <td></td> <td><label><input type="number" size="13" step="0.001"></label></td> <td class="{{ key }}_unit unit" id="{{ key }}">{{ value }}</td> <td><a href="#" class="button icon remove remove_row_button danger"></a></td> </tr> <tr id="last_value_row" class="last_value_row target_background_color"> <td></td> <td></td> <td class="{{ key }}_unit unit" id="{{ key }}">{{ value }}</td> <td></td> </tr> <tr class="error_row"> {% for field in epoch_form %} <td>{{ field.errors }}</td> {% endfor %} <td></td> </tr> </table> And this is my JavaScript-side: var new_target_element = document.getElementById("last_value_row"); var last_values = []; var index = $("#epoch_forms_table tr.value_row").index(value_row); ... for (let i = 0; i < el.length; i++) { for (let i = 0, cell; cell = new_target_element.cells[i]; i++) { if ($(this).find("td:contains('New target')")) { new_target_element.classList.add("new_target_color"); new_target_element.classList.remove("target_background_color"); } else { new_target_element.classList.add("target_background_color"); new_target_element.classList.remove("new_target_color"); } } } if (last_values[index].length === 0) { last_value_row.find("td:first").html("New target"); } else { ... } } I'm trying … -
Non-Deterministic behavior in PDF library when accessing Django model in between
A Django 4.2 on Python 3.10 application misbehaves sometimes, in a place that should be stateless. If I access the database (postgresql 14 via pcygopg 3.1.18) while working with pypdf 3.17.4, the output document is broken.. in roughly 1 out of 8 attempts. How can I determine the cause of the erratic behavior? The resulting PDF has missing content, so comparing output size is sufficient to determine the bug was triggered: # call as: python3 manage.py minrepro input.pdf import argparse, io from django.core.management.base import BaseCommand from pypdf import PdfReader, PdfWriter from djangoapp.models import DjangoModel def main(fin): pdfout = PdfWriter() pageout = pdfout.add_blank_page(width=200, height=200) for i in range(8): # Note: accessing the database *during* PDF merging is relevant! # without the next line, the problem cannot be reproduced for c in range(31): a = DjangoModel.objects.first() fin.seek(0) for pagein in PdfReader(fin, strict=True).pages: pageout.merge_page(pagein) with io.BytesIO() as fout: pdfout.write(fout) return fout.tell() class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument(dest="pdf", type=argparse.FileType("rb") ) def handle(self, *args, **options): for i in range(30): if i == 0: first_size = main(options["pdf"]) current_size = main(options["pdf"]) if not first_size == current_size: print(f"presumed stateless call was not {i=}, {first_size=} != {current_size=}") This is CPython with insert-ordered dicts, most code should behave the same … -
How to make many-to-many relation for multiple page models with one PageChooser field to select from all of them in Wagtail?
1. Introduction: It is quite easy to make a both side relation between more than two models by creating relation classess to cover all of them. For example: from django.db import models from modelcluster.fields import ParentalKey class NewsToCalendarRelation(models.Model): news = ParentalKey('pages.NewsPage', on_delete=models.CASCADE, related_name='news_calendar_source',null=True) calendar = ParentalKey('pages.CalendarPage', on_delete=models.CASCADE, related_name='news_calendar_target',null=True) class Meta: unique_together = ('news', 'calendar') class NewsToStaticRelation(models.Model): news = ParentalKey('pages.NewsPage', on_delete=models.CASCADE, related_name='news_static_source',null=True) static = ParentalKey('pages.StaticPage', on_delete=models.CASCADE, related_name='news_static_target',null=True) class Meta: unique_together = ('news', 'static') class StaticToCalendarRelation(models.Model): static = ParentalKey('pages.StaticPage', on_delete=models.CASCADE, related_name='static_calendar_source',null=True) calendar = ParentalKey('pages.CalendarPage', on_delete=models.CASCADE, related_name='static_calendar_target',null=True) class Meta: unique_together = ('static', 'calendar') And then to use in page model: class NewsPage(Page): related_news = ParentalManyToManyField('self', blank=True,symmetrical=True) related_calendar = ParentalManyToManyField('pages.CalendarPage', through=NewsToCalendarRelation, blank=True) related_static = ParentalManyToManyField('pages.StaticPage', through=NewsToStaticRelation, blank=True) content_panels = [ AutocompletePanel('related_news', target_model='pages.NewsPage'), AutocompletePanel('related_calendar', target_model='pages.CalendarPage'), AutocompletePanel('related_static', target_model='pages.StaticPage') ] class CalendarPage(Page): related_news = ParentalManyToManyField('pages.NewsPage', blank=True, through=NewsToCalendarRelation) related_calendar = ParentalManyToManyField('self', symmetrical=True) related_static = ParentalManyToManyField('pages.StaticPage', blank=True, through=StaticToCalendarRelation) content_panels = [ AutocompletePanel('related_news', target_model='pages.NewsPage'), AutocompletePanel('related_calendar', target_model='pages.CalendarPage'), AutocompletePanel('related_static', target_model='pages.StaticPage') ] and so for other models… 2. But it would be more efficient to have only one related pages field to choose from all pages. It is no problem to define chooser field for that either PageChooserPanel or AutocompletePanel('related_all', target_model='wagtailcore.Page'). But there is a problem with creating an universal relation between page … -
Optimal Kubernetes Deployment Strategy for Django with Gunicorn (Multi-Process): Fewer Multi-Process Pods vs. One Process per Pod
I'm architecting a Django application to be deployed on Kubernetes, utilizing Gunicorn as the WSGI server with multiple workers configured, essentially adopting a multi-process setup. Given the multi-process nature of my setup, I'm faced with a deployment decision and seeking your experienced opinions on the matter: Deploying Fewer Pods Running Gunicorn with Multiple Workers (Processes) Each: This approach involves deploying a smaller number of pods, where each pod runs a Gunicorn instance configured with multiple workers. My main considerations are around how this setup would affect resource utilization, fault isolation, and resilience of the system as a whole within a Kubernetes environment. Deploying More Pods, Each Running a Single Gunicorn Worker (Process): The alternative is deploying a larger number of pods, with each pod running a Gunicorn instance configured to run a single worker. While I see the potential benefits in terms of fault isolation and scalability, I'm concerned about the overhead and whether this might lead to inefficient resource utilization. I would greatly appreciate insights or experiences related to: Resource Management: How do these approaches compare in terms of resource allocation efficiency and potential overhead in a Kubernetes context? Fault Tolerance and Isolation: Does one strategy offer significant advantages … -
Django-celery-beat send task, worker receive it and don't execute
That's my libs: celery==5.3.6 django-celery-beat==2.5.0 django-celery-results==2.5.1 redis==5.0.1 settings.py: INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "bot_users.apps.BotUsersConfig", "products.apps.ProductsConfig", "categories.apps.CategoriesConfig", "commands.apps.CommandsConfig", "stories_news.apps.StoriesNewsConfig", "posts.apps.PostsConfig", "polls.apps.PollsConfig", "bot_statistics", "xml_import", "rest_framework", "nested_admin", "import_export", "ckeditor", "imagekit", "django_celery_beat", "django_celery_results", ] REDIS_HOST = '127.0.0.1' REDIS_PORT = '6379' CELERY_BROKER_URL = f'redis://{REDIS_HOST}:{REDIS_PORT}' CELERY_BROKER_BACKEND = f'redis://{REDIS_HOST}:{REDIS_PORT}' CELERY_RESULT_BACKEND = 'django-db' CELERY_BEAT_SCHEDULER='django_celery_beat.schedulers:DatabaseScheduler' CELERY_RESULT_EXTENDED = True celery.py: import os from celery import Celery # Set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'src.settings') app = Celery('src') # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django apps. app.autodiscover_tasks() task function (in services.py): @app.task def import_data_from_xml(*args): from .admin import ProductResource from xml_import.models import XMLImportSettings from .formats import XML xml_settings = XMLImportSettings.objects.all().first() logging.info(f'xml_settings:{xml_settings}') folder_path = xml_settings.folder_path logging.info(f'folder_path:{folder_path}') file_name = xml_settings.file_name logging.info(f'file_name:{file_name}') # Полный путь к XML файлу xml_file_path = f"{folder_path}/{file_name}" logging.info(f'xml_file_path:{xml_file_path}') # Создаем экземпляр ресурса resource = ProductResource() logging.info(f'resource:{resource}') xml_formatter = XML() logging.info(f'xml_formatter:{xml_formatter}') with open(xml_file_path, 'r', encoding='utf-8') as xml_file: # Создаем dataset из XML данных data = xml_formatter.create_dataset(xml_file.read()) logging.info(f'data:{data}') # Импортируем данные из XML файла dataset = resource.import_data(dataset=data, raise_errors=True) … -
postgresql 11 to 16 django.db.utils.ProgrammingError
I want to up my version of postgresql to 11 > 16, I change the version in my Dockerfile, I'm in local and I don't have yet important data, I erase the volumes and in django try to re-apply my models everything seems good a this point but, when I try to makemigrations this error appair: django.db.utils.ProgrammingError: relation "account_lib_customers" does not exist LINE 1: ..., "account_lib_customers"."profile" FROM "account_... what I do before that > I erase migrations folder of all app > delete the volume in my docker app account_lib is a lib of my company, may I need to something there? -
Django rest framework in some prebuild methods , so how do I create my own method ? After creating my own method how to use it in code
I have created my own method using the Django rest framework Similar to some prebulid methods in the Django rest framework --->get, post, and another prebulid method. so how can I create my own method? I try to create my own method, but I don't know how to write it. -
How to use Valentina or DBeaver to load/import a .sql dump file (from the development version of a website) to the local version on my computer?
I have a .sql file which is a dump of the data coming from the development version of a website. I want to use that data in the local version of the website's Django backend running on my desktop I can see it at localhost:8000 but in the docker-compose.yml file the db is located at port 5432. What are the steps I need to do using Valentina or DBeaver to load in the data such that that data is what I see in Valentina or DBeaver ? I've already tried loading the dump through right-clicking the name of the database then choosing load dump from the options but I still don't see any data in the database tables. -
Django Table - Single Row if Item is unique
Is there a way to get all the amounts on a single row in HTML if "category name" is unique? According to my code, "category name" is no longer unique because it is being annotated by month. Thank you Data: HTML Output: I want them to be all in one row since they are "Car Payment" class CashFlow(LoginRequiredMixin, AccountContextMixin, TemplateView): model = Transaction template_name = 'transaction_app/cf.html' context_object_name = 'transaction' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) user = self.request.user #-------Dropdown Begins--------- #Get unique years for dropdown distinct_years = Transaction.objects.filter(user=user).dates('transaction_date', 'year') year_choices = [(date.year, date.year) for date in distinct_years] unique_years = list(set(year_choices)) unique_years.sort() context['unique_years'] = unique_years #-------Dropdown Ends----------- #---Get Data From Dropdown Begins--------- selected_year = self.request.GET.get('selected_year') selected_year = int(selected_year) if selected_year else datetime.now().year selected_status = self.request.GET.get('selected_status') #---Get Data From Dropdown Ends----------- #----Get Data for Table Begins------------ # Obtain distinct category names category_names = Transaction.objects.filter( user=user, transaction_date__year=selected_year, status=selected_status ).values_list('category__category_name', flat=True).distinct() # Aggregate data for each distinct category category_sums = [] for category_name in category_names: # Aggregate total amount for each month within the specified year for the current category category_sum_by_month = Transaction.objects.filter( user=user, transaction_date__year=selected_year, status=selected_status, category__category_name=category_name ).annotate( month=ExtractMonth('transaction_date') ).values('month').annotate( total_amount=Sum('amount') ) # Append category name and its monthly sums to category_sums list for … -
Will I need a consumers.py, asgi,py and routing.py using Tradier's websocket API?
So I'm trying to stream market data via the tradier API with websockets. Here are 2 links to the docs: https://documentation.tradier.com/brokerage-api/streaming/websocket-streaming https://documentation.tradier.com/brokerage-api/streaming/wss-market-websocket I'm not too familiar with websockets, so I'm wondering if I need to use django channels and add a consumers.py, asgi.py, and routing.py to stream this market data live to a front end? If the answer is yes, what would I need to add in each of these files? I've tried just having a consumers.py and having the streaming endpoint in urls.py consumers.py: import json import logging import websockets from channels.generic.websocket import WebsocketConsumer from .tradingAPI.tradier import tradierFunctions logger = logging.getLogger(__name__) class TradierStreamConsumer(WebsocketConsumer): async def connect(self): await self.accept() logger.info("WebSocket connection established") uri = "wss://ws.tradier.com/v1/markets/events" async with websockets.connect(uri, ssl=True, compression=None) as websocket: payload = { "symbols": ["SPY", "NVDA"], "sessionid": tradierFunctions.createStreamingSession(), "filter": ["quote"], "linebreak": "true" } await websocket.send(json.dumps(payload)) logger.info(f"Sent payload: {payload}") async for message in websocket: logger.info(f"Received message: {message}") await self.send(text_data=json.dumps({"message": message})) urls.py: urlpatterns = [ ... path('api/tradier/stream', TradierStreamConsumer.as_asgi()), ] I expected continuous JSON data being streamed to the web page, but in reality I get this: Also, this is my console output when I log the info: -
"<Model: ModelInstance>" needs to have a value for field "id" before this many-to-many relationship can be used
Currently getting this error between my UserProfile model and Song model when I try to get all user songs "song = user_prof.songs.all()" and error is the title "<UserProfile: ...>. This is my first time using a through model for two models (Song and Note) and am suspicious. The UserProfile, Song, Notes, and SongNotes instances are all saved and viewable in django admin, however the song_instance does not show any notes, in fact it doesnt even show its notes field im guessing due to the through. Song View class Songs(APIView): def post(self, request, format=None): try: data = self.request.data user_song = data['song'] name = data['name'] user = self.request.user user_prof = UserProfile.objects.get(user=user) song_instance = Song.objects.create(name=name) user_prof.songs.add(song_instance) user_prof.save() for index, pair in enumerate(user_song): note = Note.objects.create(note=pair[0], timestamp=pair[1]) song_note_through = SongNote.objects.create(song=song_instance, note=note, order=index) song_instance.save() return Response({ 'success': 'Song created' }) except Exception as e: print('Songs:post ', e, file=sys.stderr) return Response({ 'error': 'Unable to create song' }) def get(self, request, id='all', format=None): try: if id == 'all': user = self.request.user user_prof = UserProfile(user=user) song = user_prof.songs.all() else: song = Song.objects.get(id=id) serializer = SongSerializer(song) return Response({ 'song': serializer.data}) except Exception as e: print('Songs:get ', e, file=sys.stderr) return Response({ 'error': 'Unable to get song' }) models.py class UserProfile(models.Model): … -
WordPress blog in Subdirectory of Django site on cPanel
I've gone through several similar posts here on StackOverFlow but I can't get it to work. What I want to achieve is to load any url that contains /blog/ with WordPress. I have moved my WordPress instance into a folder called blog (inside public_html) and it loads fine when the Django instance is not active with this .htaccess file in public_html. I have no .htaccess file in the blog folder. <IfModule mod_rewrite.c> RewriteEngine on RewriteCond %{HTTP_HOST} ^(www.)?mysite.com$ RewriteCond %{REQUEST_URI} !^/blog/ RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ /blog/$1 RewriteCond %{HTTP_HOST} ^(www.)?mysite.com$ RewriteRule ^(/)?$ blog/index.php [L] </IfModule> I also changed the WordPress URL and Site Address in the database to mysite.com/blog/ with https:// When I activate the Django instance, I change the .htaccess file to the below. <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteCond %{REQUEST_URI} ^/blog/ RewriteCond %{HTTP_HOST} ^(www.)?mysite.com/blog/$ RewriteRule . /blog/index.php [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . / [L] </IfModule> # DO NOT REMOVE. CLOUDLINUX PASSENGER CONFIGURATION BEGIN PassengerAppRoot "/home/usr/mysite.com" PassengerBaseURI "/" PassengerPython "/home/usr/virtualenv/mysite.com/3.11/bin/python" # DO NOT REMOVE. CLOUDLINUX PASSENGER CONFIGURATION END # DO NOT REMOVE OR MODIFY. CLOUDLINUX ENV VARS CONFIGURATION BEGIN <IfModule Litespeed> SetEnv DEBUG False etc... </IfModule> # DO NOT REMOVE OR MODIFY. … -
ConnectionRefusedError Errno 111 when Django uploaded to Godaddy Server
I dont have any problem in Local host when sending and reciving emails. But when I uploaded the files to the godaddy server, I am getting error when I am trying to send email. I spoke to godaddy support, but it was not helpful. Can someone please let me know the issue. #error ConnectionRefusedError at /support/python python [Errno 111] Connection refused # settings.py BASE_URL = 'https://www.example.com' EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtpout.secureserver.net' EMAIL_PORT = 465 EMAIL_USE_SSL = True EMAIL_HOST_USER = 'support@example.com' EMAIL_HOST_PASSWORD = 'password' DEFAULT_FROM_EMAIL = 'support@example.com' EMAIL_FROM_NAME = 'Support' # in views.py email = EmailMessage( subject, message, settings.EMAIL_HOST_USER, [recipient], reply_to=[request.user.email] # Set the reply-to address ) email.send() Thanks. -
How can one enable a mix of authenticated and unauthenticated websockets using Django Channels?
I'm running a Django application with DRF and Channels and I've configured a number of websockets, one of which I need to be open/insecure. However, all I can figure out is how to enable/disable security at the application level, not at the consumer specific level. Here is the asgi.py configuration: application = ProtocolTypeRouter( { "http": django_application, "websocket": AllowedHostsOriginValidator( AuthMiddlewareStack(URLRouter(websocket_routing.websocket_urlpatterns)) ) } ) Alternatively, to disable the authentication, I can switch the websocket entry to URLRouter(websocket_routing.websocket_urlpatterns) With the DRF views, its easy enough to disable authentication: class WebhookCallEvents(APIView): authentication_classes = [] permission_classes = [] But these properties don't seem to work in a consumer class: class MyConsumer(AsyncWebsocketConsumer): authentication_classes = [] permission_classes = [] How would one enable authentication for some websockets but have it disabled for others within the same application? Looks like this is a duplicate of this question over here: Django Channels 2 websockets multiple AuthMiddlewareStacks However, none of the answers are accepted, so perhaps restating the question will yield some results. -
Django: Views and URLs Configured, but Pages Not Found (404 Error) - only /admin shows
I'm encountering an issue with my Django project. I've set up views and URLs for several pages like 'landing', 'chat', 'impressum', 'sales', 'team', and 'user'. However, when I try to access these pages in the browser, I receive a 404 error indicating that the pages cannot be found. Here's the relevant code I've implemented: from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.landing, name='landing'), path('chat/', views.chat, name='chat'), path('impressum/', views.impressum, name='impressum'), path('sales/', views.sales, name='sales'), path('team/', views.team, name='team'), path('user/', views.user, name='user'), ] # views.py from django.shortcuts import render def landing(request): return render(request, 'landing.html') def chat(request): return render(request, 'chat.html') def impressum(request): return render(request, 'impressum.html') def sales(request): return render(request, 'sales.html') def team(request): return render(request, 'team.html') def user(request): return render(request, 'user.html') # settings.py import os TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'teacherassistant/templates')], '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', ], }, }, ] Despite correctly defining URLs and views, I'm unable to render the respective HTML templates for each page as intended. It seems like there's an issue with how Django is handling the routing.[enter image description here]enter image description here -
Django makemessages i got no such file directory error
(myenv) C:\Users\Boss\OneDrive\İş masası\Onlineshop>py manage.py makemessages -l ru CommandError: errors happened while running msguniq msguniq: error while opening "C:\Users\Boss\OneDrive\Is masasi\Onlineshop\myenv\Lib\site-packages\rosetta\locale\django.pot" for reading: No such file or directory In ubuntu server it works but in local i got this error -
Django reverts model value saved by form in POST (Ajax) when I call query by GET (Ajax)
I have a screen with a datatable with the data and I update the values using ajax and then reload it, but in some cases I save the value through a post request, and then when I make a new query to update the screen using get, the changed values are reverte without any error. View class ManualGetView(View): # get by which I query all values to show in the datatable def get(self, request): items = ConfiguracaoManual.objects.all().order_by('endereco') data = [item.to_dict_json(get_permissoes(RAIZ, request.user)) for item in items] response = {'data': data} return JsonResponse(response) class ManualAltView(View): def get(self, request, request_id): item = ConfiguracaoManual.objects.get(pk=request_id) data = item.get_data() response = {'status': 200, 'data': data} return JsonResponse(response) # post where I update the values def post(self, request, request_id): if request_id: model = ConfiguracaoManual.objects.get(pk=request_id) form = ManualForm(request.POST, instance=model) else: form = ManualForm(request.POST) if form.is_valid(): instance = form.save() # instance.save() if not request_id: Auditoria(usuario=request.user, modelo=RAIZ, mensagem=SUCESSO['incluir']).save() response = {'status': True, 'msg': SUCESSO['incluir']} else: Auditoria(usuario=request.user, modelo=RAIZ, mensagem=SUCESSO['incluir']).save() response = {'status': True, 'msg': SUCESSO['incluir']} else: if not request_id: Auditoria(usuario=request.user, modelo=RAIZ, mensagem=ERRO['alterar']).save() response = {'status': False, 'msg': ERRO['alterar'], 'erros': form.errors} else: Auditoria(usuario=request.user, modelo=RAIZ, mensagem=ERRO['alterar']).save() response = {'status': False, 'msg': ERRO['alterar'], 'erros': form.errors} return JsonResponse(response) JS Script //Function used to update by … -
Django - Create a model that holds aggregated Foreign Key values
I have a Django Model defined as a ServiceEvent, and another defined as Part. class ServiceEvent(Model): date = DateTimeField(null=False, blank=False, db_column='date', default=datetime.now()) vehicle = ForeignKey(Vehicle, on_delete=models.CASCADE) description = TextField(null=True, blank=False, db_column='description') # The contents of the notifications to create for this event. notification_contents = TextField(null=True, blank=False, db_column='notification_contents') # The mileage the event should occur. target_mileage = DecimalField(max_digits=10, decimal_places=2, null=True, blank=False, db_column='target_mileage') # The mileage at the time of the event. event_mileage = DecimalField(max_digits=10, decimal_places=2, null=True, blank=False, db_column='event_mileage') class Part(Model): part_number = CharField(max_length=100, null=False, blank=False, db_column='part_number') description = CharField(max_length=100, null=False, blank=False, db_column='description') price = DecimalField(max_digits=10, decimal_places=2, null=False, db_column='price') service_event = ForeignKey(ServiceEvent, on_delete=models.CASCADE) Since there can be multiple Parts per ServiceEvent, is there a way to store a column in the ServiceEvent table that contains the price of all of the parts added up that belong to a given event? I would like to do this for efficiency however I'm not sure if there is a better approach (like using a mapping table, which may still lead to the same question about the column). FYI: I'm using SQLite currently. Thanks! -
Heroku - Django - How to reduce cool down of keep alive
I have an API that creates a model object whenever an action is true. Slight problem, everytime the API sends some data it creates a connection and these connections dont seem to cool down very quickly. Connections seem to stay on for more than 60 minutes. This results in getting the following error: too many connections for role xxx As a result, I implemented the following code in my prod.py: from .base import * from decouple import config import django_on_heroku # Heroku Settings django_on_heroku.settings(locals(), staticfiles=False) # Adjust database settings import dj_database_url DATABASES['default'] = dj_database_url.config(conn_max_age=450, ssl_require=True) This was implemnted following Heroku's guidlines : https://devcenter.heroku.com/articles/python-concurrency-and-database-connections What I was hoping to achieve here was to have connections lasting a maximum of 45 seconds. (users dont need to spend more than 20 seconds on the site to get what they need). I seem to be missing something. Would you be able to shed some lights? Is there a better practice to ensure connections do not reach their limit? Edit: worth mentioning, I am on the Basic plan. Planning to move to Standard0 when ready for production. I am assuming the plan shouldnt affect the ability to define keep alives. -
Django How to Have an Internal Link on Custom Button Component
I am on DjangoCMS 3.11.3. I am not a Django developer, I primarily do .Net but was asked to help out with CSS and HTML. That went well, so now we are here... We currently have an imported Bootsrap4 Link/Button component that has far more options than the PM wants and than what the end users need. This imported plugin has 2 levels to the Internal Link and the 2nd level is hierarchical (indented) as show below: I seem to be able to have an internal link created in my custom Button component, but it only has a single dropdown of pages (each has a duplicate for some reason, the values of th duplicates are different if that means anything) and they are not indented (hierarchical) at all. I have been googling and such with no real success. I was able to dig into the repos and such to get some of the source code but it was getting insanely deep how far the spaghetti code was going. This is where you come in. I just want a simple component that lets the user pick a page within the CMS. I understand why all of the inheritence and such is … -
Django ORM: Case When not working when output is a Subquery producing a list of Ids?
I've been spending an incredible amount of time today on something I don't understand at all. Let me explain: I have a code similar to this one: puzzle_sequence__puzzles = <a subquery> puzzle_sequence__puzzles_3d = <another subquery> MyModel.objects.add_only_3d_puzzle_sequence().exclude(puzzle__in=Case( When(Q(only_3d_puzzle_sequence=True), then=Subquery(puzzle_sequence__puzzles_3d)), default=Subquery(puzzle_sequence__puzzles) )) which throws an error sqlite3.OperationalError: near "CASE": syntax error django.db.utils.OperationalError: near "CASE": syntax error or django.db.utils.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'CASE WHEN CASE WHEN (`games_play`.`puzzle_sequence_id` IS NOT NULL AND CASE W...' at line 1") depending if I'm on sqlite3 or MariaDB server I've been toying with it for some while now, and it seems that's it's really the Case When statement which raised the issue as both the following statements work well: MyModel.objects.add_only_3d_puzzle_sequence().exclude(puzzle__in=Subquery(puzzle_sequence__puzzles_3d)) MyModel.objects.add_only_3d_puzzle_sequence().exclude(puzzle__in=Subquery(puzzle_sequence__puzzles)) I however don't understand at all why my Case When statement would fail Is there a specific issue if the output_field of a Case When statement should be a list of objects or list of object ids ? PS: as you can see, I'm not using Postgres, so I guess I cannot force output_field=ArrayAgg Thanks in advance -
QUALIFY on a non-window field
As stated here, from 4.2 Django supports fIltering against a window function. I've tried it and Django successfully creates a QUALIFY clause when using a window field in the filter clause. However, if using, let's say, a model field, the predicate is assigned to the WHERE clause. That arises the next problem: qs.annotate( position=Window( expression=RowNumber(), order_by=order_by ) ) obj = qs.get(id=obj.id) # obj.position will always be 1, as WHERE is run before QUALIFY -
This Customer doesn't have any saved payment details
def checkout_payment(request): if request.method == "POST": user = request.user cart_items = Cart.objects.filter(user=user, is_ordered=False) cart_total = sum(float(item.product.discounted_price()) * item.quantity for item in cart_items) # Convert cart_total to the smallest currency unit and then to integer total = int(cart_total * 100) stripe.api_key = settings.STRIPE_SECRET_KEY try: customer = stripe.Customer.create( email=request.user.email, name=request.user.first_name, description='Example charge', ) # payment_intent = stripe.PaymentIntent.create( # ) # creating charge charge = stripe.Charge.create( customer=customer, amount=total, currency="PKR", description='Payment has been charged successfully', source=request.POST.get('stripeToken') ) print(charge) messages.info(request, 'Payment has been successfully') return redirect('checkout_complete') except Exception as e: print(e) return render(request, 'checkout_payment.html') this is my code and why i am getting this error This Customer doesn't have any saved payment details. Attach a legacy Token, Card, Bank Account, or Source to this Customer and then try this request again, or use Payment Intents and Payment Methods instead. -
KeyError in django when i try to migrate
everytime i try to migrate i get KeyError: ('komaki', 'msg') Traceback (most recent call last): File "C:\Users\EXO\Downloads\Compressed\mathematics-main_2\mathematics-main\maths\manage.py", line 22, in <module> main() File "C:\Users\EXO\Downloads\Compressed\mathematics-main_2\mathematics-main\maths\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\EXO\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\core\management\__init__.py", line 442, in execute_from_command_line utility.execute() File "C:\Users\EXO\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\core\management\__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\EXO\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\core\management\base.py", line 412, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\EXO\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\core\management\base.py", line 458, in execute output = self.handle(*args, **options) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\EXO\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\core\management\base.py", line 106, in wrapper res = handle_func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\EXO\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\core\management\commands\makemigrations.py", line 211, in handle loader.project_state(), ^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\EXO\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\db\migrations\loader.py", line 361, in project_state return self.graph.make_state( ^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\EXO\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\db\migrations\graph.py", line 329, in make_state project_state = self.nodes[node].mutate_state(project_state, preserve=False) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\EXO\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\db\migrations\migration.py", line 91, in mutate_state operation.state_forwards(self.app_label, new_state) File "C:\Users\EXO\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\db\migrations\operations\models.py", line 384, in state_forwards state.remove_model(app_label, self.name_lower) File "C:\Users\EXO\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\db\migrations\state.py", line 128, in remove_model del self.models[model_key] ~~~~~~~~~~~^^^^^^^^^^^ KeyError: ('komaki', 'msg') why is thi happening