Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ValueError:The field admin.LogEntry.user was declared with a lazy reference to 'recipes.customuser',but app'recipes'doesn't provide model 'customuser'
This is the Custom user model I also declared in settings AUTH_USER_MODEL="recipes.CustomUser" still I face this error ValueError:The field admin.LogEntry.user was declared with a lazy reference to 'recipes.customuser',but app'recipes'doesn't provide model 'customuser'` from django.db import models from django.http import HttpResponse from django.contrib.auth.models import AbstractUser, Permission from django.conf import settings from django.contrib.auth import get_user_model import secrets class CustomUser(AbstractUser): email=models.EmailField(unique=True) USERNAME_FIELD="email" REQUIRED_FIELDS=["username"] def __str__(self) -> str: return self.email -
What is the configuration for Apache Airflow, Django, PySpark together in Systemd services?
We are using Apache airflow, Django (python), and Spark (pySpark) in our project. Our DAGs are running fine when run 'airflow scheduler' is run from command line. However, these DAGs are not working when 'airflow scheduler' is run from systemd (systemctl). Note: We are using virtual environment to run airflow scheduler (and many python apps). Initially, we faced issues related to Virtual Environment. Later, Django Setup. We resolved the same. However, we are now facing the pyspark related issues. We have tried this for the scheduler. [Unit] Description=Airflow scheduler daemon After=network.target postgresql.service mysql.service redis.service rabbitmq-server.service Wants=postgresql.service mysql.service redis.service rabbitmq-server.service [Service] PIDFile=/home/datauser/Documents/airflow_workspace/airflow_env/bin/scheduler.pid Environment="PATH=/home/datauser/Documents/airflow_workspace/airflow_env/bin:/home/datauser/airflow_workspace/airflow_env/airnet/aqdms:/home/datauser/Downloads/spark-3.5.1-bin-hadoop3/bin:/home/datauser/Downloads/spark-3.5.1-bin-hadoop3/sbin" Environment="PYTHONPATH=/home/datauser/Documents/airflow_workspace/airflow_env" Environment="JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64/jre" Environment="SPARK_HOME=/home/datauser/Downloads/spark-3.5.1-bin-hadoop3" Environment="PYSPARK_DRIVER_PYTHON=python3" Environment="PYTHONSTARTUP=/home/datauser/Downloads/spark-3.5.1-bin-hadoop3/python/pyspark/shell.py" Environment="PYSPARK_PYTHON=python3" Environment="SPARK_CONF_DIR=/home/datauser/Downloads/spark-3.5.1-bin-hadoop3/conf" Environment="PYSPARK_SUBMIT_ARGS=--master local[2] pyspark-shell" User=datauser Group=datauser Type=simple ExecStart=/usr/bin/bash -c 'source /home/datauser/Documents/airflow_workspace/airflow_env/bin/activate ; /home/datauser/Documents/airflow_workspace/airflow_env/bin/airflow scheduler --pid /home/datauser/Documents/airflow_workspace/airflow_env/bin/scheduler.pid' Restart=on-failure RestartSec=5s PrivateTmp=true [Install] WantedBy=multi-user.target What should be the configuration to use Apache airflow, Django, PySpark and virtual environment in Systemd? -
What is causing Unexpected Keyword 500 error when trying to pass data from URL as a variable using Django?
I am taking an online course and replicate the instructor's code on my Mac in VS Code to help me learn how it works; and this is not a homework problem. The instructor was showing how to dynamically create responses based on the URL by sending the last part of the url as a variable to a function that then generates the response. However , when I try it I get a 500 error. I have reviewed my code and it looks identical to the instructors, with only added comments. Fixed paths work fine, i.e. path("brian", views.brian, name = "brian"), works fine, but this fails: path("<str:name>", views.greet, name = "greet") the error is: [18/Jul/2024 20:50:39] "GET /hello/jim HTTP/1.1" 500 59430 [18/Jul/2024 20:50:41] "GET /hello/ HTTP/1.1" 200 5 Internal Server Error: /hello/jim Traceback (most recent call last): File "/Users/XXX/Documents/Work/Python Projects/Dashboard/.venv/lib/python3.12/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "/Users/XXX/Documents/Work/Python Projects/Dashboard/.venv/lib/python3.12/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ TypeError: greet() got an unexpected keyword argument 'Name' I created several bits of code: (comments are mine so when I go back to the code later I can understand it) Created app called hello and added to installed apps in … -
Django prefetch_related not being helpful in diminishing queries
myList = [] qs = MyModel.objects.all().prefetch_related('m2m_model_set') for model in qs: k = model.m2m_model_set.all().values_list('field') myList.extend(k) This code represents what I am doing. Why is the line k = model.m2m_model_set.all().values_list('field') causing many queries? How can I fix this problem and do the same without making so many queries? -
How can I log variables based on database configuration?
Backend: Python 3.11 and Django 5.0.6 Database: PostgreSQL 15.6 We are shifting to deploying a Python executable file for the backend. Consequently, we will be unable to modify the code directly on the server. We do use a logger to save important information or errors from the server. However, sometimes we need to debug the code in production. How can we achieve this considering we can't modify the executable? Can we log/print variables at a specific line number configured in the database, without restarting the backend service? For example, if I want to log a variable report_name1 at line number 40 in the file portal/reports/report.py, how should this be set up? I am considering importing a class or function at the top of the file once, with all configurations being handled from the database. Here's the proposed structure for a LogVariables table: path_name = 'portal/reports/report.py' line_number = 40 variable_name = 'report_name1' is_active = True is_deleted = False -
Optimized way to handle user graded items?
I'm working on website that allows users to grade items, e.g. books. The grade should be displayed on the book page, but also on the collective page containing all books. The grades should be possible to modify: class BookUserGrade: user = foreign_key_to_user book = foreign_key_to_book grade = ... However the operation of requesting the grades each time a user access the booklist (or to lesser degree single book page) seems expensive. I'm pondering about making an additional two fields on the book itself, number_of_grades and cumulative_grade which are going to be updated only on user grading a book. Maybe also calculated_grade (is it worthy to add this field instead of calculating cumulative_grade / number_of_grades on the fly? Or perhaps there's another proper way to do so? -
A local variable seemingly breaking scope in Django
I have introduced this function in a file storage.py that is imported from models.py: def uuid_file_name(kind): def file_name(instance, filename): h = str(uuid.uuid4()) basename, ext = os.path.splitext(filename) return os.path.join(f'{kind}_files', h[0:1], h[1:2], h + ext.lower()) return file_name The intention of the function is to dynamically generate file names in a field declaration, such as: class Thingy(models.Model): widget = FileField(upload_to=uuid_file_name("widget")) Now when I makemigrations, I get an odd error: ValueError: Could not find function file_name in <app>.storage. There is no other mention of file_name in my project, and if I change the identifier, the error message changes accordingly, so the error is definitely from this. However, without some metaprogramming, I can't see how file_name can leak from within this function. I thought I could avoid whatever magic was happening by from .storage import uuid_file_name as _uuid_file_name, hoping Django wouldn't act on a private module member, but the same error occurs. So, a two-fold question: Why is this happening, and how do I prevent it? Is there another way to write the equivalent code to circumvent the error? Full traceback: Traceback (most recent call last): File "<project>/./manage.py", line 22, in <module> main() File "<project>/./manage.py", line 18, in main execute_from_command_line(sys.argv) File "<project>/<venv>/lib/python3.12/site-packages/django/core/management/__init__.py", line 442, in … -
How to restrict available InlinePanel instances that can be choosen in wagtail admin
Let's say we Course and Lesson Wagtail Page models, where Lesson page instances are sub-pages of Course page instance. E.g. "Web Development Course > HTML Lesson". Implemented as: class Course(Page): description = models.TextField(null=True, blank=True) content_panels = Page.content_panels + [ FieldPanel('description'), ] class Lesson(Page): description = models.TextField(null=True, blank=True) content_panels = Page.content_panels + [ FieldPanel('description'), ] parent_page_types = ['app.Course'] Now we add an orderable many2many relationship to Course using InlinePanel(), so we can set each course's lessons and order them in Wagtail Admin. implementation: class Course(Page): description = models.TextField(null=True, blank=True) content_panels = Page.content_panels + [ FieldPanel('description'), InlinePanel('course_lessons', label='Lessons'), ] class CourseLessons(Orderable): page = ParentalKey('Course', on_delete=models.CASCADE, related_name='course_lessons') lesson = models.ForeignKey('Lesson', on_delete=models.CASCADE) panels = [ FieldPanel('lesson'), ] class Lesson(Page): description = models.TextField(null=True, blank=True) content_panels = Page.content_panels + [ FieldPanel('description'), ] parent_page_types = ['course.Course'] Question: How can we limit the inline page choices to specific parent page's sub-pages? E.g. When selecting lessons for a course, only that course's lessons(sub-pages) are available. I thing this can be achieved either by limiting Page -
How to run on_success in Celery ONLY on the last worker process in a group?
I have been scratching my head about this for days now. I have a a background running task, which takes around 1 hour. I am processing 5000 images. I create a group of celery tasks and each task processes 1000 images each. I have an on_success method where I create a 'Finished' database record, and remove the 'inProgress' record. The problem however is, that even while having tons of checks in the on_success method, it still somehow generates 2 'Finished' database records. It sounds confusing, see the code below: def on_success(self, retval, task_id, *args, **kwargs): self.image_job.refresh_from_db() total_nr_of_images = self.image_job.total_nr_of_images stored_results = ImageJobResults.objects.filter(job=self.image_job).count() if stored_results == total_nr_of_images: #It means all the workers have completed processing images # for this job, and we need to create a csv file, and a Finished BC Job with transaction.atomic(using='my_db'): image_job = ImageJob.objects.select_for_update().get(id=self.image_job.id) if not ImageJobFinished.objects.filter(job=image_job).exists(): job_in_progress = ImageJobInProgress.objects.get(job=image_job) started_at = job_in_progress.started_at image_job.generate_results(started_at=started_at,completed_at=now(),csv_rds_handle_job_id=self.image_job.pk) #Now that a ImageJobFinished is created. # We delete the ImageJobInProgress instance job_in_progress.delete() return super().on_success(retval, task_id, *args, **kwargs) Now theoretically, the stored_results should be equal to total_nr_of_images only in the last worker. But both the workers somehow finish on the same time, and they get the same values here. Both of them then … -
How to register voice for TTS in windows 11?
I have some troubles to use 2 additional voices, in my case i try to use Pablo (Spanish - Spain) and George (English - GB). I develop a app in python/Django, from the front i sent a JSON with the language (in this case with what voice i want to read the text), and the text, the back received and process it calling the proper voice reading the text. here is part of the code: import win32com.client, pythoncom from .translator import translate_text def check_voices(): pythoncom.CoInitialize() try: speaker = win32com.client.Dispatch('SAPI.SpVoice') voices = speaker.GetVoices() for voice in voices: print(f"Voice: {voice.GetDescription()}, Id: {voice.Id}") finally: # Finalizar COM pythoncom.CoUninitialize() def sound_rate(speaker): speaker.Rate = -1 # rango -10(lento) - 10(rapido) def sound_volume(speaker): speaker.Volume = 100 # rango 0(bajo) - 100(alto) def text_to_speech(language, text): pythoncom.CoInitialize() try: speaker = win32com.client.Dispatch('SAPI.SpVoice') voices = speaker.GetVoices() check_voices() if language.startswith('en-'): text = translate_text(text, from_code='es', to_code='en') language_map = { 'es-ES-female': 'Microsoft Helena Desktop - Spanish (Spain)', 'es-ES-male': 'Microsoft Pablo Desktop - Spanish (Spain)', 'en-UK-female': 'Microsoft Hazel Desktop - English (Great Britain)', 'en-UK-male': 'Microsoft George Desktop - English (Great Britain)', } voice_name = language_map.get(language) for voice in voices: if voice.GetDescription() == voice_name: speaker.Voice = voice break speaker.Speak(text) except Exception as e: print(f"An error … -
Optimizing Django Application Performance
I'm currently dealing with performance issues in a Django application that's structured as follows: User - Social Network - Post - Tag/Label Each entity is represented by its own table. The number of tags is growing exponentially, even after filtering out less significant ones (tags are assigned by an AI, not humans). Here's what I'm considering to optimize performance: Separate Tables for Insignificant Tags: Move less significant tags to a different table or even a different database. For instance, having 100k rows in MediaTags table and 10M rows in SmallMediaTags. Would this improve the performance of the main tables? Denormalization: Currently, each post is linked to 2-5 primary tags, meaning the number of tags equals 2-5 times the number of posts, with occasional outliers having 6+ tags. This puts a massive load on MediaTags, complicates searches, and incurs additional costs for converting MediaTags into objects. However, if we store top-N tags directly with the posts (e.g., top-10 tags), it could result in nearly a 1:1 ratio. This way, all required tags would be part of the posts themselves, eliminating the need for additional table queries. We have recently started displaying lists of posts with specific tags, which has become a … -
How do I pass request to a form in test
I am trying to pass request to a Django form in unittest. This is my test: def test_AddPairedStudyForm(self): self.client.force_login(self.user) request = RequestFactory().get(reverse("researcher_ui:console")) request.user = self.user study_group = 'StudyGroup' payload = { "study_group": study_group, "paired_studies": [self.study.id, self.study1.id], 'request': request } form = AddPairedStudyForm(data=payload) self.assertTrue(form.is_valid()) This generates a key error in the form: KeyError: 'request' Within the form itself, this error occurs during the __init__ function def __init__(self, *args, **kwargs): self.request = kwargs.pop("request") super(AddPairedStudyForm, self).__init__(*args, **kwargs) Within the CBV I add the request using the get_form_kwargs function: def get_form_kwargs(self): kwargs = super().get_form_kwargs() kwargs["request"] = self.request return kwargs How can I pass the request to the form in unittest? -
How to retrieve the mobile number linked to an any user Aadhaar card in python django
How to retrieve the mobile number linked to an any users Aadhaar card. I want to validate user aadhaar card so I'll send OTP on aadhaar mobile number to validate, that's my approach. So Any builtin API or any Doc suggestion anyone can refer. -
import class in admin.py from package that in site-packages
I used django-comment-system I want import classadmin from admin.py (that in my app project) at admin.py (that in LIB/site-packages/comment) from kernel.blog import models #here is LIB/site-packages/comment/admin.py i tried with that code but give me error: No module named 'kernel.blog' kernel is base and blog is a app in kernel -
Resize readonly fields in Django Admi
In my Django admin im currently displaying JSONField as readonly, the JSON data is quite large and takes up about 80-90% of the page. I was able to find an answer for how one might resize a not readonly field here but other then that I am lost. My ideal outcome would have the large JSON data in a scrollable text box like so: Ideal outcome How can I control the size of a readonly field without truncating the data? -
Database is locked when acreate operation is handled
I'm writting tests for my project. I tried to add some async things to it. And that things worked but when I run tests it fails: django.db.utils.OperationalError: database is locked await UserBill.objects.acreate(user_id=user_id, bill=total_cost, duration=rent_range) Test is: @pytest.mark.django_db @override_settings( CELERY_TASK_EAGER_PROPAGATES=True, CELERY_TASK_ALWAYS_EAGER=True, CELERY_BROKER_URL='memory://', CELERY_RESULT_BACKEND='cache+memory://', ) def test_finish_rent(django_db_blocker, django_db_setup): with django_db_blocker.unblock(): user = User.objects.get(email='test2@example.com') bicycle = Bicycle.objects.get(name='Bicycle 2') finish_rent(bicycle, user) assert BicycleUser.objects.filter(bicycle=bicycle, user=user).exists() is False conftest.py is: @pytest.fixture(scope='session') def django_db_setup(delete_db, django_db_blocker): with django_db_blocker.unblock(): call_command('sqlflush') with django_db_blocker.unblock(): call_command('migrate', '--noinput') yield finish_rent: def finish_rent(bicycle, user): bicycle_user = BicycleUser.objects.get(bicycle=bicycle, user=user) start_rent = bicycle_user.rent_start bicycle_user.delete() add_bill.delay(bicycle.id, user.id, start_rent) async task: async def add_bill_task(bicycle_id, user_id, start_rent): now = timezone.now() rent_range = (now - start_rent).total_seconds() rent_range = rent_range // 60 bicycle = await Bicycle.objects.aget(id=bicycle_id) total_cost = bicycle.cost_per_minute * rent_range await UserBill.objects.acreate(user_id=user_id, bill=total_cost, duration=rent_range) @shared_task def add_bill(bicycle_id, user_id, start_rent): asyncio.run(add_bill_task(bicycle_id, user_id, start_rent)) What's wrong with my code guys? -
Datatables causes table element to disappear, only when deployed
I have a Django web app which I'm hosting on Heroku, and I'm using the Datatables JQuery library to add extra features to a table. When I run my app locally, it works beautifully. When I deploy on Heroku, the JQuery function that loads the Datatable instead causes the table to disappear. There are no errors in the console and nothing different in the Network tab than when I run locally. I'm thinking that it might be some kind of configuration problem with Heroku, even though Datatables is client-side? Any advice would be appreciated. I know that the JS script is running because I can print things to the console. I also know that it's specifically the creation of the Datatable that causes the problem, because if I include a setTimeout call, the table appears (in default HTML format) until the timeout ends and the function gets called. Some excerpts - from table.js: $('#ads').DataTable( { autoWidth: false, tabIndex: -1, pageLength: 100, stateSave: true, order: [[3, 'desc']], columnDefs: [{ orderable: false, targets: 2 }, { render: $.fn.dataTable.render.number(',', '.', 0, '$', ''), targets: 3 }, { searchPanes: { show: true }, targets: $(location).attr('pathname')=='/review/all' ? [0, 1, 4] : [0, 1] }, { … -
how to make every posts equal in size when respond to screen size?
Inside the post div, there will be multiple post rows. Each row contains maximum 4 posts. So when there are 5 posts there comes the problem with responsiveness. First 4 posts (first row) will respond to the screen size but the 5th post (second row) does nothing because there are space left for the 5th post. <div class="posts"> {% if post %} {% for media in post %} {% if forloop.counter0|divisibleby:"4" %} <div class="post-row"> {% endif %} <a id="post-wrapper" href="{% url 'sh-media' %}?pid={{media.pid}}"> <div class="thumbnail-container"> <img src="{{ media.media_thumbnail.url }}" class="post-thumbnail"> <div class="gradient-overlay"> <h2 class="video-caption">{{ media.caption}}</h2> <p class="video-description">{{ media.descr }}</p> </div> </div> </a> {% if forloop.counter0|add:"1"|divisibleby:"4" or forloop.last %} </div> {% endif %} {% endfor %} {% endif %} </div> <style> .posts{ display: flex; flex-direction: column; color: #fff; padding-top: 15px; justify-content: flex-start; } .post-row{ display: flex: } #post-wrapper{ margin: 20px 10px; } </style> Is there any way to make all the posts will maintain the same size when it respond to the screen size? Output HTML: <div class="posts"> <div class="post-row"> <a id="post-wrapper" href="/watch-profile%23ed-media?pid=060"> <div class="thumbnail-container"> <img src="/static/images/9_16%20Video.png" class="post-thumbnail"> <div class="gradient-overlay"> <h2 class="video-caption">sea breeze</h2> <p class="video-description">Winter morning sweet music</p> </div> </div> </a> <a id="post-wrapper" href="/watch-profile%23ed-media?pid=bea"> <div class="thumbnail-container"> <img src="/static/images/9_16%20Audio.png" class="post-thumbnail" > <div … -
Django Topic dropdown displays Topic object(1) but not the name of the object
Django Topic dropdown displays Topic object(1) but not the name of the object class Topic(models.Model): """A topic the user is learning about.""" text = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) class Entry(models.Model): """Something specific learned about a topic""" topic = models.ForeignKey(Topic, on_delete=models.CASCADE) text = models.TextField() date_added = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural = 'entries' def __str__(self): """Return a simple string representation of the entry.""" return f"{self.text[:50]}..." Above is the code in the models.py, I'm very knew to django but I an alright understanding of python. Cant really seem to figure out why when I navigate to the website the topics name doesnt appear but instead it says topic object(1) --> topic object(2) -
How to write a Case() SQL expression with an aggregated field (Sum) using Django's query builder
I am trying to recreate this SQL statement using Django's query builder: CASE WHEN sum(imps) = 0 THEN NULL ELSE SUM(total_expenses) / (sum(imps) / 1000) END as "cpm" I have tried: MyModel.objects.annotate( cpm=Case( When( Sum("imps")>0, then=Sum("total_expenses") / Sum("imps"), ), default=0, output_field=FloatField(), ) ) However it doesn't work because of this TypeError '>' not supported between instances of 'Sum' and 'int'. If there was a field lookup that enabled me to do total_imps__sum__gt=0, I am sure that would solve the problem. Note: Adding Sum("imps") as an annotation (total_imps=Sum("imps")) and doing total_imps__gt=0 works but it is not an ideal solution as I would have to create multiple annotations for fields I won't need. -
Postgresql SELECT optimisation into Django ORM
Please see below a PostgreSQL SELECT statement. This presently returns around 300k rows, which is the grouped result of several million underlying rows. The dataset is only going to get larger. Using the ANALYSE EXPLAIN function the cost of this select is 111847 units. This select statement is being used in a Django ORM query set model. So the results are queried and mapped into an object. Due to the time taken for the SELECT to complete my Django application is timing out. The underlying data is made of up daily times series data, but I don't need the whole history. I am using the dataset for current day, MTD, QTD, YTD, ITD grouped values. How can I optimise this? I have been investigating indexing but am struggling to apply here. Or should I just try and re-structure the whole query? Or even build other tables to hold the aggregated results for my Django ORM to call? SELECT customers_data.position_date, customers_data.code_id, customers_data.book_id, customers_data.base_lmv, book_tags.book, book_tags.market, book_tags.employee, pnl_data.base_daily_pnl, disasters_data.disaster_5_pnl FROM ( SELECT daily_customers_holding_scenario.code_id, daily_customers_holding_scenario.position_date, daily_customers_holding_scenario.book_id, sum(daily_customers_holding_scenario.base_lmv) AS base_lmv FROM daily_customers_holding_scenario GROUP BY daily_customers_holding_scenario.position_date, daily_customers_holding_scenario.code_id, daily_customers_holding_scenario.book_id) customers_data LEFT JOIN book_tags ON customers_data.book_id = book_tags.book_id FULL JOIN ( SELECT products.position_date, products.code_id, products.book_id, sum(products.palliser_base_pnl) AS … -
I need help to solve this
I'm encountering an issue with one of my Django views, and I'm hoping someone can help me troubleshoot it. When I try to access the URL: https://tout-talent.com/forfait/, the browser or site displays a different page with the message: {"success": false, "message": "Invalid request method"} However, on my server and in the debug.log file, I see the following log entry: "GET /forfait/ HTTP/1.1" 200 indicating a 200 OK HTTP status code. But the template that should normally display is not being rendered. Here's the code for the view : @login_required def subscribe(request): if not hasattr(request.user, 'company'): print("Utilisateur non connecté ou sans compagnie associée.") return redirect('login') # Or show an appropriate message company = request.user.company print(f"Company: {company}") active_subscription = None try: active_subscription = CompanySubscription.objects.get(company=company, is_active=True) print(f"Active subscription found: {active_subscription}") except CompanySubscription.DoesNotExist: print("No active subscription found.") if request.method == 'POST': form = SubscriptionForm(request.POST) if form.is_valid(): plan = form.cleaned_data['plan'] print(f"Selected plan: {plan}") if plan.name == 'lite': print("Redirecting to Lite plan duration view.") return redirect('days_duration_for_lite_plan', plan_ref=plan.ref) else: days = plan.duration_days amount = plan.price_per_month if days >= 30 else plan.price_per_day * days print(f"Days: {days}, Amount: {amount}") if plan.name == 'free': subscription, created = CompanySubscription.objects.get_or_create( company=company, defaults={ 'plan': plan, 'start_date': timezone.now(), 'end_date': timezone.now() + timedelta(days=days), 'is_active': True, … -
How to access set of objects in reverse Foreign Key in Django
I have 2 tables defined like this: class Optimization(BaseModel): name = models.TextField(unique=True, null=False) is_active = models.BooleanField(null=False, default=True) class Meta: db_table = 'optimization' class OptimizationInput(BaseModel): name = models.TextField(null=False) optimization = models.ForeignKey(Optimization, null=False, on_delete=models.CASCADE) class Meta: db_table = 'optimization_input' I want to get some Optimizations with their inputs. I can't figure out how to access the set of OptimizationInputs I'm trying to do this: optimizations = Optimization.objects.filter(is_active=True).only('name').values('name', 'optimizationinputs_set') but I also tried this optimizations = Optimization.objects.filter(is_active=True).first() print('inputs', optimizations.optimizationinputs_set) Either way, it tells me there is no such attribute as optimizationinputs_set -
Alternative of django-boolean-switch for new version django
I used the package of django-boolean-switch for new django but it wasn't work because it is for old version. I trying to change its codes to usable for new django but it so crazing ! is there new package or new solution for this idea? -
Django Rest Framework RetrieveUpdateAPIView not working
I'm having an issue with using RetrieveUpdateAPIView and RetrieveDestroyAPIView. I'm trying to Update or Delete a Newsletter object while logged in as an administrator. Unfortunately, after clicking 'PUT' or 'DELETE', it automatically logs me out and Django Rest Framework shows an error: { "detail": "CSRF Failed: CSRF token missing." } Postman also displays an error: { "detail": "Authentication credentials were not provided." } Code below: settings.py MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", ] REST_FRAMEWORK = { "DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.LimitOffsetPagination", "PAGE SIZE": 10, "DEFAULT_FILTER_BACKENDS": [ "django_filters.rest_framework.DjangoFilterBackend", ], } serializers.py from rest_framework import serializers from core.models import Newsletter import re class NewsletterSerializer(serializers.ModelSerializer): class Meta: model = Newsletter fields = "__all__" extra_kwargs = { "created_at": { "format": "%Y-%m-%d %H:%M:%S", } } class NewsletterCreateSerializer(serializers.ModelSerializer): email = serializers.CharField( required=False, allow_blank=True, ) class Meta: model = Newsletter fields = [ "id", "created_at", "email", ] extra_kwargs = { "created_at": { "format": "%Y-%m-%d %H:%M:%S", "read_only": True, }, } def validate_email(self, email): print(email) if email == "": raise serializers.ValidationError( detail="E-mail Address is required.", ) if email and not re.match(pattern=r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)", string=email): raise serializers.ValidationError( detail="The e-mail address format is invalid.", ) if self.instance is None: if email and re.match(pattern=r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)", string=email) and Newsletter.objects.filter(email=email).exists(): raise serializers.ValidationError( detail="The newsletter already exists.", …