Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Form Field Filtering Issue: Unable to Filter Foreign Keys to Show Only User-Created Content
I'm having some issues working with filters on the forms of my Django project. This the the form that i am using, and the field "Company client" was sopposed to be showing only the companies that have been created by the user logged in, but once i filter using: self.fields['company_client'].queryset = ClientCompany.objects.filter(user=self.user) It does not show any company at all. And when i do not use the filter, it shows the companies that any user have created. forms.py class ClientContractForm(ModelForm): clausules = forms.CheckboxSelectMultiple() work_order = forms.CharField(required=True, label='Ordem de serviço', widget=forms.TextInput(attrs={'class': 'form-control'})) contract_name = forms.CharField(required=True, label='Nome do contrato', widget=forms.TextInput( attrs={'class': 'form-control', 'placeholder': 'Insira o nome do seu contrato'})) address = forms.CharField(required=True, label='Endereço do contrato', widget=forms.TextInput( attrs={'class': 'form-control', 'placeholder': 'Insira o endereço do contrato'})) installments = forms.CharField(required=True, label='Parcelas', widget=forms.TextInput( attrs={'class': 'form-control', 'placeholder': 'Insira o número de parcelas do contrato'})) items = forms.CharField(required=True, label='Itens do contrato', widget=forms.TextInput( attrs={'class': 'form-control', 'placeholder': 'Insira o número de parcelas do contrato'})) class Meta: model = ClientContract fields = ['work_order', 'contract_name', 'address', 'installments', 'items', 'clausules', 'company_client'] def __init__(self, *args, **kwargs): self.user = kwargs.pop('user', None) super(ClientContractForm, self).__init__(*args, **kwargs) self.fields['clausules'].queryset = Clausule.objects.filter(user=self.user) self.fields['items'].queryset = Item.objects.filter(user=self.user) self.fields['work_order'].queryset = Contract.objects.filter(user=self.user) self.fields['company_client'].queryset = ClientCompany.objects.filter(user=self.user) models.py class ClientContract(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) work_order = … -
Trouble with Django View and URL Configuration for Google AdMob app-ads.txt
I'm currently facing an issue with configuring my Django application published in linode server using Nginx. My issue is in the app-ads.txt file for Google AdMob. I have set up a view in my views.py and added the corresponding URL pattern in urls.py as follows: views.py @require_GET def ads_txt(request): content = 'google.com, pub-*****************, DIRECT, ************' return HttpResponse(content, content_type="text/plain") urls.py from django.urls import path from .views import ads_txt urlpatterns = [ path('app-ads.txt', ads_txt), ] Problem: The view works when I access the URL without a trailing slash (https://www.example.com/app-ads.txt), but I encounter a 404 Not Found error when I include the trailing slash (https://www.example.com/app-ads.txt/). Question: Which is the best configuration to my Django application to handle both cases the app-ads.txt URL? is it with or without the backslash as per the documentation without Additionally, is there anything specific I need to do to ensure that Google's crawler can correctly detect changes to the domain URL? Any insights or suggestions would be greatly appreciated. Thank you! -
How to overcome: Uncaught SyntaxError: Unexpected token ':'
I am receiving this error: script.js:21 Uncaught SyntaxError: Unexpected token ':' My JSON is returning as this: ["2023-10-16", "2023-10-22"] which is valid JSON. The error is pointing to json_script: {{ unavailable_dates|json_script:'unavailable' }} const dates = JSON.parse(document.getElementById('unavailable').textContent); console.log(dates) $('#datepicker').datepicker ({ beforeShowDay: function (date) { var string = jQuery.datepicker.formatDate('yy-mm-dd', date); if ($.inArray(string, dates) != -1) { return [true, 'highlighted-date']; } else { return [true, '']; } }, }); -
ENOENT error : spawn on packaging ElectronJS + ReactJs + Django although it works on development mode, and paths are correct
I am developing a not very common type of desktop applications, it was a web app built by ReactJS and Django, and now I want to convert it into a desktop app, I used ElectronJS for wrapping this web app so it would be a desktop app. First I integrated ElectronJS and ReactJS together, and it worked very smoothly, then on adding the backend (Django), all I wanted was packaging Django (using PyInstaller), adding the Django dist to my electron app dist, and automatically launching the Django server using electron, the rest will all happen through ReactJS and Django, Electron is only to : 1- wrap this as a desktop app. 2- automatically launch the Django server. This worked on the development mode, the django server was launched, and the app worked perfectly, but on the setup of the electron app exe I got this error: error on setup Although the paths are correct, and the same exact way I handled this works on development. **This is my electron.js : ** const { app, BrowserWindow } = require('electron'); const { spawn } = require('child_process'); const path = require('path'); const isDev = require('electron-is-dev'); let mainWindow; function createWindow() { mainWindow = new … -
How to pass value from views.py to display on sendmail
I'm new in sendmail and I want to know if it is possible to pass a context value from views to Forms.py in django sendmail. In the image attached, the context value "getlogincode" is not displaying after I receive an email using sendmail. forms.py: class MyCustomLoginForm(LoginForm): def login(self, *args, **kwargs): html_content = render_to_string('getlogincode_sendmail.html') send_mail(subject="Reliance Assurance Worth", message=html_content, from_email=settings.EMAIL_HOST_USER, recipient_list=[self.user.email], html_message=html_content) # You must return the original result. return super(MyCustomLoginForm, self).login(*args, **kwargs) views.py: def GetLoginCodeView(request): #Get User LOGIN CODE user = Profile.objects.filter(user=request.user) for code in user: getlogincode = code.login_code #print(getlogincode) context = { 'getlogincode': getlogincode, } return render(request, 'getlogincode_sendmail.html', context) Template" getlogincode_sendmail.html <p style="padding-bottom: 16px">Please use the login code below to complete your request.</p> <p style="padding-bottom: 16px"><strong style="font-size: 150%;">{{ getlogincode }}</strong></p> -
Django Quiz- fetching data from database onto specific website
I am having troubles fetching data from my data base. The quiz questions are unpopulated. Chat GPT considers the code for correct. Check if there is anything that interferes with them downloading the questions from the database and displaying them at questionmanager.html. Please take a look and provide me with feedback: views.py # Questions' deletion and edition in separate htmls & urls class QuestionManagerView(LoginRequiredMixin, TemplateView): template_name = "questionmanager.html" context_object_name = "questions" # Fetching data from database: def get_queryset(self): multi_questions = MultiQuesModel.objects.all() single_choice_questions = SingleChoiceQuestion.objects.all() text_questions = SingleQuestion.objects.all() # Debugging: Add print statements to check data print("Multi Questions:", multi_questions) print("Single Choice Questions:", single_choice_questions) print("Text Questions:", text_questions) return {"multi_questions": multi_questions, "single_choice_questions": single_choice_questions, "text_questions": text_questions} # Add this method to handle form submissions def post(self, request, *args, **kwargs): # Process form data here # Debugging: Print form data answers_data = request.POST print("Form Data:", answers_data) # Validate the form form = YourFormHere(request.POST) print("Form is Valid:", form.is_valid()) print("Form Errors:", form.errors) if form.is_valid(): pass # Process the form data return super().get(request, *args, **kwargs) # Or redirect to another page class DeleteMultiQuestionView(DeleteView): model = MultiQuesModel def get_success_url(self): return reverse("question_manager") class DeleteSingleQuestionView(DeleteView): model = SingleChoiceQuestion def get_success_url(self): return reverse("question_manager") class DeleteTextQuestionView(DeleteView): model = SingleQuestion def get_success_url(self): return reverse("question_manager") … -
Django Ignoring TestCases
There are loads of questions with this issue, but whatever I try, it just doesn't want to work. This is the file structure of my project. As you can see, all directories have an init file. Here is the code within that tests.py from django.test import TestCase from django.contrib.auth import get_user_model class UserManagerTestCase(TestCase): def setUp(self): self.data = { "user": { "email": "normal@user.com", "password": "foo", "first_name": "Joe", "last_name": "Doe" } } def test_create_user(self): User = get_user_model() user = User.objects.create_user(**self.data['user']) self.assertEquals(user.email, self.data['user']['email']) self.assertEquals(user.first_name, self.data['user']['first_name']) self.assertEquals(user.last_name, self.data['user']['last_name']) self.assertTrue(user.is_active) Indentation here is a bit messed up. Not sure what causing the tests to be ignored. If I run the test by app namespace (python project/manage.py test project) it works fine, but If I try to run all the tests (python project/manage.py test) it says no tests are found. Thanks. -
error while saving database file foreignkey constrained failed realese restore point
from django.db import models from django.contrib import auth class Publisher(models.Model): name = models.CharField( max_length=50, help_text="The name of the publisher") website = models.URLField(help_text="The website of the publisher") email = models.EmailField(help_text="The email of the publisher") def str(self): return self.name class Book(models.Model): title = models.CharField(max_length=70, help_text="The title of the book") publication_date = models.DateField( verbose_name="Publication date") isbn = models.CharField( max_length=20, verbose_name="ISBN number of the book") publisher = models.ForeignKey( Publisher, on_delete=models.CASCADE) contributores = models.ManyToManyField( 'Contributor', through='BookContributor') def str(self): return self.title class Contributor(models.Model): first_names = models.CharField( max_length=50, help_text="The first names of the contributor") last_names = models.CharField( max_length=50, help_text="The last names of the contributor") email = models.EmailField(help_text="The email of the contributor") def str(self): return self.first_names class BookContributor(models.Model): class ContributionRole(models.TextChoices): AUTHOR = 'AUTHOR', 'Author' CO_AUTHOR = 'CO_AUTHOR', 'Co-author' EDITOR = 'EDITOR', 'Editor' CO_EDITOR = 'CO_EDITOR', 'Co-editor' book = models.ForeignKey(Book, on_delete=models.CASCADE) contributor = models.ForeignKey(Contributor, on_delete=models.CASCADE) role = models.CharField(verbose_name="Contribution role", choices=ContributionRole.choices, max_length=20) class Review(models.Model): content = models.TextField(help_text="The review text") rating = models.IntegerField(help_text="The rating the reviewer has given") date_created = models.DateTimeField( auto_now_add=True, help_text="The date and time the review was created") date_edited = models.DateTimeField( null=True, help_text="The date and time the review was edited") creator = models.ForeignKey( auth.get_user_model(), on_delete=models.CASCADE) book = models.ForeignKey( Book, on_delete=models.CASCADE, help_text="The book that this review is for") in my … -
how to detect vpn in django?
I want to find out if a user is using a VPN when a user sends a request to the API (to warn the user that he is using a VPN and to use the API he must turn off the VPN) I get the user's IP using the following code: def get_client_ip(request): x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip_list = x_forwarded_for.split(',') return ip_list[0].strip() return request.META.get('REMOTE_ADDR') But there are different ways to detect the use of VPN by the user, which are limited and also not free Is there a way to solve this problem? -
Pros & Cons of Django-ninja over fastapi [closed]
Coming from Django, I like the "included batteries" of Django like the built in user authentication, admin, etc. But, soemtimes Django and DRF feel a bit much, so I am now trying FastAPI (but not in a production code, yet.) I have seen Django-ninja recommended both on this site and other sites. In theory, it sounds like it's the best of both worlds. But I would like to hear people's experiences, especially if there is anyone who has used both for real projects. What worked really well? And, what issues did you run into? What features did you wish you had (that were in the other)? Thanks for your time. -
How to debug Django views.py?
I am having some issues trying to parse json data from Django views into javascript. I am getting the following error: script.js:29 Error parsing JSON: SyntaxError: Expected property name or '}' in JSON at position 1. I have serialised my data using the built in Django function DjangoJSONEncoder. What im after is a way to see what is being returned by the view. How would i debug this? def customer_booking(request): if request.method == 'POST': customer_form = CustomerForm(request.POST, prefix='customer') booking_form = BookingForm(request.POST, prefix='booking') if customer_form.is_valid() and booking_form.is_valid(): customer = customer_form.save(commit=False) customer.user = request.user customer.save() booking = booking_form.save(commit=False) booking.customer = customer if limit_no_attendees(booking.booking_date, booking.booking_time, booking.number_attending): booking.save() customer_form = CustomerForm() booking_form = BookingForm() messages.add_message(request, messages.SUCCESS, 'Your booking request was successful, please visit your profile to view the status!') else: messages.add_message(request, messages.ERROR, 'Date and time unavailable!') else: customer_form = CustomerForm(prefix='customer') booking_form = BookingForm(prefix='booking') unavailable_booking_dates = unavailable_dates() context = { 'customer_form': customer_form, 'booking_form': booking_form, 'unavailable_dates': unavailable_booking_dates, } return render(request, 'booking.html', context) var dates = JSON.parse("{{ unavailable_dates|safe }}"); $('#datepicker').datepicker ({ beforeShowDay: function (date) { var string = jQuery.datepicker.formatDate('dd-mm-yy', date); if ($.inArray(string, dates) != -1) { return [true, 'highlighted-date']; } else { return [true, '']; } }, }); -
Django-Cms Multilanguage Website "RecursionError at /tr/ maximum recursion depth exceeded" Error
I need help to solve the error in my multilanguage website error RecursionError at /tr/ maximum recursion depth exceeded" Request Method: GET Request URL: http://eldemmedya.com.tr/tr/ Django Version: 4.2 Exception Type: RecursionError Exception Value: maximum recursion depth exceeded Exception Location: /home/ytsejam/.virtualenvs/eldemproduction/lib/python3.11/site-packages/asgiref/local.py, line 81, in _get_storage Raised during: cms.views.details Python Executable: /home/ytsejam/.virtualenvs/eldemproduction/bin/python Python Version: 3.11.3 Python Path: ['/home/ytsejam/.virtualenvs/eldemproduction/bin', '/home/ytsejam/public_html/eldemmedya', '/usr/lib/python311.zip', '/usr/lib/python3.11', '/usr/lib/python3.11/lib-dynload', '/home/ytsejam/.virtualenvs/eldemproduction/lib/python3.11/site-packages'] Error during template rendering In template /home/ytsejam/public_html/eldemmedya/eldemmedya/templates/base.html, error at line 25 maximum recursion depth exceeded 15 <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}"> 16 <link rel="stylesheet" href="{% static 'css/fontawesome.min.css' %}"> 17 <link rel="stylesheet" href="{% static 'css/animate.css' %}"> 18 <link rel="stylesheet" href="{% static 'css/swiper.min.css' %}"> 19 <link rel="stylesheet" href="{% static 'css/odometer.css' %}"> 20 <link rel="stylesheet" href="{% static 'css/style.css' %}"> 21 <link rel="stylesheet" href="{% static 'css/custom.css' %}"> 22 {% render_block "css" %} 23 </head> 24 <body class="cs_dark"> 25 {% cms_toolbar %} I have basically copied the urls.py in the documents admin.autodiscover() # urlpatterns = [ # path("i18n/", include("django.conf.urls.i18n")), # ] urlpatterns = i18n_patterns( re_path(r'^jsi18n/$', JavaScriptCatalog.as_view(), name='javascript-catalog'), ) urlpatterns += staticfiles_urlpatterns() # note the django CMS URLs included via i18n_patterns urlpatterns += i18n_patterns( re_path(r'^admin/', admin.site.urls), re_path(r'^sitemap\.xml$', sitemap, {'sitemaps': {'cmspages': CMSSitemap}}), re_path(r'^', include('cms.urls')), ) in the settings I have added LANGUAGE_CODE = 'en' LANGUAGES … -
Getting logging error while using the custom logger class
I have developed a custom logger class known as ClassNameLogger, which includes an additional parameter called 'className'. I have integrated this specialized logger class into the settings.py by utilizing the logger.setLoggerClass(ClassNameLogger) method. Consequently, when I initiate the server, it successfully commences; however, I am encountering a logging error simultaneously.The error says: --- Logging error --- Traceback (most recent call last): File "C:\Users\z004mtzy\AppData\Local\Programs\Python\Python310\lib\logging\__init__.py", line 440, in format return self._format(record) File "C:\Users\z004mtzy\AppData\Local\Programs\Python\Python310\lib\logging\__init__.py", line 458, in _format return self._fmt.format(**values) KeyError: 'className' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\z004mtzy\AppData\Local\Programs\Python\Python310\lib\logging\handlers.py", line 73, in emit if self.shouldRollover(record): File "C:\Users\z004mtzy\AppData\Local\Programs\Python\Python310\lib\logging\handlers.py", line 196, in shouldRollover msg = "%s\n" % self.format(record) File "C:\Users\z004mtzy\AppData\Local\Programs\Python\Python310\lib\logging\__init__.py", line 943, in format return fmt.format(record) File "D:\ws1\hmi.dashboard\dashboard\custom_logging.py", line 18, in format File "C:\Users\z004mtzy\AppData\Local\Programs\Python\Python310\lib\logging\__init__.py", line 681, in format s = self.formatMessage(record) File "C:\Users\z004mtzy\AppData\Local\Programs\Python\Python310\lib\logging\__init__.py", line 650, in formatMessage return self._style.format(record) File "C:\Users\z004mtzy\AppData\Local\Programs\Python\Python310\lib\logging\__init__.py", line 442, in format raise ValueError('Formatting field not found in record: %s' % e) ValueError: Formatting field not found in record: 'className' Here is my custom_logging.py: import logging class ClassNameLogger(logging.Logger): def __init__(self, name): super().__init__(name) def _log(self, level, msg, args, exc_info=None, extra=None, stack_info=False): if extra is None: extra = {} # Automatically add the class name to … -
Seemingly no connection to Nginx but website error page successfully loads
I have an issue going on that has me completely stumped. I am running a Django Application through Nginx and UWSGI, and a DNS that runs through cloudflare. When I go the website, I receive the proper website error page (the one set in Django). However, there are no logs anywhere, not in Django, UWSGI, or Nginx (even regarding access!). I have no idea how this is routing yet failing to log anything and have no idea where to look to change anything. Just to reiterate: server: Nginx through UWSGI using a python virtual env | App type: Django | DNS provider: Cloudflare | Logs: None found, but should be propagating if things error | Error page: Django applications custom error Will gladly post info or logs if someone points me towards where I should look. We have had this site working properly on a different server using a different OS version (Debian stretch versus our current debian bullseye). Folder names etc have all been copied from there. ** We are running a nonstandard python version, but all research has shown that this should be fine as long as our Virtualenv is setup with the right python version. -
how to connect two model with a common value present in both the models in my view.py and show the merge data in template file in django
I have a model called eligibility check. In that model I have added institute code. I have another model called register, there i have institute name as well as institute code. I want to add a condition so that, all my entries saved in eligibility check get displayed in a table format in my template file along with institute name. I don't have institute name in eligibility check model, so i want to fetch it from register model with a common value institute code , which i have in both models. I tried this, but getting error of The QuerySet value for an exact lookup must be limited to one result using slicing. I want to have a structure of my template like this I have institute code in eligibility table and institute name, institute code in register table. so i want to merge both table with the common parameter which is institute code -
How do I edit commands and see the history in Python/Django shell?
I'm using Django 3 with Python 3.10. I have this dependency bpython==0.21 I use the python shell like so python manage.py shell Is there a way to have a history of the shell commands so that I can access previous commands using the up arrow? Right now, when I press the up arrow I get >>> ^[[A Similarly, if I try an edit a bad command in the shell by using the left arrow to position my cursor over the bad error, I get this weird chararacter sequence ... >>> my_obj = MyObjectt.objects.get(abbrev='ABC')^[[D How do I get a smoother shell experience? -
Django Superuser Permission Issue: "You don’t have permission to view or edit anything" please help! Thankyou
I'm encountering an issue in my Django project where I'm unable to access the admin site as a superuser. When I try to log in as a superuser, I receive the error message: "You don’t have permission to view or edit anything." I've followed the standard steps for creating a superuser and configuring my custom user model, but I can't figure out why this permission issue is occurring. Django administration: Site Administration, You don’t have permission to view or edit anything.* ---------------------------------* for fresh start* deleted migrations deleted db.sqlite3 powershell-> >>Python manage.py makemigrations Migrations for 'auth_app': auth_app\migrations\0001_initial.py - Create model CustomUser >>Python manage.py migrate Operations to perform: Apply all migrations: admin, auth, auth_app, contenttypes, sessions Running migrations: Applying contenttypes.0001_initial... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0001_initial... OK Applying auth.0002_alter_permission_name_max_length... OK Applying auth.0003_alter_user_email_max_length... OK Applying auth.0004_alter_user_username_opts... OK Applying auth.0005_alter_user_last_login_null... OK Applying auth.0006_require_contenttypes_0002... OK Applying auth.0007_alter_validators_add_error_messages... OK Applying auth.0008_alter_user_username_max_length... OK Applying auth.0009_alter_user_last_name_max_length... OK Applying auth.0010_alter_group_name_max_length... OK Applying auth.0011_update_proxy_permissions... OK Applying auth.0012_alter_user_first_name_max_length... OK Applying auth_app.0001_initial... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying admin.0003_logentry_add_action_flag_choices... OK Applying sessions.0001_initial... OK >> python manage.py createsuperuser Email: helloadmin@mail.com Name: helloname Password: Password (again): This password is too short. It must contain at least 8 characters. This password is … -
How to filter objects by foreign key object in Django with filterset_fields?
What I want to do is simply this: Models.py class Business(AbstractUser, PermissionsMixin): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) email = models.CharField(max_length=255, unique=True) username = models.CharField(max_length=40, unique=True, default='undefinedusername') location = models.CharField(max_length=85, unique=True,null=True,blank=True) class Food(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='foods') name = models.CharField(max_length=50, null=True, blank=True) Views.py class FoodByLocationViewSet(viewsets.ModelViewSet): permission_classes = (IsAuthenticated,) queryset = Article.objects.all().order_by('-average_rating') serializer_class = ArticleSerializer filter_backends = [filters.SearchFilter,DjangoFilterBackend] pagination_class = StandardResultsSetPagination filterset_fields = ['name'] I can search foods by its name with using filterset_fields = ['name'] I just want to filter foods by Business' (Parents) location object. How can I do it? -
After creating virtual env the script is not getting activated. Help me out
Project1\django-todo\demoEnv\Scripts\activate.ps1 cannot be loaded because running scripts is disabled on this system. For more information, see about_Execution_Policies at https:/go.microsoft.com/fwlink/?LinkID=135170. At line:1 char:1 demoEnv/Scripts/activate + CategoryInfo : SecurityError: (:) [], PSSecurityException + FullyQualifiedErrorId : UnauthorizedAccess As I am using windows I was going with the command demoEnv/bin/activate, but getting above error -
problem with django after ondrive file movving
does anyway could help me with below ? I tried all i found already and no luck.... Basically some time ago my company enforces use onedrive and all files where moved from my /Desktop to /One Drive/Desktop ... i figured out all how to change all thing to get Django working and python manage runserver works fine but when i try to migrate i got something like below...i am using Pycharm and maybe something in settings of Pycharm is still related with old files location ? venv is using my new onedrive folder but errors in screen are related with my old folder location, really appreciate of any help to fix that problem Pycharm error Checked all Django settings related fixes but no luck for now -
Aggregate not working in prefetched queryset in Django
I have a query that I am trying to aggregate values so I can calculate balances more quickly than querying multiple times to get the values needed. Overall I simply want to be able to run: header_accounts = custom_report.account_tree_header.all() for header_account in header_accounts: for regular_account in header_account.associated_regular_account_tree_accounts.all(): gl_account = regular_account.associated_account_from_chart_of_accounts gl_entries = gl_account.range_gl # range entries # this does not work below... prior_credit = gl_account.old_gl['prior_credit_amount'] prior_debit = gl_account.old_gl['prior_debit_amount'] I get an AttributeError 'dict' object has no attribute '_add_hints' How can I do this? custom_report = AccountTree.objects.select_related().prefetch_related( 'account_tree_total', 'account_tree_regular', Prefetch('account_tree_header', queryset=AccountTreeHeader.objects.select_related( 'associated_account_from_chart_of_accounts', 'associated_total_account_tree_account__associated_account_from_chart_of_accounts' ).prefetch_related( 'associated_regular_account_tree_accounts', Prefetch('associated_regular_account_tree_accounts__associated_account_from_chart_of_accounts__general_ledger', queryset=GeneralLedger.objects.select_related( 'transaction_code', 'accounts_payable_line_item', 'accounts_payable_line_item__accounts_payable_entry', 'accounts_payable_line_item__property', 'accounts_payable_line_item__account', 'accounts_payable_line_item__book', 'accounts_payable_line_item__generated_check', 'journal_line_item', 'journal_line_item__journal_entry', 'journal_line_item__payment_id__code', 'journal_line_item__charge_id__code', 'journal_line_item__payment_id__balance', 'journal_line_item__charge_id__balance', 'journal_line_item__payment_id__balance__unit', 'journal_line_item__charge_id__balance__unit', 'journal_line_item__payment_id__balance__unit__building', 'journal_line_item__charge_id__balance__unit__building', 'journal_line_item__property', 'journal_line_item__account', 'journal_line_item__book', ).filter(Q( accounts_payable_line_item__property__pk__in=property_pks, journal_line_item__property__pk__in=property_pks, _connector=Q.OR, ), date_entered__date__gte=start_date, date_entered__date__lte=end_date).order_by('date_entered'), to_attr='range_gl'), Prefetch('associated_regular_account_tree_accounts__associated_account_from_chart_of_accounts__general_ledger', queryset=GeneralLedger.objects.select_related( 'transaction_code', 'accounts_payable_line_item', 'accounts_payable_line_item__accounts_payable_entry', 'accounts_payable_line_item__property', 'accounts_payable_line_item__account', 'accounts_payable_line_item__book', 'accounts_payable_line_item__generated_check', 'journal_line_item', 'journal_line_item__journal_entry', 'journal_line_item__payment_id__code', 'journal_line_item__charge_id__code', 'journal_line_item__payment_id__balance', 'journal_line_item__charge_id__balance', 'journal_line_item__payment_id__balance__unit', 'journal_line_item__charge_id__balance__unit', 'journal_line_item__payment_id__balance__unit__building', 'journal_line_item__charge_id__balance__unit__building', 'journal_line_item__property', 'journal_line_item__account', 'journal_line_item__book', ).filter(Q( accounts_payable_line_item__property__pk__in=property_pks, journal_line_item__property__pk__in=property_pks, _connector=Q.OR, ), date_entered__date__lte=start_date).aggregate(prior_credit_amount=Sum('credit_amount'), prior_debit_amount=Sum('debit_amount')), to_attr='old_gl'), # TODO: GRAB THE ENTRIES FROM PRIOR SO I DO NOT HAVE TO CALL SO MANY SLOW QUERIES LATER )), ).get(pk=custom_report.pk) -
Chatterbot- multiple custom adapters don't work
I'm using the django integration. settings.py CHATTERBOT = { 'name': 'chatbot0', 'storage_adapter': "chatterbot.storage.SQLStorageAdapter", 'logic_adapters': [ 'chatterbot.logic.BestMatch', #custom adapters 'chatbot.adapters.adapter_1', 'chatbot.adapters.adapter_2', ] } But adapter_2 doesnt work unless I remover adapter_1, and vise versa. What is the problem? -
Django tests fails if I add a Foreign Key to custom Default User Model even if referenced data table should be prepulated during migration
I Have a default user Model class User(models.model) nation = ForeignKey(Nation, on_delete=CASCADE, related_name='users', default='en', null=True) The initial migration for Nation model is prepulated in this way: def populate_table(apps, schema_editor): nation_model = apps.get_model('nations', 'Nation') nation_model.objects.create(name=en, ....) class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( .... ), migrations.RunPython(populate_table) ] This totally works fine in normal runs, but tests fail. This is my logs: Synchronizing apps without migrations: Creating tables... Creating table auth_permission Creating table auth_group Creating table nations_nation .... Running migrations: No migrations to apply. Traceback (most recent call last): No migrations to apply. Traceback (most recent call last): ... Traceback (most recent call last): ... File "/python3.10/site-packages/guardian/management/__init__.py", line 32, in create_anonymous_user User.objects.using(kwargs['using']).get(**lookup) File "/python3.10/site-packages/django/db/models/query.py", line 435, in get raise self.model.DoesNotExist( mymodule.models.User.DoesNotExist: User matching query does not exist. During handling of the above exception, another exception occurred: DETAIL: Key (nation_id)=(en) is not present in table "nations_nation". I tried to put a breakpoint where User.save() is called, and there I tested if some nations exist in the database, and I got nothing. So to me, it is clear that Django is trying to create a user, before running the Nation migration -
How can I access properties of a foreign key field in django?
In my Django application, I have 2 models: Product and Image. A product can have many images and an image can only belong to a single product. I want to be able to create a sub-folder for the images of a product with the name of the product itself when images of a product are uploaded. So, in the Image model, I need to access the title of the product. Here is my code: class Product(models.Model): title = models.CharField(max_length=255) slug = models.SlugField(unique=True, blank=True, allow_unicode=True) class Image(models.Model): name = models.CharField(max_length=255, null=True, blank=True) product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='images') image = models.ImageField(upload_to=f'product_images/{product.title}/') In the Image model, I have an "image" field which is of type ImageField in which I want to get the title of the product. I get the following error: 'ForeignKey' object has no attribute 'title' How can i access the title of the product inside the Image model? Thanks -
How to overcome "Object of type date is not JSON serializable"?
I am building a booking system, currently i am trying to have unavailable dates displayed in red on a jQuery datepicker. I have composed a view that gets the unavailable dates and saves this to an array. When trying to parse into JavaScript I am getting the following error: "Object of type date is not JSON serializable". I have seen this answered on here, however the solutions I have tried do not seem to be working. In particular I have tried the answers given here: How to overcome "datetime.datetime not JSON serializable"? def unavailable_dates(): confirmed_bookings = Booking.objects.filter(booking_status=1) bookings_max_attendees = confirmed_bookings.values( 'booking_date', 'booking_time').annotate( attendees=Sum('number_attending')).filter(attendees=20) unavailable_dates = [] for booking in bookings_max_attendees: unavailable_dates.append(booking['booking_date']) return unavailable_dates # https://stackoverflow.com/questions/77218397/how-to-access-instances-of-models-in-view-in-order-to-save-both-forms-at-once?noredirect=1&lq=1 def customer_booking(request): if request.method == 'POST': customer_form = CustomerForm(request.POST, prefix='customer') booking_form = BookingForm(request.POST, prefix='booking') if customer_form.is_valid() and booking_form.is_valid(): customer = customer_form.save(commit=False) customer.user = request.user customer.save() booking = booking_form.save(commit=False) booking.customer = customer if limit_no_attendees(booking.booking_date, booking.booking_time, booking.number_attending): booking.save() customer_form = CustomerForm() booking_form = BookingForm() messages.add_message(request, messages.SUCCESS, 'Your booking request was successful, please visit your profile to view the status!') else: messages.add_message(request, messages.ERROR, 'Date and time unavailable!') else: customer_form = CustomerForm(prefix='customer') booking_form = BookingForm(prefix='booking') unavailable_booking_dates = unavailable_dates() dataJSON = json.dumps(unavailable_booking_dates) context = { 'customer_form': customer_form, 'booking_form': booking_form, 'data': …