Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to apply custom validation on GenericTabularInline, TabularInline (related objects) in Django admin?
This is a question about GenericTabularInline, TabularInline, and admin.py. models.py class Chapters(models.Model): name = models.CharField(max_length=40, unique=True) class Projects(models.Model): name = models.CharField(max_length=40) class Courses(models.Model): name = models.CharField(max_length=30) is_active = models.BooleanField(default=False) chapters = SortedManyToManyField(Chapters, related_name="courses", blank=True, sort_value_field_name="chapter_number", base_class=CourseChapters) projects = models.ManyToManyField(Projects, related_name="courses", blank=True) # Here comes generic relations class QuestionsManager(models.Manager): def active(self): return self.get_queryset().filter(Q(fib__is_active=True) | Q(mcq__is_active=True) | Q(code__is_active=True)) class Questions(models.Model): chapter = models.ForeignKey(Chapters, on_delete=models.CASCADE) content_type = models.ForeignKey(ContentType, limit_choices_to={ "model__in": ["fib", "mcq", "code"]}, on_delete=models.CASCADE ) object_id = models.PositiveIntegerField() fib_mcq_code = GenericForeignKey("content_type", "object_id") objects = QuestionsManager() class CODE(models.Model): name = models.CharField(max_length=36) chapter_question = GenericRelation("questions", related_query_name='code') is_active = models.BooleanField(default=False) class MCQ(models.Model): name = models.CharField(max_length=36) chapter_question = GenericRelation("questions", related_query_name='mcq') is_active = models.BooleanField(default=False) class FIB(models.Model): name = models.CharField(max_length=36) chapter_question = GenericRelation("questions", related_query_name='fib') is_active = models.BooleanField(default=False) admin.py class QuestionsChaptersInlineForm(forms.BaseInlineFormSet): def clean(self): pass class QuestionsChaptersInline(admin.TabularInline): model = Questions formset = QuestionsChaptersInlineForm extra = 0 readonly_fields = ['content_type', 'object_id', 'is_active', "modify"] def has_add_permission(self, request, obj): return False def has_delete_permission(self, request, obj): return False class ChapterAdminForm(forms.ModelForm): class Meta: model = Chapters fields = '__all__' def clean(self): cleaned_data = super().clean() if cleaned_data.get('is_active'): if not self.instance.questions_set.active().exists(): self.add_error('is_active', 'At least one question in this chapter must be active.') return cleaned_data class ChaptersAdmin(ImportExportModelAdmin, ImportExportActionModelAdmin, admin.ModelAdmin): form = ChapterAdminForm inlines = [QuestionsChaptersInline, CoursesChaptersInline] # =========================== class … -
Is there a way to filter multiple class objects in views.py and connect to eachother?
I have a Django project where I want to make 3 menus that can be accesed by clicking the select button in each main_menu(like mainfood) >> menu(pastas) >> items of pastas(bluh bluh) *main_menu is accesed from the homepage* I have created 3 classes in models.py called MainMenu, Menu, Item class MainMenu(models.Model): title = models.CharField(max_length=100) main_slug = models.SlugField(max_length=50,unique=True) created = models.DateTimeField("Date created", default=timezone.now) def __str__(self): return self.title class Menu(models.Model): title = models.CharField(max_length=100) slug = models.SlugField(max_length=50,unique=True) created = models.DateTimeField("Date created", default=timezone.now) main_menus = models.ForeignKey(MainMenu,default="",verbose_name="Menus",on_delete=models.SET_DEFAULT, null=True) def __str__(self): return f"{self.title}||{self.main_menus}" class Meta: ordering = ['-created'] class Item(models.Model): title = models.CharField(max_length=100) price = models.CharField(max_length=12) description = models.TextField(blank=True) created = models.DateTimeField("Date created", default=timezone.now) menus = models.ForeignKey(Menu,default="",verbose_name="Menus",on_delete=models.SET_DEFAULT) def __str__(self): return f"{self.title}||{self.menus}" class Meta: ordering = ['-created'] and I have filtered objects in views.py def menus(request,main_slug): matching_menus = Menu.objects.filter(main_menus__main_slug=main_slug).all() return render( request=request, template_name='Menu.html', context={"objects": matching_menus} ) def items(request,slug): matching_items = Item.objects.filter(menus__slug=slug).all() return render( request=request, template_name='Item.html', context={"objects": matching_items} ) and the urls.py : urlpatterns = [ ... path('<slug:main_slug>', views.menus), path('<str:slug>', views.items), ] it kinda WORKS but only menu is filtered correctly. I can go from MainMenu to Menu and the Menus are filtered correctly, but I CANNOT access the items in the Menus. when I click a menu … -
How to programmatically test Django Auth0 protected api's?
I want to do unit tests for my Django app. I'm using the Django-oauth-toolkit library to protect my views, but I can't test my APIs because they are protected by a Bearer Token. def test_get_meeting_list(self): response = self.client.get('/meetings/') # (I need to pass a token, # but I won't have the token) self.assertEqual(response.status_code, 200) # (AssertionError: 401 != 200) So, how could I test that? I tried to make a fake authentication like the official lib tests https://github.com/jazzband/django-oauth-toolkit/blob/master/tests/test_application_views.py but I realized that's will be very complex. -
Django: How to show an admin user message if correction was made during model save?
I have an app, and am wanting to do some automatic corrections to geometry (GeoDjango with PostGIS) rather than simply reject the save operation, since the corrections are being done after the data is committed to the database through the "MakeValid" database operation. I would like to inform the admin user that the model was corrected and to verify their changed geometry, and this is where I am running into trouble. I am attempting the "MakeValid" through an additional query in the model's "save" method after the initial save has completed, but it appears that I can only get the message to show if I move that logic into the admin logic overriding "save_model" to call "obj.save()" and then do my post-processing. Is there a better way to pass information back to the admin view from the model save? -
Django REST Framework Custom Registration Serializer Not Being Called
I'm currently working on a Django project where I'm using Django REST Framework and dj-rest-auth for user authentication. I have a custom user model that includes an additional field for Date of Birth (DOB). I've created a custom registration serializer to handle the additional field during registration. However, I'm running into an issue: my custom serializer is not being called during the registration process, leading to HTTP 400 errors from the frontend. Goal: I want to allow users to register by providing an email, password, and DOB. Problem: When I attempt to register a user from the frontend, I receive a HTTP 400 error. I'm also noticing that print statements in my custom registration serializer aren't showing up in the console logs, which leads me to believe it's not being called at all. What I've tried: I have tried to override the registration process in dj-rest-auth by providing a custom serializer, and configuring REST_AUTH_REGISTER_SERIALIZERS in my settings. I've also checked my URL routing and it seems to be correct. Here are the key sections of my code: models.py from django.contrib.auth.models import AbstractUser, BaseUserManager from django.db import models from django.utils.translation import gettext as _ class CustomUserManager(BaseUserManager): def create_user(self, email, password=None, **extra_fields): … -
Django tests: model name cannot be resolved, although site works
I have a website written in Django. Apart from main app, I have one called app and other users. In users I have implemented my CustomUser model, which I am also using inside models for app. When I run the website, it all works fine; however when I tried to create tests for the app I get: ValueError: Related model 'users.customuser' cannot be resolved (even though tests.py are empty now). And obviously, in app/tests.py I do from .models import CustomUser. I tried looking at the order of imports in settings.py but it seemed right to me: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'users', 'app', ] I have also done migrations for both apps. -
Django testing a simple model with Foreign Key and UpdateView
Two very simple models from django.db import models class Location(models.Model): name = models.CharField(max_length=255) location_number = models.CharField(max_length=30, unique=True) def __str__(self): return self.name class Project(models.Model): location = models.ForeignKey(Location, on_delete=models.CASCADE, to_field='location_number', db_column='location_number', related_name='projects', verbose_name='Standort') name = models.CharField(max_length=255) slug = models.SlugField(unique=True) def __str__(self): return self.name with an UpdateView from .models import Project from django.views.generic import UpdateView class ProjectUpdateView(UpdateView): model = Project fields = "__all__" slug_url_kwarg = 'project_slug' slug_field = 'slug' should be tested with this simple test: from django.test import TestCase from django.urls import reverse from .models import Project, Location from urllib.parse import urlencode from django.utils.http import urlencode class ProjectUpdateTest(TestCase): def setUp(self): self.location = Location.objects.create( name='Test Location', ) self.project = Project.objects.create( location=self.location, slug="test", name='Test Project', ) def test_project_update_view(self): # Prepare the data for the form form_data = { 'name': 'Updated Project', 'location': self.location.pk, 'slug': 'test', } # Build the URL for the project detail view url = reverse('update_project', kwargs={ 'project_slug': self.project.slug }) # Encode the form data as form-encoded data encoded_form_data = urlencode(form_data, doseq=True) # Send a POST request to the project update view with the form-encoded data response = self.client.post(url, data=encoded_form_data, content_type='application/x-www-form-urlencoded') # Print form errors, if any form = response.context['form'] print(form.errors) self.project.refresh_from_db() self.assertEqual(self.project.name, 'Updated Project') But it fails with locationSelect a valid … -
how to upload file to server / django rest framework
Thanks to stack overflow, I implemented loading a file in views, but how to make sure that the file gets to the server and data appears in the database. If I upload a file through the admin panel, then everything works fine. I'm testing with postman. Thank you) # urls.py path('api/v1/UploadDataset/', UploadDataset.as_view()), # models.py class Datasets(models.Model): create_at = models.IntegerField(max_length=50) user = models.IntegerField(max_length=50) name_dataset = models.CharField(max_length=255) link_dataset = models.FileField (upload_to=datasets_filename) # serializers.py class UploadDatasetSerializer(serializers.ModelSerializer): class Meta: model = Datasets fields = '__all__' # views.py class UploadDataset(APIView): parser_classes = (MultiPartParser, FormParser ) #parser_classes = [FileUploadParser] def put(self, request, format=None): file_obj = request.FILES['file'] # do some stuff with uploaded file ??? return Response(status=204) -
drf_spectacular.utils.PolymorphicProxySerializer.__init__() got an unexpected keyword argument 'context'
I am using a PolymorphicProxySerializer provided by drf_spectacular but I am getting a strange error when attempting to load the schema usage @extend_schema( parameters=[NoteQueryParameters], responses=PolymorphicProxySerializer( component_name="NoteSerializer", serializers=[NoteSerializer, NoteSerializerWithJiraData], resource_type_field_name=None, ), ) def list(self, request, *args, **kwargs): return super().list(request, *args, **kwargs) serializers class CleanedJiraDataSerializer(serializers.Serializer): key = serializers.CharField(max_length=20, allow_null=True) class BugSerializer(serializers.Serializer): failures = serializers.CharField(max_length=10, required=False, allow_null=True) suite = serializers.CharField(max_length=100, required=False, allow_null=True) notes = serializers.CharField(max_length=1000, required=False, allow_null=True) tags = StringListField(required=False, allow_null=True, allow_empty=True) testCaseNames = StringListField(required=False, allow_null=True, allow_empty=True) testCaseIds = StringListField(required=False, allow_null=True, allow_empty=True) jira = CleanedJiraDataSerializer(required=False, allow_null=True) class BugSerializerWithJiraData(BugSerializer): jira = serializers.DictField() class NoteSerializer(serializers.ModelSerializer): bug = serializers.ListField(child=BugSerializer()) class Meta: model = Notes fields = "__all__" class NoteSerializerWithJiraData(serializers.ModelSerializer): bug = serializers.ListField(child=BugSerializerWithJiraData()) class Meta: model = Notes fields = "__all__" Basically, if a boolean query parameter is added to the request, I will inject some dynamic data fetched from the jira api. I am trying to update the api docs to represent to two distinct possible schema PolymorphicProxySerializer.__init__() got an unexpected keyword argument 'context' -
How do I run a python APscheduler independant of subsequent deployments
I have a django application with a python AP scheduler running a specific job. I wish to run the job once every week. There might be subsequent deployments to the application and I do not want the scheduler to reset the jobs every time that happens. Is there any way to provide a past start date or check if a week has elapsed since the last run to ensure that the scheduler jobs run independant of deployments. The scheduler code - from apscheduler.schedulers.background import BackgroundScheduler scheduler = BackgroundScheduler() scheduler.add_job(send_weekly_email, 'interval', weeks=1) scheduler.start() -
Translate jquery ajax code snippet into HTMX or manage to fetch selector value
I built a 3 interdependent select lists using htmx, (country region town) and I managed to fetch the selected town as I have this on the last part <select id="localidades" class="form-control-sm custom-select " name="town" hx-get="{% url 'query_for_properties' %}" hx-trigger="change" hx-target="#response" required> <option value="">Select municipality</option> {% for z in lista_localidades %} <option value="{{z}}">{{z}}</option> {% endfor %} </select>` Here I fetch it alright (notice that I am calling this function from the above snippet) def query_for_properties(request): town = request.GET.get('town') etc as I need that town value for the next code. However, this next code needs to send the values to different targets and for each target a different value, like, number of cars, number of bikes etc to different selectors.And that is where I get stuck.The htmx docs, as usual everywhere, are only for the very simple scenarios, but if you need something else, you are a goner, stranded. I have no idea how to deal out different values to different targets. So, I tried ajax, and with jquery it was easy to build calls for every selector. However, because I built the interdependent select lists with htmx,ajax query doesn't get the value. Here it goes <script> $(document).ready(function(){ $("#localidades").on({ change: function(){ var … -
DJANGO - Error creating Solr container (java.nio.file.AccessDeniedException)
I'm trying to implement Solr in my Django project, but when I run the Solr container I get an AccessDenied error. Below are the container and haystack settings local.yml solr: image: solr:7.7.1 restart: always ports: - "8983:8983" volumes: - ./index/core:/opt/solr/server/solr/core environment: - SOLR_JAVA_MEM=-Xms512m -Xmx512m - SOLR_HEAP=512m settings.py HAYSTACK_CONNECTIONS = { "default": { "ENGINE": "haystack.backends.solr_backend.SolrEngine", "URL": env("SOLR_URL", default="http://0.0.0.0:8983/solr/core"), "SILENTLY_FAIL": False, "SOLR_TIMEOUT": 10 } } HAYSTACK_SIGNAL_PROCESSOR = "haystack.signals.RealtimeSignalProcessor" error: SolrCore Initialization Failures core: org.apache.solr.common.SolrException:org.apache.solr.common.SolrException: java.nio.file.AccessDeniedException: /opt/solr/server/solr/core/data -
Django project not displaying some components
so I am building a Django web application, and it has a preview section and this preview section is supposed to display a main-experience and additional-experience however when the form is filled, the main-experience is not being displayed, only the additional-experience displays, its as if the main-experience is being filtered out when the additional-experience is being displayed. What should I change in the code, such that both main and additional experiences are displayed in the preview? The associated codes are below. this is the code i have. both the views and the associated html: views.py: @login_required def experience_v(request): if request.method == 'POST': form = ExperienceForm(request.POST) if form.is_valid(): main_experience = form.save(commit=False) main_experience.user = request.user main_experience.is_main_experience = True main_experience.save() additional_experiences = experience.objects.filter(user=request.user).exclude(pk=main_experience.pk) for entry in additional_experiences: exp = experience.objects.create( user=request.user, position=entry.position, company=entry.company, startdate=entry.startdate, enddate=entry.enddate, roles=entry.roles ) return redirect('education') else: form = ExperienceForm() return render(request, 'experience.html', {'form': form}) @login_required def preview(request): personal_info = personalinfo.objects.filter(user=request.user).last() main_experience = experience.objects.filter(user=request.user, is_main_experience=True).first() additional_experiences = experience.objects.filter(user=request.user).exclude(pk=main_experience.pk) if main_experience else [] educations = education.objects.filter(user=request.user) certs = certificates.objects.filter(user=request.user) return render(request, 'preview.html', { 'personal_info': personal_info, 'main_experience': main_experience, 'additional_experiences': additional_experiences, 'educations': educations, 'certs': certs }) html: <div class="preview-data"> <h2>Experience</h2> <div class="experience-item"> <p><span class="bred">Position</span>: {{ main_experience.position }}</p> <p><span class="bred">Company</span>: {{ main_experience.company }}</p> <p><span … -
I want to create testcase for my project but i got this error
this is the testcase i wrote i have user model that records create only with email confirmation so i have to get email code from EmailConfirm model and i can't pass it to test class as self.email_code. same problem for self.refresh_token and self.user_id class AccountTestCase(APITestCase): def setUp(self): self.email_code = None self.refresh_token = None self.user_id = None return super().setUp() def test_send_email_code(self): url = reverse("accounts:resend_code") data = { 'email': 'testuser@example.com' } response = self.client.post(url, data) self.assertEqual(response.status_code, status.HTTP_200_OK) self.email_code = EmailConfirm.objects.get(email='testuser@example.com').code def test_register(self): url = reverse("accounts:register") data = { 'username': 'testuser', 'email': 'testuser@example.com', 'password': 'testpassword', 'confirm_password': 'testpassword', 'code': self.email_code } response = self.client.post(url, data) self.assertEqual(response.status_code, status.HTTP_201_CREATED) self.user_id = response.data['id'] def test_login(self): url = reverse("accounts:login") data = { 'username': 'testuser', 'password': 'testpassword', } response = self.client.post(url, data) self.assertEqual(response.status_code, status.HTTP_200_OK) self.refresh_token = response.data['refresh'] def test_token_refresh(self): url = reverse("accounts:token_refresh") data = { 'refresh': self.refresh_token } response = self.client.post(url, data) self.assertEqual(response.status_code, status.HTTP_200_OK) self.access_token = response.data['access'] The errors: ERROR: test_register (accounts.tests.AccountTestCase) Traceback (most recent call last): File "C:\Users\Mahdyar Eatemad\OneDrive\Projects\Django\ReelRave API\reelrave\accounts\tests.py", line 40, in test_register response = self.client.post(url, data) File "C:\Users\Mahdyar Eatemad\OneDrive\Projects\Django\ReelRave API\reelrave\venv\lib\site-packages\rest_framework\test.py", line 296, in post response = super().post( File "C:\Users\Mahdyar Eatemad\OneDrive\Projects\Django\ReelRave API\reelrave\venv\lib\site-packages\rest_framework\test.py", line 209, in post data, content_type = self._encode_data(data, format, content_type) File "C:\Users\Mahdyar Eatemad\OneDrive\Projects\Django\ReelRave API\reelrave\venv\lib\site-packages\rest_framework\test.py", line … -
Django-Verify-Email 2.0.3 is not defined even after i installed it
im new to django and im trying to verify users email with Django-Verify-Email 2.0.3. As the documentation says i installed the package and did the same steps as they say but i get this error ModuleNotFoundError: No module named 'verify_email' i checked pip and it's already installed what is the problem is there any steps i should do first like create new app of name verify_email or something? i tryed to reinstall the package but same problem still appear -
How can communicate between HTML docs using Django server running via Google Colab notebook?
I want to simply experiment with this tutorial and reflect inputs of Home.html and reflect the summation of them in result.html using Django Server running in Google Colab notebook. I can run the Django server successfully in Google Colab medium, as shown in this screenshot You just need to manually set ALLOWED_HOSTS = ['colab.research.google.com'] in settings.py once you have installed django library in your cluster. The problem is I can't communicate and reflect the results of Home.html and reflect the summation of them in result.html. I saw in the Tutorial the browser of the local machine when opening HTML docs are: I tried following the set-up, but I still could figure out how I could communicate between HTML docs running by Django in Google Colab medium. I think I'm close to a solution, but I still can't manage it yet. ALLOWED_HOSTS = ['127.0.0.1', 'localhost'] Please feel free to access the notebook for quick troubleshooting. You can create HTML docs quickly using Win notepad and save with .html and upload to notebook if necessary. home.html or download from this link: <h2> Welcome to my Web </h2> <form action="result"> <input type="number" name="no1" placeholder="input1"/> <input type="number" name="no2" placeholder="input2"/> <input type="submit"/> </form> result.html or … -
How can I display data from the current hour of data collection from my Django database using Chart.js on my frontend canvas?
I have an issue displaying data from the current hour of data collection from my django database to my frontend Chart.js . (See code below) I have tried what I found with datetime.now() queries below: #1. This block is the one I am trying to fix from datetime import datetime def datapage(request now = datetime.now() print(now.day) # to check current day output print(now.hour) # to check current hour output # Storing appends labels = [] data = [] queryset = Object.objects.filter(datefield__day=now.day, datefield__hour=now.hour) for entry in queryset: labels.append(entry.date.strftime('Hour %H')) data.append(entry.Datafield) return render(request, 'datapage.html', { 'labels': labels, 'data': data, }) #2 This is the compromise I made but it would display rather the current day's data # Modifying this line queryset = Object.objects.filter(datefield__day=now.day, datefield__hour__lte=now.hour) For Context, here's my script on the chart in the frontend, <body> <div class="flex w-full justify-around g-4"> <div class="w-1/2 shadow-md rounded-lg"> <div class="py-3 px-5 bg-gray-50"> Total Environmental Temperature </div> <canvas class="p-10" id="barChart1"></canvas> </div> </div> </body> <script> const barData = { labels: {{labels|safe}}, datasets: [ { label: 'Bar Dataset', backgroundColor: "rgb(34 211 238)", borderColor: "rgb(34 211 238)", data: {{data|safe}}, }, ], }; const barConfig = { type: 'bar', data: barData, options: { responsive: true, plugins: { legend: { position: … -
How to render django form with validators errors ussing reverse() instea of render() to not duplicate the code actually rendering the whole view?
I am trying to implement forms with validators for the 1st time. I have learned that to actually display validators errors to user after he/she will send the form, in the view function definition that covers POST request processing I have to once again trigger view rendering and pass all saved form data (I am storing that in form variable) to this view. I could do it like that: if form.is_valid: (..) else: return render(request, "auctions/listing-details.html", {"auction_id": auction_id, "bidding_form": form} The problem is, that my view requires bunch of params that are being calculated before render function is being called. So to not have to repeat all the calculation code + render() with all the params, I wanted to use HttpResponseRedirect(reverse()) - in my understanding that would redirect the app to the GET request processing of the view (that includes all the params calculation needed for the view rendering). So for example I could do somethig like: if form.is_valid: (..) else: return HttpResponseRedirect(reverse("auctions:listing_details", kwargs={"auction_id": auction_id, "bidding_form": form},)) BUT with this approach I am getting error Reverse for 'listing_details' with keyword arguments '{'auction_id': 3, 'bidding_form': <BidForm bound=True, valid=False, fields=(bid_amount)>}' not found. 1 pattern(s) tried: ['listing\\-details/(?P<auction_id>[0-9]+)\\Z'] Why is that? Is the only … -
Problem with Python Zappa deploy to AWS Lambda
I couldn't fix the problem with zappa aws lambda deploy. My zappa settings: { "dev": { "aws_region": "us-east-1", "django_settings": "photo_crm.settings", "profile_name": "default", "project_name": "photo-crm", "runtime": "python3.10", "s3_bucket": "photo-crm-zappa", "keep_warm": true, "slim_handler": true, "events": [ { "function": "photo_crm.tasks.destroy_galleries_by_terms", "expression": "cron(0 0 * * ? *)" }, { "function": "photo_crm.tasks.birthdays_telegram_bot", "expression": "cron(0 8 * * ? *)" } ], "remote_env": "s3://bucket_link", "exclude": [".env"] } } and I've got the error in the end: Error: Warning! Status check on the deployed lambda failed. A GET request to '/' yielded a 500 response code. Part of Logs Calling tail for stage dev.. [1685898767317] INIT_START Runtime Version: python:3.10.v5 Runtime Version ARN: arn:aws:lambda:us-east-1::runtime:51b59a64d1fa5125d324f5fe77fbc805ea96f487f1d112fe4bf3f60323b552cb [1685898767841] Instancing.. [1685898772523] [ERROR] ImproperlyConfigured: Error loading psycopg2 module: No module named 'psycopg2._psycopg' Traceback (most recent call last): File "/var/task/handler.py", line 657, in lambda_handler return LambdaHandler.lambda_handler(event, context) File "/var/task/handler.py", line 241, in lambda_handler handler = global_handler or cls() File "/var/task/handler.py", line 150, in __init__ wsgi_app_function = get_django_wsgi(self.settings.DJANGO_SETTINGS) File "/var/task/zappa/ext/django_zappa.py", line 13, in get_django_wsgi return get_wsgi_application() File "/var/task/django/core/wsgi.py", line 12, in get_wsgi_application django.setup(set_prefix=False) File "/var/task/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/var/task/django/apps/registry.py", line 116, in populate app_config.import_models() File "/var/task/django/apps/config.py", line 269, in import_models self.models_module = import_module(models_module_name) File "/var/lang/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], … -
Recreating Stack Overflow's tag input in Django
I've been trying to recreate Stack Overflow's tag input using Django, Alpine, and Tailwind. I managed to create the UI for it but have no idea how to save it to the database via Django's ORM. For context, we're trying to create a matchmaking system. I am using two fields named wins and losses, based on the teams that player X has wins and losses against. The catch is, a team name that's yet to exist can be entered to accommodate future teams to be registered in the database. Using model forms, I've been told to just use a ManyToMany field for the wins and losses field (related to the Team model), but I don't think that'll work because if they are to be translated into forms, they'd just be dropdowns of pre-existing teams. What's the best approach to this? -
How to safely and atomically decrement a counter with Django and PostgreSQL?
I've been reading up on PostgreSQL transaction isolation and how that relates to Django's transaction.atomic() (e.g. this article, PostgreSQL docs), but I'm far from fluent in this topic and I'm not sure I understand what I've read. We've got a PostgreSQL-backed Django app that involves quota objects. Simplified, it's just this: class Quota(models.Model): obj = models.OneToOneField(AnotherModel) count = models.PositiveIntegerField() An instance of this controls how many times a certain operation can be performed against the obj instance. count is initialized to a certain number, and will only ever decrement until it hits zero. Any number of processes/threads can concurrently perform these operations. Basically, we need to atomically decrement (with UPDATE) the count of a single database row without deadlocking and without two processes/threads ever e.g. starting with a count of 100 and both trying to decrement it to 99. My naive approach would be this: with transaction.atomic(): cursor = connection.cursor() cursor.execute('SET TRANSACTION ISOLATION LEVEL SERIALIZABLE') Quota.objects.filter(obj=instance).update(count=F('count')-1) However, I'm not sure if this is subject to this issue, from the linked article: if at COMMIT the database cannot determine that the transaction could have been performed serially with respect to the read/writes of other transactions, then it will fail with a … -
PostgreSQL synchronous stored procedure execution calls from Django Backend
We have 5 PostgreSQL stored procedures and we need them to be chronologically executed in order. We have them listed in one stored procedure: CREATE PROCEDURE main(input_file_path varchar) LANGUAGE 'plpgsql' begin as $$ CALL get_input_file(input_file_path); CALL gla_first_step(); CALL glab_first_step(); CALL jet_first_step(); CALL completeness(); end; $$ We need gla_first_step procedure to be called after get_input_file procedure is done etc We have tried using PERFORM as was suggested by GPT but that brought the following error: ERROR: get_input_file(character varying) is a procedure LINE 1: SELECT get_input_file(input_file_path) ^ HINT: To call a procedure, use CALL. We have tried calling them separately from our backend with a loop of SELECT 1 to simulate a wait but that also did not work. cur.execute('CALL get_input_file(%s)', [path]) result = None while result is None: cur.execute("SELECT 1") result = cur.fetchone() cur.execute('CALL CALL gla_first_step()') result = None while result is None: cur.execute("SELECT 1") result = cur.fetchone() cur.execute('CALL glab_first_step()') result = None while result is None: cur.execute("SELECT 1") result = cur.fetchone() cur.execute('CALL jet_first_step()') result = None while result is None: cur.execute("SELECT 1") result = cur.fetchone() cur.execute('CALL completeness()') result = None while result is None: cur.execute("SELECT 1") result = cur.fetchone() -
What is non_field_errors?
I use forms.Form and forms.ModelForm {% if form.non_field_errors %} {% for err in form.non_field_errors %} <span style="color:darkred;">{{ err }}</span><br /> {% endfor %} {% endif %} Show nothing {{ form.errors }} Show everything,clean_fields() and form. -
I am getting this error django.core.exceptions.FieldError: Unsupported lookup 'icontains' for ForeignKey or join on the field not permitted
Below is models.py: class Author(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) def __str__(self): return self.first_name + ' ' + self.last_name class Book(models.Model): title = models.CharField(max_length=100) rating = models.IntegerField(validators=[MinValueValidator(1), MaxValueValidator(5)]) author = models.ForeignKey(Author,on_delete=models.CASCADE,null=True) is_bestselling = models.BooleanField(default=False) slug = models.SlugField(default="",null=False,blank=True) def get_absolute_url(self): return reverse("model_detail", args=[self.slug]) def __str__(self): return self.title Below is admin.py: class BookAdmin(admin.ModelAdmin): list_display = ('title', 'rating', 'author','is_bestselling',) list_display_links = ('title', 'rating',) search_fields = ('title', 'rating','author',) list_filter = ('rating', 'is_bestselling',) prepopulated_fields = { 'slug': ('title',) } class AuthorAdmin(admin.ModelAdmin): list_display = ('first_name', 'last_name',) list_display_links = ('first_name', 'last_name',) search_fields = ('first_name', 'last_name',) I was trying to search Author in my Books Model. Update: This is answer below : To resolve this issue, you can modify the search_fields attribute to search on related fields of the Author model instead. Here's an updated version of my BookAdmin class: class BookAdmin(admin.ModelAdmin): list_display = ('title', 'rating', 'author', 'is_bestselling',) list_display_links = ('title', 'rating',) search_fields = ('title', 'rating', 'author__first_name', 'author__last_name',) list_filter = ('rating', 'is_bestselling',) prepopulated_fields = { 'slug': ('title',) } In the modified search_fields, 'author__first_name' and 'author__last_name' are used to search on the first_name and last_name fields of the related Author model. The __ syntax is used to traverse the relationship between Book and Author models. By specifying the … -
I cannot pass the values between the methods in classBasedView
I need to pass the bundle and the message values to get_context_data() method, but I cannot figure out how to do it. In this instance the form is valid when I pass it (I can add the better error handling when I figure out why the data gets updated in the post method, but doesn't in the get_context_data()). The form has just 1 filed and it takes the file. Please help. class FirmwareView(FormView, TemplateView): template_name = "dev_tools/firmware_cbv2.html" form_class = forms.InitialFirmwareForm2 def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.bundle = {} self.message = {} def get_success_url(self): return self.request.path def post(self, request, *args, **kwargs): form = self.get_form() if form.is_valid(): if request.FILES: if "file" in request.FILES: file = request.FILES["file"] try: content = json.loads(file.read().decode('utf-8')) folder_name = utils.format_folder_name(content["title"]) units = [] for unit in content["units"]: units.append(unit) self.bundle["units"] = units self.bundle["file"] = { "name": folder_name, "content": json.dumps(content) } self.message = { "type": "info", "content": "The form was parsed successfully" } except Exception as e: print("there was an error", e) return self.form_valid(form) else: print("the form is invalid") return self.form_invalid(form) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["bundle"] = self.bundle context["msg"] = self.message return context def form_valid(self, form): if isinstance(form, forms.InitialFirmwareForm2): return super().form_valid(form)