Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Let Django form add class to input in case of error
I'm using Django 4.2.9 and need a form add an additional class to an input field, in case the validiation failed. I can already add classes for every case, but I do not know how to do it for the error-case. class ItemForm(forms.models.ModelForm): class Meta: model = Item fields = ("text", ) widgets = { "text": forms.widgets.TextInput( attrs={ "placeholder": "Enter a to-do item", "class": "form-control form-control-lg", } ), } error_messages = {"text": {"required": EMPTY_ITEM_ERROR}} def save(self, for_list): self.instance.list = for_list return super().save() I'd like to have class="form-control form-control-lg is-invalid" for the text-input. <form method="POST" action="/lists/8/"> <input type="text" name="text" value="Buy wellies" placeholder="Enter a to-do item" class="form-control form-control-lg" required id="id_text"> <input type="hidden" name="csrfmiddlewaretoken" value="vcojkMtz3GeonURczjMwIsbsDPQUbeKgrXrPIxZY4jIJSfuUKKGVgaj7wLQBatsd"> <div class="invalid-feedback"><ul class="errorlist"><li>You&#x27;ve already got this in your list</li></ul></div> </form> -
django obtain a value from a determinated queryset with a string?
I want to get or obtain the data from a selected queryset with a string, something like this: queryset= BasicModel.objects.all() x = 10 my_atribute = "name" queryset[x]["my_atribute"] values() don't work, because it's give me, in ForeingKeys model, the key and not the data. -
I can't apply the migrations in Django DB
I am Facing a problem with my project, (cant apply the changes on Django DB) There was an empty field and it didn't set it to Null = TRUE, Blank =True, when I migrated it kept giving me this error message : ''' django.db.utils.IntegrityError: NOT NULL constraint failed: new__orders_order.total ''' I tried to set the values in the cart model to True and then I changed them to False, It didn't solve the problem. I tried importing the Integrity error, still didn't solve the issue : ''' def save(self, *args, **kwargs): try: super.save(*args, **kwargs) except IntegrityError: self.code = generate_code() super.save(*args, **kwargs) ''' Models ''' from django.db import models, IntegrityError from django.contrib.auth.models import User from django.utils import timezone from utils.generate_code import generate_code from products.models import Product from accounts.models import Address import datetime ORDER_STATUS = ( ('Received', 'Received'), ('Processed', 'Processed'), ('Shipped', 'Shipped'), ('Delivered', 'Delivered') ) class Order(models.Model): user = models.ForeignKey(User,related_name='order_owner', on_delete = models.SET_NULL, null = True, blank = True) status = models.CharField(choices=ORDER_STATUS, max_length=12) code = models.CharField(default=generate_code, max_length=20,unique=True) order_time = models.DateTimeField(default=timezone.now) delivery_time = models.DateTimeField(blank=True, null=True) delivery_address = models.ForeignKey(Address, related_name='delivery_address', on_delete=models.SET_NULL, null=True,blank = True) coupon = models.ForeignKey('Coupon', related_name='order_coupon', on_delete=models.SET_NULL, null=True,blank = True) total = models.FloatField(null=True,blank = True) total_with_coupon = models.FloatField(null=True,blank = True) def save(self, … -
Django: Subclassing django.forms.widgets.Media
I want to use a custom javascript widget in my app. The javascript is not static, but dependant on template variables that I have already successfully attached to the widget as attributes (it's a MultiWidget in case that matters). Since the media property can only render static javascript, I was thinking of using the html template renderer in an own subclass MediaDirect(widgets.Media). For that, I have also subclassed Media.render_js and Media.get_absolute_path so that it uses django.template.loader.render_to_string and pastes the content between a <script></script> tag: from django.template.loader import render_to_string from django.utils.html import format_html class MediaDirect(widgets.Media): """Media class that directly renders a template, using the media's parent as context. Important: Javascript or CSS *templates* are accessed per definition of settings.TEMPLATES, not settings.STATIC_URL, since they are not static. """ def __init__(self, context, *args, **kwargs): self.context = context super().__init__(*args, **kwargs) def render_js(self): print("This is never called") result = [] for path in self._js: js = render_to_string(self.absolute_path(path), self.context) ########## <--- result.append(format_html("<script>{}</script>", js)) ########## <--- return result def absolute_path(self, path): if path.startswith(("http://", "https://", "/")): return path return path class NoUISliderMinMaxWidget(widgets.MultiWidget): template_name = "widgets/nouislider_minmax.html" def _get_media(self): """ Media for a multiwidget is the combination of all media of the subwidgets. Override method to use MediaDirect instead of … -
Default pagination with strawberry django
According to the doc and this issue there is no default pagination or maximum limit on returned results. I've managed to have a default pagination by defining field_cls : PAGINATION_MAX_LIMIT = 1000 class DefaultPaginationStrawberryDjangoField(StrawberryDjangoField): def apply_pagination(self, queryset, pagination=None): if pagination is None: pagination = OffsetPaginationInput() if pagination.limit > PAGINATION_MAX_LIMIT or pagination.limit == -1: pagination.limit = PAGINATION_MAX_LIMIT return super().apply_pagination(queryset, pagination) @strawberry.django.type(Project, pagination=True) class ProjectType: ... @strawberry.type class Query: projects: list[ProjectType] = strawberry.django.field(field_cls=DefaultPaginationStrawberryDjangoField) Since I do not want to use Relay, there is a better / cleaner way ? -
Image not changing in Django edit view
def edit_image(request, pk): current_image = get_object_or_404(Images, pk=pk) if request.method == "POST": form = EditImage(request.POST, request.FILES, instance=current_image) print(form) if form.is_valid(): image_path = current_image.image.path print(image_path) print("hello \n\n\n") if os.path.exists(image_path): print("path exists") os.remove(image_path) form.save() messages.success(request, "Image updated successfully") return redirect("index") return render(request, "edit.html", {"image": current_image}) I have this edit_image view which isn't updating the image to a new image. Why is it happening and how do i fix it. I tried the above code and I expected the image to change to a new image after the user chooses an image and submits it. -
HTTP Error 500.0 - Internal Server Error An unknown FastCGI error occurred
HTTP Error 500.0 - Internal Server Error An unknown FastCGI error occurred Most likely causes: IIS received the request; however, an internal error occurred during the processing of the request. The root cause of this error depends on which module handles the request and what was happening in the worker process when this error occurred. IIS was not able to access the web.config file for the Web site or application. This can occur if the NTFS permissions are set incorrectly. IIS was not able to process configuration for the Web site or application. The authenticated user does not have permission to use this DLL. The request is mapped to a managed handler but the .NET Extensibility Feature is not installed. Things you can try: Ensure that the NTFS permissions for the web.config file are correct and allow access to the Web server's machine account. Check the event logs to see if any additional information was logged. Verify the permissions for the DLL. Install the .NET Extensibility feature if the request is mapped to a managed handler. Create a tracing rule to track failed requests for this HTTP status code. For more information about creating a tracing rule for failed requests, … -
raise e.__class__( ValueError: Field '_id' expected a number but got 'get_recent_products'. ->?
in windows 10 , i'm using react-router-dom 5.2.0 and react-redux 7.2.5 and react 17.0.2 and axios 0.21.4 and WebStorm 2023.1.3 IDE and PyCharm Community Edition 2023.2 and djangorestframework==3.14.0 and Django==4.2.4 and djangorestframework-simplejwt==5.3.0. Note: Although this question is repeated, I hope that I will not encounter a typo error in this forum, because I really did not find the answer in the set of answers that I searched and observed, and also this error in this program is very stupid and I do not have a specific answer for it, so I have to ask my question. Should I bring it up? information: Actually, in this class based view of Django, I have used pagination for django-rest-api, and my project encountered this error after these changes, and in fact, first in the functional form of this Django view, product_id or ID I had used the product, but I deleted it because I didn't need it, so I applied the necessary changes to the url and django class base view and deleted the product id, but still my project is missing the id due to this error. Despite these modifications it shows in product_urls.py and product_views.py BACKEND: Consider - product_views.py: class GetRecentProducts(GenericAPIView): … -
How to Execute Oracle SQL Query with Multiple Database Links in Django?
I'm working on a Django project where I need to execute a complex Oracle SQL query that involves multiple database links. I have already configured the database credentials for both databases in my Django settings, but I'm struggling with how to correctly execute a query that fetches data from different databases through these links. Here's a sample of the type of query I'm trying to execute: SELECT CASE WHEN ACDMH_LOC_CODE LIKE '02%' THEN 'KHOBAR' WHEN ACDMH_LOC_CODE LIKE '03%' THEN 'RIYADH' ELSE 'JEDDAH' END AS Region, ACDMH_INTF_YN, ACDMH_TRANSACTION_TYPE AS TRANSACTION_TYPE, ACDMH_SOURCE_DOC_NO AS SOURCE_DOC_NO, TO_CHAR(ACDMH_TRANSACTION_DATE, 'dd-MM-yyyy') AS TRANSACTION_DATE, ACDMH_CUSTOMER_ID AS CUSTOMER_No, CUSTOMER_NAME, TO_CHAR(ACDMH_CRE_DATE, 'dd-mm-yyyy') AS Pushed_date_WinIT, TO_CHAR(ACDMH_CRE_DATE, 'hh:mi:ss AM') AS Pushed_time_WinIT, ACDMH_INTF_ORA_REF AS ERP_REF, ACDMH_LOC_CODE AS LOC_CODE, ACDMD_ORIGINAL_INVOICE_NO AS ORIGINAL_INVOICE_NO, ACDMD_OLD_VALUE AS fake_PRICE, ACDMD_NEW_VALUE AS selling_price, ACDMD_TOTAL AS tran_value, ACDMD_TAX_AMOUNT AS TAX_AMOUNT FROM AX_CREDIT_DEBIT_MEMO_HEADERS@erpbridge INNER JOIN AX_CREDIT_DEBIT_MEMO_LINES@erpbridge ON ACDMH_HEADER_ID = ACDMD_HEADER_ID LEFT JOIN AXKSA_ORACLE_CUSTOMER ON CUSTOMER_NUMBER = ACDMH_CUSTOMER_ID WHERE [some conditions]; This query involves database links (@erpbridge) to other sources. I'm unsure how to execute such a query in Django, especially considering the database links. I have the following questions: How can I execute this Oracle SQL query in Django, given the use of multiple database links? Are there any specific configurations … -
Slugify when editing an entry
By adding prepopulated_fields = {'slug': ('title',)} to admin model, Django slugifies the slug field in real-time i.e. as I type in the title field, but only when adding a new entry. After the entry is saved and I come back to edit the title field, the slugification (that's not a word) does not happen and I have to override the save() method to re-slugify, however that doesn't provide the real-time functionality. I have tried to find something related by looking at the source code of the templates, but failed. So is there any way to achieve the real-time slugification of the prepopulated field when editing an entry? -
Use serializer in Django (GeoDjango) to include both model field and some related ForeignKey fields
In my Django project, I have two model Home and Tenant. model Home is based on geodjango model and has a PointField. Model Tenant has the person information, and also has a ForeignKey to a Home. from django.db import models from django.contrib.gis.db import models as geomodels class Home(geomodels.Model): location = models.PointField() code = models.IntegerField() # many other fields class Tenant(models.Model): home = models.ForeignKey(Home, on_delete=models.CASCADE) person_name = models.TextField() # many other fields I use serializer to turn a Queryset of Homes into geojson. The thing is, I want to also include some fields of the last Tenant model object of each well in that geojson, too (As they are home fields, but with a prefix tenant__ to have seperated name from original home fields). I also prefer not to use Django-Rest-Framework. Could you help me? -
Azure SpeechSynthesizer Problem with Safari Browser
We have a ReactJS frontend app, using Django (rest framework) as backend. We are developing an AI-Based Avatar Assistant for businesses which would answer various questions. Here is a demo page: https://sales.airdec.net/ The problem is we have no issue with the process of making the avatar talk in Chrome or Firefox. Although it won't work it Safari Browser. I've been searching for a week now and still have no clue what could be the reason. reproduce problem: Navigate here: https://sales.airdec.net/ Click on the hamburger menu and then Introduction OR Just ask a question At first i was using NodeJS as the backend and was having a request/response error in Safari only (preflight response is not successful 421) So, i decided to transfer the code to Python/Django (the one i have more experience in) and now it still not working despite having no network or console error. -
Django Dynamic Navbar Links
I have a Django website where I have two separate user bases, one is CustomUser the other is Agent. Both models extend AbstractUser model. Now I have separate login urls for both and both logins work fine, like Agents can login through AgentSignIn form only and users can login through UserSignIn form only. But now a problem is that when I login as an Agent through AgentSignIn form, I want to show the links Dashboard(agent dashboard) and Agent Sign Out instead of Sign In and Agent Sign In links. But the problem is I don't know how to let my home view know if an Agent is authenticated or a user. Also how do I write the base.html code? My models.py: class CustomUser(AbstractUser): email = models.EmailField(unique=True) groups = models.ManyToManyField(Group, related_name='CustomUser_set', blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.') user_permissions = models.ManyToManyField(Permission, related_name='customuser_set', blank=True, help_text='Specific permissions for this user.') is_user = True class Profile(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE) phonenumber = models.IntegerField() def __str__(self): return f'{self.user.username} Profile' class Agent(AbstractUser): username = models.CharField(max_length=100, unique=True) name = models.CharField(max_length=100) agent_email = models.CharField(max_length=100, unique=True) password = models.CharField(max_length=200) image = models.ImageField(upload_to = 'Images/') bio = models.TextField() … -
Put pinpoints on canvas and leave comment in html/js/django
I have a django project and i am implementing functionallity to have some pinpoint containing comment on my canvas layout: <input type="hidden" id="imageLoader" name="imageLoader"/> I have corresponding JS where I achieve adding pinpoint (x, y coordinates) on canvas drawing/image and also relevant comment on it via modal window once submit button is hit. <!-- Modal --> <div class="modal fade" id="commentModal" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="commentModalLabel" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered"> <div class="modal-content"> <div class="modal-header"> <h1 class="modal-title fs-5" id="commentModalLabel">Add Comment</h1> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> <form id="commentForm"> <div class="mb-3"> <label for="comment" class="form-label">Comment:</label> <textarea class="form-control" id="comment" name="comment" rows="3"></textarea> </div> <button type="submit" class="btn btn-primary">Submit</button> </form> </div> </div> </div> </div> JS code: {% block javascript %} <script> document.addEventListener("DOMContentLoaded", function () { const getCsrfToken = () => document.cookie.split(';').find(cookie => cookie.trim().startsWith('csrftoken=')).split('=')[1] || ''; const canvas = document.getElementById('myCanvas'); const ctx = canvas.getContext('2d'); const imageUrl = canvas.getAttribute('data-image-url'); const drawingId = canvas.getAttribute('data-drawing-id'); const canvasContainer = canvas.parentElement; const loadServerImage = (url) => { const img = new Image(); img.onload = () => { canvas.width = img.width; canvas.height = img.height; ctx.drawImage(img, 0, 0); {% for pinpoint in pinpoints %} renderPinpoint({{ pinpoint.x_coordinate }}, {{ pinpoint.y_coordinate }}); {% endfor %} }; img.src = url; }; if (imageUrl) { loadServerImage(imageUrl); } const imageLoader … -
On the timeweb server, django-ckeditor does not work in the admin panel
on server: Python == 3.6.9 Django == 3.2.23 django-ckeditor == 5.9.0 the editor was installed according to the instructions https://django-ckeditor.readthedocs.io/en/latest/#section-9 there is no point in rewriting my files: models.py from ckeditor.fields import RichTextField ... education = RichTextField(verbose_name='Education') ... settings.py INSTALLED_APPS = [ ... 'ckeditor', 'ckeditor_uploader' ] STATIC_ROOT = '/home/.../public_html/static/' STATIC_URL = '/static/' # change STATICFILES_DIRS = [ BASE_DIR/'staticfiles' ] if DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) ### CKEDITOR_BASEPATH = "/home/.../public_html/static/ckeditor/ckeditor/" CKEDITOR_UPLOAD_PATH = "uploads/" CKEDITOR_CONFIGS = { 'default': { 'toolbar': 'full', 'height': 300, 'width': 300, }, } after changing the code I started getting an error VM1137 ckeditor.js:260 Uncaught TypeError: Cannot set properties of undefined (setting 'dir') at Object.d (VM1137 ckeditor.js:260:54) at w (VM1137 ckeditor.js:261:181) at Array.y (VM1137 ckeditor.js:261:336) at z (VM1137 ckeditor.js:261:420) at A.CKEDITOR.env.ie.f.$.onerror (VM1137 ckeditor.js:262:429) how can this be solved? I tried changing the paths and reinstalling the application, to no avail. -
Djang/websocket not sending messages
i'm using django and daphne and websocket to make a chat room by following a tutorial on youtube..everything worked fine , but when i send the message it does'nt show the message in the screen....it does not show any errors in the server side ..but shows 2 warniings and one error in the browser console im intermediate in django but completely new to web sockets Here's my script tag: {% endblock %} {% block scripts %} {{ room.slug|json_script:"json-roomname" }} {{ request.user.username|json_script:"json-username"}} <script> const roomName = JSON.parse( document.getElementById("json-roomname").textContent ); const usrName = JSON.parse( document.getElementById("json-username").textContent ); const chatSocket = new WebSocket( "ws://" + window.location.host + "/ws/" + roomName + "/" ); chatSocket.onmessage = function (e) { console.log("onemssage"); const data = JSON.parse(e.data); if (data.message) { let html = '<div class="p-4 bg-gray-200 rounded-xl">'; html += '<p class="font-semibold">' + data.username + "</p>"; html += "<p>" + data.message + "</p></div>"; document.querySelector("#chat-messages").innerHTML += html; } else { alert("The message was empty!"); } }; chatSocket.onclose = function (e) { console.log("onclose", e); }; document .querySelector("#chat-message-submit") .addEventListener("click", function (e) { e.preventDefault(); const messageInputDom = document.querySelector("#chat-message-input"); const message = messageInputDom.value; chatSocket.send( JSON.stringify({ message: message, username: usrName, room: roomName, }) ); messageInputDom.value = ""; return false; }); </script> here's my python file: … -
migration the database and django
(venv) C:\Users\LENOVO\PycharmProjects\Projectpython\mysite>python manage.py makemigrations No changes detected Traceback (most recent call last): File "C:\Users\LENOVO\PycharmProjects\Projectpython\mysite\manage.py", line 22, in main() File "C:\Users\LENOVO\PycharmProjects\Projectpython\mysite\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\LENOVO\PycharmProjects\Projectpython\venv\Lib\site-packages\django\core\management_init_.py", line 446, in execute_from_command_line utility.execute() File "C:\Users\LENOVO\PycharmProjects\Projectpython\venv\Lib\site-packages\django\core\management_init_.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\LENOVO\PycharmProjects\Projectpython\venv\Lib\site-packages\django\core\management\base.py", line 415, in run_from_argv connections.close_all() File "C:\Users\LENOVO\PycharmProjects\Projectpython\venv\Lib\site-packages\django\utils\connection.py", line 85, in close_all conn.close() File "C:\Users\LENOVO\PycharmProjects\Projectpython\venv\Lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\LENOVO\PycharmProjects\Projectpython\venv\Lib\site-packages\django\db\backends\base\base.py", line 358, in close self._close() File "C:\Users\LENOVO\PycharmProjects\Projectpython\venv\Lib\site-packages\djongo\base.py", line 208, in _close if self.connection: File "C:\Users\LENOVO\PycharmProjects\Projectpython\venv\Lib\site-packages\pymongo\database.py", line 1337, in bool raise NotImplementedError( NotImplementedError: Database objects do not implement truth value testing or bool(). Please compare with None instead: database is not None (venv) C:\Users\LENOVO\PycharmProjects\Projectpython\mysite>python manage.py makemigrations No changes detected Traceback (most recent call last): File "C:\Users\LENOVO\PycharmProjects\Projectpython\mysite\manage.py", line 22, in main() File "C:\Users\LENOVO\PycharmProjects\Projectpython\mysite\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\LENOVO\PycharmProjects\Projectpython\venv\Lib\site-packages\django\core\management_init_.py", line 446, in execute_from_command_line utility.execute() File "C:\Users\LENOVO\PycharmProjects\Projectpython\venv\Lib\site-packages\django\core\management_init_.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\LENOVO\PycharmProjects\Projectpython\venv\Lib\site-packages\django\core\management\base.py", line 415, in run_from_argv connections.close_all() File "C:\Users\LENOVO\PycharmProjects\Projectpython\venv\Lib\site-packages\django\utils\connection.py", line 85, in close_all conn.close() File "C:\Users\LENOVO\PycharmProjects\Projectpython\venv\Lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\LENOVO\PycharmProjects\Projectpython\venv\Lib\site-packages\django\db\backends\base\base.py", line 358, in close self._close() File "C:\Users\LENOVO\PycharmProjects\Projectpython\venv\Lib\site-packages\djongo\base.py", line 208, in _close if self.connection: File "C:\Users\LENOVO\PycharmProjects\Projectpython\venv\Lib\site-packages\pymongo\database.py", line 1337, in bool raise NotImplementedError( NotImplementedError: Database objects do not implement truth value … -
Getting a 500 Internal Server Error when Booking a Hotel with Amadeus API
I'm working on integrating the Amadeus API into my application to allow users to book hotels. However, I'm encountering a 500 Internal Server Error when attempting to book a hotel using the provided offer ID. Here's a simplified version of my Python code: @app.post("/book_hotel") async def book_hotel( offer_id: str = Query(..., description="Offer ID") ): try: # Confirm availability of a given offer offer_availability = amadeus.shopping.hotel_offer_search(offer_id).get() if offer_availability.status_code == 200: guests = [ { 'id': 1, 'name': {'title': 'MR', 'firstName': 'BOB', 'lastName': 'SMITH'}, 'contact': {'phone': '+33679278416', 'email': 'bob.smith@email.com'} } ] payments = { 'id': 1, 'method': 'creditCard', 'card': { 'vendorCode': 'VI', 'cardNumber': '4151289722471370', 'expiryDate': '2023-08' } } booking = amadeus.booking.hotel_bookings.post(offer_id, guests, payments).data else: return {"response": 'The room is not available'} except ResponseError as error: raise HTTPException(status_code=500, detail=str(error.response.body)) return { "id": booking[0]['id'], "providerConfirmationId": booking[0]['providerConfirmationId'] } I'm providing a valid offer ID, '8ANZ20L7F2', but I'm consistently getting a 500 error. I've checked my API credentials, and they seem to be correct. What could be causing this 500 Internal Server Error when trying to book a hotel with the Amadeus API? Are there any common issues or troubleshooting steps I should consider? The other endpoints for fetching data and so work as expected, only … -
Django Weasyprint PDF output into Postgres Database
I am trying to stick a WeasyPrint html PDF into the Model. Using Django. I can generate the PDF file fine. pdf_file = HTML(string=html,base_url=base_url).write_pdf(stylesheets, [css_path],font_config=font_config) Now what is best way to convert the pdf_file output to a format I can use for the database? class Reports(models.Model): pdf = models.FileField( upload_to='media/pdfs/', max_length=254, ) created = models.DateField(auto_now=False, auto_now_add=True) If I do something like this it creates the file automatically before the Model. fs = FileSystemStorage() report = fs.save(f'pdfs/{uuid}.pdf', File(BytesIO(pdf_file)) ) And gives the table a 'pdf/...' in the database. What is most efficent way to convert the Wesasy HTML into a format the Model can use and let the model save the file? Thanks. -
Using Django_tenants and django_tenant_users for a multi tenancy SAAS
I am creating a SAAS project, what I want is that I will have clients, and each client can have sub clients/departments. So I came across django_tenants and using it, also django_tenant_users. But I am little stuck with, how can I manage a multi level tenancy, where each tenant has multiple tenants. Can I do that ? -
How to manage iterative django migrations when working on same branch with other people
I am working on a django project and many times i will iterate on a new model creating new migration files along the way.The migration file names are different but change parts of the same model. These migration files are also shared with other developers.What is the correct order of operations to execute in order to synchronize the changes with other developers working on the same branch and applying the migrations? I understand that reinitializing the db is a solution but arguably not a very clean one. I have tried this sequence after deleting the last migration in the receiving end but it does not work as expected python manage.py migrate app_name XX #returns to the previous migration python manage.py makemigrations python manage.py migrate # this creates issue because the relations-columns already exist The next logical thing to do is python manage.py migrate --fake However, this does not solve the issue because the updated changes are not reflected. Lastly, I have also tried python manage.py makemigrations --merge but this does not find something to merge. -
Django admin outputs ul for foreignkey instead of dropdown list
that is, instead of a drop-down list, the ul-li tag appears class EpApplicationAdmin(admin.ModelAdmin): list_display = ('id', 'application_status', 'f_iin', 'f_phone', 's_iin', 's_phone', 'entity_bin', 'entity_grnz') list_per_page = 20 search_fields = ["id__id", "f_iin", "s_iin", "f_phone", "s_phone"] list_filter = ('application_status__description', ) -
DJango - different auth models and urls
To Modesl: Customers Agents I've got custom auth for Customers with URL: /customers/ /customers/login.html /customers/logout.html with added middleware auth script in settings.py MIDDLEWARE = [ ... 'main.backends.check_user_customer', ... ] Now i wanna add new sections for new Model: Agent with new URL: /agent/ /agent/login.html /agent/logout.html My goal: to make different login/logout pages, auth backends and custom redirects if each section (eq login_required) also how to prevent open another section when user authenticated NON AUTH /agent/ -> /agent/login.html /customer/ -> /customer/login.html AUTHENTICATED AS AGENT /agent/ -> OK /customer/ -> /customer/login.html AUTHENTICATED AS CUSTOMER /agent/ -> /agent/login.html /customer/ -> OK So the question is: how to make it correct? -
Django-tenants: Tenant App specific URLs throw 404 error, but when included in Shared App works perfectly
I have a Django-tenant based application. In the Shared App I have a 'publicApp' and in Tenant Apps I have 'AHIDev' & 'ahi'. Now this ahi is my django project starting point, meaning ahi folder includes settings.py, wsgi.py, etc. When I try the urls included in publicApp everything is working as expected. But problem arises when I try the urls included in 'ahi' or 'AHIDev'. Everytime Django throws 404 error. Now if I include the tenant urls in publicApp it is again working. My settings.py file: SHARED_APPS = [ 'django_tenants', ... 'publicApp', ] TENANT_APPS = [ #Project related apps 'ahi', 'ahiDev', ] INSTALLED_APPS = SHARED_APPS + [app for app in TENANT_APPS if app not in SHARED_APPS] I cannot find the problem. Can someone help? i'm new to Django-tenants. Thank you. ahi/urls.py: urlpatterns = [ #For standard user logins path('AHIDev/',include('ahiDev.urls')), ] ahidev/urls.py urlpatterns = [ path('test_get/', views.test_get, name="test_get"), .... ] -
How do i collect static files in a django application deployed in digital ocean and store this in a staticfiles folder in AmazonS3 bucket?
I have a dockerized app deployed in digital ocean. However it fails to collect static files to be used in production. I have a static folder (static) containing the app's static files in django. I want to save the static files from the local static directory in a staticfiles folder in digital ocean.How can i solve this? Attached is my settings.py in Django for storage settings. AWS_ACCESS_KEY_ID = os.getenv("AWS_ACCESS_KEY_ID") AWS_SECRET_ACCESS_KEY = os.getenv("AWS_SECRET_ACCESS_KEY") AWS_STORAGE_BUCKET_NAME = os.getenv("AWS_STORAGE_BUCKET_NAME") AWS_S3_ENDPOINT_URL = os.getenv("AWS_S3_ENDPOINT_URL") AWS_S3_OBJECT_PARAMETERS = { "CacheControl": "max-age=86400", } AWS_LOCATION = "static" AWS_S3_SIGNATURE_VERSION = "s3v4" STATIC_URL = 'static/' STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles") # STATICFILES_DIRS = [ # os.path.join(BASE_DIR, "static"), # ] STATICFILES_STORAGE = "storages.backends.s3boto3.S3Boto3Storage" # Media files MEDIA_URL = "https://%s/%s/" % ( AWS_S3_ENDPOINT_URL, "media", ) # Change this to a different path # DEFAULT_FILE_STORAGE = "storages.backends.s3boto3.S3Boto3Storage" # Configuring Django to use DigitalOcean Spaces for media files DEFAULT_FILE_STORAGE = "storages.backends.s3boto3.S3Boto3Storage" Here is my Dockerfile: FROM python:3.10 ENV PYTHONUNBUFFERED=1 WORKDIR /code # Install build dependencies RUN apt-get update && apt-get install -y tzdata libpython3-dev gcc # Upgrade pip and setuptools RUN pip install --upgrade pip setuptools # Copy requirements and install dependencies COPY requirements.txt . # RUN pip install poetry # RUN pip install django_cleanup # RUN …