Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Not able to highlight my subject_id getting in my request for Django project
When the user clicks on a subject_id on one page, it redirects to a another page and on that page the subject_id in the request url, should be highlighted to the user, but somehow I am not able to see it. Open to suggestions, Added this in my javascript function, is this the right way to do it? if (data.name == {{subject_id|safe}}) { $('#dtBasicExample').DataTable().row(i).addClass('highlight-green'); } -
Control the Error from Meta class in Django model
I'm working with Blog website with Django, I have a model called Post and its like this: class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=100) txt = models.TextField() created_at = models.DateTimeField(auto_now_add=True) def __str__(self) -> str: return f"{self.user} {self.title}" class Meta: ordering = ['-created_at'] unique_together = ['title', 'txt'] and so when a user try to create more than one Post with the same title and text it must launch an Error, but I don't know how to control this error and turn it into a proper Error and code will launch the Constraint_failed error and I wanna control this kind of Errors not just in the Admin panel but in the User client side that User can see his mistakes and fix it. can anyone give a tip or solution. thanks. -
Replace image in static folder Django 1.5
I uploaded an image, which saved in the database correctly and I'm able to view it using an tag. Now I wanted to replace the image. I went to the static folder where the image is stored and deleted the old one, then replace it with the new one ( with same name and extension). The problem is when I refreshed my page, it still shows me previous image. What am I not doing correctly pls. I have restarted my machine. Restarted my apache server. But it still shows old image -
django pagination returns nothing
i'm not sure what went wrong here. spent hours trying to figure out. when run the program i can see list of objects displayed but none of pagination.html information is displayed. views.py def post_list(request): post_list = Post.objects.all() p = Paginator(post_list, 2) page_num = request.GET.get('page',1) posts = p.page(page_num) return render(request, 'blog/post/list.html', {"posts":posts}) list.html {% extends "blog/base.html" %} <!DOCTYPE html> <html> <head> {% block title %} My Post{% endblock %} </head> <body> {% block content %} {% for post in posts %} <ol> {{post.title}} by {{post.author}} published= {{post.status}} slug==> {{post.slug}} <span><a href="{{ post.get_absolute_url }}">details</a></span> </ol> {% endfor %} {% include "directory/pagination.html" with pages=posts %} {% endblock %} </body> </html> pagination.html <div class="pagination"> <span class="step-links"> {% if pages.has_previous %} <a href="?page=1">&laquo; first</a> <a href="?page={{ pages.previous_page_number }}">previous</a> {% endif %} <span class="current"> Page {{ pages.number }} of {{ pages.paginator.num_pages }}. </span> {% if pages.has_next %} <a href="?page={{ pages.next_page_number }}">next</a> <a href="?page={{ pages.paginator.num_pages }}">last &raquo;</a> {% endif %} </span> </div> -
Render(Deploy) ERROR: Ignored the following versions that require a different python version
I'm trying to deploy an Api using Render but i get this error ERROR: Ignored the following versions that require a different python version: 1.21.2 Requires-Python >=3.7,<3.11; 1.21.3 Requires-Python >=3.7,<3.11; 1.21.4 Requires-Python >=3.7,<3.11; 1.21.5 Requires-Python >=3.7,<3.11; 1.21.6 Requires-Python >=3.7,<3.11 ERROR: Could not find a version that satisfies the requirement pywin32==306 (from versions: none) ERROR: No matching distribution found for pywin32==306 [notice] A new release of pip available: 22.3.1 -> 23.1.2 [notice] To update, run: pip install --upgrade pip ==> Build failed the version of python i'm using is 3.11.2 and i already updated pip so i have the 23.1.2 version I'm new with this so it's my first time trying to deploy, it woude be really helpful if someone can explain what's going on and how i can solve it -
best way to compress uploaded photos and videos with python and django to reduce storage
Hoping I can get some suggestions here, thanks for the help. I am building a django python based web app where users will be able to upload photos and videos that they would take with their mobile phone. At this stage I would be limiting each user to 10 photos or videos, but we have high user volumes so the main concern here is storage space consumption. What are some recommended compression packages that could be used to store the photos and videos? Thanks for any recommendations. I had a look at tinypng which would be fine for images but I dont think it processes videos. I also expect that the file formats for the images and videos could be a range of formats, there is no specific format that I need to store the media files as. -
Can registered users create more users in a django app?
I'm trying to create an app in which a user (not admin) can add more users? Let me explain a little bit... If I log in the app as a user I would like to add clients without the intervention of the clients. Also such clients should be able to log in the app and see the information that I placed in their behalf, for instance their orders. I thought that maybe they can log with their email and drivers license number as password or something like that, information that would be provided at the time of me adding them (a client) to the system -
Generic Django template to display multiple tables
Is there a way to create a generic html table in Django. I want to reuse the same form.html to display entities with different columns. For example in the below code a pass a list of headers, and dynamically create the thead,but I need for each row in the body to get every value. So I need to iterate. Or is there any other approach to reuse templates in a mo generic way instead of build N templates for each table yuo need to display <table class="table table-bordered" id="vendor_table" style="text-align: center;"> <thead class="tables-success"> <tr> {% for header in list_headers %} <th>{{ header }}</th> {% endfor %} </tr> </thead> {% for row in list_values %} <tr> {% for header_name in list_headers %} <th> {{ row.{{ header_name }} }} </th> <--------- {% endfor %} </tr> {% endfor %} </table> -
Images in list in form Django, How?
Dear masters! Please help me with this question. models.py class New_tables(models.Model): TYPEBET_CHOICES = ( ('1','up'), ('0', 'down'), ) type_bet = models.IntegerField(choices=TYPEBET_CHOICES) form.py type_bet = forms.TypedChoiceField(choices=New_tables.TYPEBET_CHOICES) how to make sure that when you select from the list, there are not “up” and “down”, but that instead of them a picture is displayed, preloaded in /media/ ? I didn't find any information on the Internet. -
Can Django ORM calculate market share of specific brands over multiple time periods in a single query?
I have the following Django model: class MarketData(models.Model): category = models.CharField(max_length=64, null=True) brand = models.CharField(max_length=128, null=True) time_period = models.DateField() sales = models.IntegerField(default=0, null=True) I am trying to use Django's ORM to calculate the market share of each brand within each time period of my dataset to output to a line chart. The market share calculation itself is simple: the sales of each brand within the time period divided by the total sales in each time period. I can use Django's ORM to generate a queryset of brands and sales by time period, but I'm struggling to annotate the additional metric of sales for all brands. My current query: sales = MarketData.objects.filter(brand__in=['Brand 1', 'Brand 2']) \ .values('time_period', 'brand') \ .annotate(sales=Sum('sales')) \ .order_by('period', '-sales') My current queryset output: <QuerySet [{'time_period': datetime.date(2020, 6, 30), 'brand': "Brand 1", 'sales': 21734}, {'time_period': datetime.date(2020, 6, 30), 'brand': 'Brand 2', 'sales': 93622}]> How can I add another annotation that includes the sales of ALL brands for that time period, not just the brands specified in the filter, and not just the current brand? I have tried to use a Subquery to get the total market sales by period, but I end up with an aggregate across all … -
Django.auth.authenticate not authenticating user
I am creating an app, and I am trying to manually create the login page so I can add some things that I can't add using the default Django authentication pages. This is what my view looks like: def logIn(request): formClass = LogInForm template = "login.html" if request.method == "POST": auth.authenticate(username=request.POST["username"], password=request.POST["password"]) return redirect("/") return render(request, template, { "form" : formClass }) But, when I print out the user's id after logging in, it returns none. Does somebody know what is going on? -
Why isn't session value persisting with Django Rest Framework (DRF)?
thank you for your time and attention to this query. I am trying to set (key, value) into the request session from one drf function and accessing that (key, value) via the request session in another drf function. Please see the code below for the current implmentation: class FunctionOne(GenericAPIView): permission_classes = (permissions.AllowAny,) authentication_classes = [] def get(self, request, *args, **kwargs): request.session["kcc"] = request.GET.get("code") request.session.modified = True print("kcc", request.session.get("kcc", None)) return redirect("http://localhost:3000/checkout") class FunctionTwo(GenericAPIView): permission_classes = (permissions.AllowAny,) authentication_classes = [] def get(self, request, *args, **kwargs): print(dir(request.session)) code = request.session.get("kcc") if code: return Response(status=status.HTTP_200_OK) else: return Response(status=status.HTTP_404_NOT_FOUND) It is successfully setting the (key, value) into the session in function one and can be seen via the print statement. However when accessing the function two view the (key, value) saved in the session can't be found. I've checked the settings.py "django.contrib.sessions.middleware.SessionMiddleware" is included in the middleware and also these are the current rest_framework settings: REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": [ "backend.authentication.FirebaseAuthentication", ], "DEFAULT_RENDERER_CLASSES": [ "rest_framework.renderers.JSONRenderer", ], "DEFAULT_PERMISSION_CLASSES": [ "rest_framework.permissions.IsAuthenticated", ], } Additionally, I am not using the default Sqlite database that is shipped with Django, I have a postgresql database hooked up to the project instead. I would greatly appreciate if pointed in the … -
how to use ckeditor for two fields in django crispy form?
First of all, I have installed CKeditor, not django-ckeditor. I am trying to display two ckeditor for two fields in same model and form. I have customize widget created. Here is my custom widget class CKClassicEditorWidget(forms.Textarea): """CKEditor Classic Editor widget. Custom widget for Django forms, integrating CKEditor Classic Editor as a rich text editor. """ template_name = "widgets/ckeditor.html" and here is the html file. {% load static %} {% with id=widget.attrs.id required=widget.attrs.required %} <script defer src="{% static 'js/ckeditor/ckeditor.js' %}"></script> <style> .ck-editor__editable { min-height: 200px; } </style> <textarea name="{{ widget.name }}" {% for key, value in widget.attrs.items %}{% if key != 'required' %}{{ key }}="{{ value }}"{% endif %}{% if not forloop.last %} {% endif %}{% endfor %}>{{ widget.value|default:'' }}</textarea> <script> document.addEventListener('DOMContentLoaded', function() { ClassicEditor .create(document.querySelector('#{{ id }}'), { toolbar: { language: 'en', items: [ 'heading', '|', 'bold', 'italic', 'link', 'bulletedList', 'numberedList', '|', 'outdent', 'indent', '|', 'blockQuote', 'insertTable', 'undo', 'redo', '|', 'sourceEditing', 'selectAll' ] }, table: { contentToolbar: [ 'tableColumn', 'tableRow', 'mergeTableCells', 'tableCellProperties', 'tableProperties' ] } }) .then(editor => { document.querySelector('#{{ id }}').ckeditorInstance = editor; if ('{{ required }}' === 'True') { const form = document.querySelector('#{{ id }}').closest('form'); form.addEventListener('submit', function(event) { const editorData = editor.getData(); if (editorData.trim() === '') { alert('Content … -
The issue you are facing is related to the usage of the {% block body %} tag in your child template
i am facing issue dont know what to do please help me with that i cant add any html code to my body i want to add html code to my body tag TemplateSyntaxError at / Invalid block tag on line 6: 'endblock'. Did you forget to register or load this tag? Request Method:GETRequest URL:http://127.0.0.1:8000/Django Version:4.2.3Exception Type:TemplateSyntaxErrorException Value:Invalid block tag on line 6: 'endblock'. Did you forget to register or load this tag?Exception Location:C:\Users\91939\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\django\template\base.py, line 568, in invalid_block_tagRaised during:products.views.indexPython Executable:C:\Users\91939\AppData\Local\Microsoft\WindowsApps\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\python.exePython Version:3.11.4Python Path:['C:\\shops\\newshops', 'C:\\Program ' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.11_3.11.1264.0_x64__qbz5n2kfra8p0\\python311.zip', 'C:\\Program ' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.11_3.11.1264.0_x64__qbz5n2kfra8p0\\DLLs', 'C:\\Program ' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.11_3.11.1264.0_x64__qbz5n2kfra8p0\\Lib', 'C:\\Program ' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.11_3.11.1264.0_x64__qbz5n2kfra8p0', 'C:\\Users\\91939\\AppData\\Local\\Packages\\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\\LocalCache\\local-packages\\Python311\\site-packages', 'C:\\Program ' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.11_3.11.1264.0_x64__qbz5n2kfra8p0\\Lib\\site-packages']Server time:Fri, 07 Jul 2023 19:43:13 +0000 Error during template rendering In template C:\shops\newshops\products\templates\products\home.html, error at line 6 Invalid block tag on line 6: 'endblock'. Did you forget to register or load this tag? 1{% extends 'base.html' %} {% block title %}hello hi{% endblock %}{% block body2%}34<h1>hello</h1>5<h2>hi</h2>6{% endblock %}7 so can yo please provide me detail explanrtion of this question -
Pass multiple arguments from Django template for loops into Django template filter or tag
I'm building a timetable application and I need to check if there is a certian room available so I want to create a function/template tag/template filter to return me a boolean value which I want to later on pass into Django template if statement. View function: def my_view(request): args = { 'days': Days.objects.all(), 'times': Times.objects.all(), 'rooms': Rooms.objects.all(), } return render(request, 'my_page', args) Template stucture example that I need: {% for day in days %} {% for time in times %} {% for room in rooms %} {% if MY_TAG {{ day }} {{ time }} KWARG={{ room }} %} <p>SOMETHING IF TRUE</p> {% else %} <p>SOMETHING IF FALSE</p> {% endif %} {% endfor %} {% endfor %} I've looked on the official Django docs, SO and other sites and forums for these things. I've found a couple of promising code examples that didn't work but gave me the idea of structure concept for my function. Official Django docs 1 Official Django docs 2 Stack Overflow 1 Stack Overflow 2 The function that I have so far is working but I can't implement it in Django template. My function/template tag: from ..models import Timetables from django import template register = template.Library() … -
Least painful way of not using int4 as primary key in Django user models?
I'm new to Django, and upon running the first migration, it seems the primary key ID of the auth_users table is an int4. Looking through the docs, it seems if I use any kind of custom User model, for example to bigint or uuid, I am opening a can of worms and losing Django Admin functionality and possibly all sorts of auth scaffolding functionality? Is there a standard way of not using int4 that I'm failing to see, let's say using UUID, short of going full custom on the auth backend? Tried custom model extending django.contrib.auth.models.AbstractUser. Django Admin stops working, which seems expected according to documentation. However, auth scaffolding, such as python manage.py createsuperuser also starts throwing errors, such as django.db.utils.IntegrityError: null value in column "id" of relation "users_user" violates not-null constraint. This is when id is a Postgres UUID. Here's the User model: class User(AbstractUser): id = models.UUIDField(primary_key=True) -
How do I use a statically hosted design template in a Django Project
I need to use elements from a statically hosted design template in a django site. When I try using resources from the statically hosted site hosted on github pages the content is available, however when I hosted the static host on an ec2 instance (using http with Apache) the content from the design template is not available. Any thoughts on what the issue might be? Possibly using http vs https? Ideally I would like the static content to be hosted in AWS in order to control access to it and do not want to use django's local features for rendering static content. I tried using a statically hosted design template hosted over github pages and an ec2 instance, it works on the github pages but not the ec2 host. I tried changing the aws security groups on the ec2 instance -
ImportError: Couldn't import Django having it installed
I'm trying to run a Django app on an Ubuntu VM but when I execute python manage.py runserver I get this error message: ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? The code is de default of a Django project, ie, try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc I've tried with all of the things described in this post (ie, I'm in a venv reciently created with django installed, checked the django installation, verified that PYTHONPATH is pointing to venv/lib/python3.8/site-packages, etc.) but I still have the error. Any idea? -
Django new entry fetching previous entry in Postgres and not creating a new one
This is my first time here, and I'm trying to develop an app for a personal project (journal app) using Django and Postgres. When I use the Shell method, I am able to create a new entry into a table defined in my Postgres DB. However, when using the browser method, it keeps retrieving the last entry in the DB instead of creating a new one. I tried calling the entry_id in my views.py file and made sure to call the save() method to save a new entry. But instead, it keeps fetching the latest entry from the DB. Any help and/or direction is highly appreciated by someone who's just learning. Misael VIEWS.PY from django.shortcuts import render, redirect from .models import Entry from .forms import EntryForm from django.urls import reverse def entry_form(request): latest_entry = Entry.objects.latest('id') latest_entry_id = latest_entry.id if latest_entry else None if request.method == 'POST': form = EntryForm(request.POST) if form.is_valid(): entry = form.save() # Save the form data to the database return redirect(reverse('journal:entry_success', kwargs={'latest_entry_id': entry.id})) # Pass the latest_entry_id as a parameter else: print('Form errors:', form.errors) else: form = EntryForm() return render(request, 'journal/entry_form.html', {'form': form, 'latest_entry_id': latest_entry_id}) def entry_list(request): entries = Entry.objects.all() return render(request, 'journal/entry_list.html', {'entries': entries}) def entry_success(request, … -
Display the value of current foreignkey in update form when limiting queryset choice
I have a model named TimeTable (as shown below). In my update form I want to display the current value of the foreignkey field (say 'mon_1'). Since I am limiting the foreignkey choices using queryset in my form, the current value isn't being displayed. So i set initial value of the field 'mon_1' as the current model instance's mon_1, but it does not work. What is the mistake I am doing #models.py class TimeTable(models.Model): standard_choice = ( ('Grade 1','Grade 1'), ('Grade 2','Grade 2'), ('Grade 3','Grade 3'), ('Grade 4','Grade 4'), ('Grade 5','Grade 5'), ('Grade 6','Grade 6'), ('Grade 7','Grade 7'), ('Grade 8','Grade 8'), ('Grade 9','Grade 9'), ('Grade 10','Grade 10'), ('Grade 11','Grade 11'), ('Grade 12','Grade 12'), ) section_choice = ( ('A','A'), ('B','B'), ('C','C'), ('D','D'), ) standard = models.CharField(max_length=256,choices=standard_choice) section = models.CharField(max_length=1,choices=section_choice) mon_1 = models.ForeignKey(Teachers,on_delete=models.CASCADE,related_name='mon_1_subject_teacher') mon_2 = models.ForeignKey(Teachers,on_delete=models.CASCADE,related_name='mon_2_subject_teacher') mon_3 = models.ForeignKey(Teachers,on_delete=models.CASCADE,related_name='mon_3_subject_teacher') mon_4 = models.ForeignKey(Teachers,on_delete=models.CASCADE,related_name='mon_4_subject_teacher') mon_5 = models.ForeignKey(Teachers,on_delete=models.CASCADE,related_name='mon_5_subject_teacher') tue_1 = models.ForeignKey(Teachers,on_delete=models.CASCADE,related_name='tue_1_subject_teacher') tue_2 = models.ForeignKey(Teachers,on_delete=models.CASCADE,related_name='tue_2_subject_teacher') tue_3 = models.ForeignKey(Teachers,on_delete=models.CASCADE,related_name='tue_3_subject_teacher') tue_4 = models.ForeignKey(Teachers,on_delete=models.CASCADE,related_name='tue_4_subject_teacher') tue_5 = models.ForeignKey(Teachers,on_delete=models.CASCADE,related_name='tue_5_subject_teacher') wednes_1 = models.ForeignKey(Teachers,on_delete=models.CASCADE,related_name='wed_1_subject_teacher') wednes_2 = models.ForeignKey(Teachers,on_delete=models.CASCADE,related_name='wed_2_subject_teacher') wednes_3 = models.ForeignKey(Teachers,on_delete=models.CASCADE,related_name='wed_3_subject_teacher') wednes_4 = models.ForeignKey(Teachers,on_delete=models.CASCADE,related_name='wed_4_subject_teacher') wednes_5 = models.ForeignKey(Teachers,on_delete=models.CASCADE,related_name='wed_5_subject_teacher') thurs_1 = models.ForeignKey(Teachers,on_delete=models.CASCADE,related_name='thurs_1_subject_teacher') thurs_2 = models.ForeignKey(Teachers,on_delete=models.CASCADE,related_name='thurs_2_subject_teacher') thurs_3 = models.ForeignKey(Teachers,on_delete=models.CASCADE,related_name='thurs_3_subject_teacher') thurs_4 = models.ForeignKey(Teachers,on_delete=models.CASCADE,related_name='thurs_4_subject_teacher') thurs_5 = models.ForeignKey(Teachers,on_delete=models.CASCADE,related_name='thurs_5_subject_teacher') fri_1 = models.ForeignKey(Teachers,on_delete=models.CASCADE,related_name='fri_1_subject_teacher') fri_2 = models.ForeignKey(Teachers,on_delete=models.CASCADE,related_name='fri_2_subject_teacher') fri_3 = models.ForeignKey(Teachers,on_delete=models.CASCADE,related_name='fri_3_subject_teacher') fri_4 = models.ForeignKey(Teachers,on_delete=models.CASCADE,related_name='fri_4_subject_teacher') … -
Is there a way to optimize the query for this piece of code؟
I want that when the user gets the messages of a page, the field **seen **of all unread messages should be set to True Is there a way to **improve **and **optimize **this code below? I have 4 table (user, room, message, seen) One user can have several rooms and one room can have several users A user can send several messages and a message can only be related to a specific user And one message can be seen by several users (seen table) models.py file: class User(models.Model): username = models.CharField(max_length=255, unique=True) sso_id = models.BigIntegerField(null=True) is_active = models.BooleanField(default=False) date_join = models.DateTimeField(auto_now_add=True) is_admin = models.BooleanField(default=False) def __str__(self): return f"{self.username}|{self.is_admin}" class Room(models.Model): name = models.CharField(max_length=255) users = models.ManyToManyField(User, related_name="rooms") def __str__(self): return f"{self.name}" class Message(models.Model): content = models.TextField() seen = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="messages") room = models.ForeignKey(Room, on_delete=models.CASCADE, related_name="room_messages") replied_to = models.ForeignKey('self', null=True, blank=True, on_delete=models.SET_NULL) def __str__(self): return f"{self.user.sso_id}: {self.content} [{self.created_at}]" class Seen(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) message = models.ForeignKey(Message, on_delete=models.CASCADE, related_name="seens") date_seen = models.DateTimeField(auto_now_add=True) views.py file: class MessageViewSet(GenericViewSet, ListModelMixin, RetrieveModelMixin, DestroyModelMixin): def list(self, request, *args, **kwargs): queryset = self.get_queryset() if self.kwargs.get("room_pk"): queryset = queryset.filter(room_id=self.kwargs.get("room_pk")) filter_queryset = self.filter_queryset(queryset) page = self.paginate_queryset(filter_queryset) if page is not None: serializer … -
Django test multiple databases managed and unmanaged
My setup: one managed database for "django-stuff" (auth, admin, contenttypes, sessions) one unmanaged database for the company_db I am trying to create a test databases for both. Django only sets up the test database for the company_db and adds the tables from django-stuff to that db. It does not add the company_db tables to the django_test_company_db. I was hoping django would create an im memory database for django-stuff and create a sql database django_test_company_db with the tables of the company_db model. # test_stuff.py from django.test import TestCase class TestStuffClass(TestCase): databases = ['default', 'company_db'] def test_post_01(self): pass # settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / CONFIG('SQLITE_LOCATION', default='') / 'db.sqlite3', }, 'company_db': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'company_db', 'USER': 'username', 'PASSWORD': '', 'HOST': db_host, 'PORT': db_port, 'TEST': {'NAME': 'django_test_company_db'}, }, } DATABASE_ROUTERS = [ 'api.dbrouter.AuthRouter', 'api.dbrouter.company_db_router', ] TEST_RUNNER = 'api.test.runner.UnManagedModelTestRunner' I added a custom test runner to switch the model meta fields to managed = True from django.test.runner import DiscoverRunner class UnManagedModelTestRunner(DiscoverRunner): def setup_test_environment(self,**kwargs): from django.apps import apps get_models = apps.get_models self.unmanaged_models = [m for m in get_models() if not m._meta.managed] for m in self.unmanaged_models: m._meta.managed = True super().setup_test_environment(**kwargs) def teardown_test_environment(self, *args, **kwargs): super().teardown_test_environment(**kwargs) for m in self.unmanaged_models: m._meta.managed … -
How to retrieve the first object for each set of values in a django filter operation?
I'm running a django 1.29 app on a postgresql database. I have a model similar to this: class DataFile(models.Model): user = models.ForeignKey('data.User', verbose_name='Data View') period = models.ForeignKey('data.Period', verbose_name='Period') category = models.ForeignKey('data.Period', verbose_name='Period') created = models.DateTimeField(auto_now_add=True,null=True) My code is currently retrieving objects that the program needs as this: pending_ids = pending_files.values_list("id", flat=True).distinct() my_data = pending_files.values_list("user_id","category_id","period_id") import_files_pending=[] for u, c, p in pending_bu_way_period: last_file_bpw = DataFile.objects.filter(user_id=u, period_id=p,category_id=c).order_by('-created').first() if last_file_bpw and last_file_bpw.id in pending_ids: import_files_pending.append(last_file_bpw) But is very inefficent, so I tried refractoring and came up with this: import_files_pending2 = DataFile.objects.filter(id__in=pending_ids,user_id=my_data.values_list("user_id", flat=True), category_id__in=my_data.values_list("category_id", flat=True), period_id__in=my_data.values_list("period_id", flat=True)).order_by('user_id', 'period_id', '-created').distinct("from_who_id", 'period_id') But it appears to retrieve much more objects other than the ones I need. What am I doing wrong? Why is my refractoring giving different results? For what I understand, my query is not retrieving only the first instance for the other values' combination, but any of them. -
Django with react router dont work and show empty page
I am using react inside django. I use npx create-react-app and npm run build to create react . The structure looks like this frontend main mysite In react I have two components. Form and App. App is the one that renders all other components. In settings I have configured frontend/build to be the templates. main/views.py def createUser(request): return render(request, 'index.html') main/urls.py from django.urls import path, re_path from . import views urlpatterns = [ path('register/', views.createUser), ] frontend/src/App.js import Form from './Form'; import { BrowserRouter as Router, Routes, Route} from 'react-router-dom'; <Router> <Routes> <Route exact path='/register' element={<Form/>} /> </Routes> </Router> When I go to /register I get a blank page with the css that I wrote for form.js but nothing else shows. -
How to resolve an InconsistentMigrationHistory in Django?
In our django project we had over 900 migrations and they were slowing down our tests. Due to complex interdependencies between apps, we decided that squashing wasn't a real option, so we wanted to reset them. However we have a couple of 3rd party apps as well (celery etc.) with their own migrations. After running python manage.py shell -c "from django.db import connection; cursor = connection.cursor(); cursor.execute(\"DELETE FROM django_migrations WHERE app IN ('api', 'user');\")" and makemigrations we are now trying to apply the migrations with --fake-initial. We are now getting the error django.db.migrations.exceptions.InconsistentMigrationHistory: Migration admin.0001_initial is applied before its dependency user.0001_initial on database 'default'. which makes sense as the database currently "thinks" that it has celery, admin etc. installed, but not user (even though it has). How could we work around this issue? Also we can't loose any data, otherwise I would just delete the migrations for this as well or reset the entire database.