Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django managed=False model save doing insert instead of update and failing for duplicate PK
I'm connected to a legacy database using PyODBC. Some models insert and update just fine, however this one doesn't. When we grab existing records using the ORM, it tries to do an insert on save instead of an update class PurchaseOrder(models.Model): purchaseorderid = models.BigAutoField(db_column='PurchaseOrderId', primary_key=True) ticketnumber = models.CharField(db_column='TicketNumber', unique=True, max_length=20, blank=True, null=True) customer = models.ForeignKey('Customer', to_field='local_id', db_column='CustId', on_delete=models.DO_NOTHING) # a bunch of other irrelevant columns class Meta: managed = False db_table = 'PurchaseOrders' In the shell (or code anywhere else) I can grab an existing PurchaseOrder and even print it's pk just fine: >>> po = PurchaseOrder.objects.all()[76543] # grab a random existing po >>> print(po.pk) 78730 But when I go to save the record, which should do an update -- we've verified the pk exists -- it tries to do an insert and fails due to duplicate pk: >>> po.save() Traceback (most recent call last): File "/home/django/.env/lib/python3.10/site-packages/django/db/backends/utils.py", line 89, in _execute return self.cursor.execute(sql, params) File "/home/django/.env/lib/python3.10/site-packages/mssql/base.py", line 621, in execute return self.cursor.execute(sql, params) pyodbc.IntegrityError: ('23000', "[23000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Violation of PRIMARY KEY constraint 'PK_PurchaseOrders_1'. Cannot insert duplicate key in object 'dbo.PurchaseOrders'. The duplicate key value is (78730). (2627) (SQLExecDirectW)") If I change the model to use … -
Docker + Django + ElasticSearch: Failed to establish a connection
I'm having issues connecting ElasticSearch to Django while dockerizing my application. When I try to run my applicatiom using docker compose, i get the following error: elastic_transport.ConnectionError: Connection error caused by: ConnectionError(Connection error caused by: NewConnectionError(<urllib3.connection.HTTPSConnection object at 0x7fc59132e890>: Failed to establish a new connection: [Errno 111] Connection refused)) Before building the containers, I followed this tutorial, adapting the packages to the versions I wanted. I was able to establish a connection between the Django App and a single-node cluster running on a docker container. I copied the SSL certificate from the ElasticSearch container to the Django app root, and defined the ELASTICSEARCH_DSL on Django settings as: ELASTICSEARCH_DSL = { 'default': { 'hosts': ['https://localhost:9200'], 'http_auth': ('elastic', 'password'), 'verify_certs': True, 'ca_certs' : './http_ca.crt', }, } After building the containers and creating a docker-compose.yml, I didn't find a way to extract the certificate to the Django container. I tried to establish a connection putting 'verify_certs': False but it didn't work. I tried to find a solution, but most of the time I found people using ElastiSsearch 7.x.x while I'm using version 8.10.1. Python Packages django==4.2.6 djangorestframework==3.14.0 django-cors-headers==4.3.0 elasticsearch==8.10.1 elasticsearch-dsl==8.9.0 django-elasticsearch-dsl==8.0 psycopg2-binary==2.9.9 docker-compose.yml version: '3.8' services: db: image: postgres:15.4-alpine3.18 volumes: - postgres_data:/var/lib/postgresql/data/ environment: … -
Django: adding a second 'detailed' view for retrieving extra information
I have set up my urls.py and views.py file to serialize my Projects model in two different ways: detailed information for the 'retrieve' action, and abbreviated information for the 'list' action. This works well so far: /projects/ = list of projects with abbreviated information /projects/12 = detailed information about a specific project (id=12) urls.py: router.register(r'projects', ProjectViewSet, basename='project') views.py class ProjectViewSet(viewsets.ModelViewSet): serializer_class = ProjectSerializerMini # Select a serializer according to the action (i.e.: 'retrieve' will # return a more detailed serialized data than 'list') action_serializers = { 'retrieve': ProjectSerializerDetail, 'list': ProjectSerializerList } def get_serializer_class(self): return self.action_serializers.get(self.action, self.serializer_class) My question is: would it be possible, using the ViewSet framework, to summon a third serializer that would return, say, an even more detailed set of information. Ex.: /projects/12/extradetail The reason for this is that some of these records include geospatial data that is quite voluminous. I would only want to retrieve this extra detail in some cases -
django-simple-history only works in the admin interface
I am trying to get django-simple-history to work. It does work in the admin interface but not in my view code. I recreated the sample but it does not work for me. Models class Poll(models.Model): question = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') history = HistoricalRecords() class Choice(models.Model): poll = models.ForeignKey(Poll, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) history = HistoricalRecords() view: def main_view(request): p = Poll.objects.first() p.question = 'Test' p.save() return HttpResponse('done') It won't create a history entry when i call the view. If u change it in the admin interface i do get a changed entry. Does anyone know what i am doing wrong. Using: Django==4.2.6 django-simple-history==3.4.0 -
How I can use singleton with rabbitmq django celery?
I cannot find a solution. But I found realization on Redis. https://github.com/steinitzu/celery-singleton Please send me the Singleton realization with RabbitMQ if you have. Example: @shared_task(base=SomeSingleton): def some_task(): """deliver or count something""" -
django rest serializer to_representation failing
Im messing around with django rest framework and its serializers, and im running into an error when overriding the create method. serializer class AdddTestModel(serializers.Serializer): name = serializers.CharField() score = serializers.FloatField() score2 = serializers.FloatField() song = serializers.IntegerField() def create(self, validated_data): print(validated_data["song"]) song = Song.objects.get(id=validated_data["song"]) print(song) instance = TestModel.objects.create(name=validated_data["name"], score = validated_data["score"], score2 = validated_data["score2"], song = song) return instance def to_representation(self, instance): representation = super().to_representation(instance) return representation View @api_view(["POST"]) def addTestModel(request): serializer = AdddTestModel(data=request.data) if serializer.is_valid(): serializer.save() print(serializer.data) return Response("hello", status=status.HTTP_201_CREATED) return Response("Error", status=status.HTTP_401_UNAUTHORIZED) I had everything working correctly when I was using a modelSerializer, but wanted to experiment with serializer.Serializer. I know the create method is working as the TestModel object is being persisted into my db. The error seems to be coming from the to_representation method, specifically representation = super().to_representation(instance) The error i am getting is the following Internal Server Error: /api/addTest/ Traceback (most recent call last): File "C:\Users\thoma\Documents\venv\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\thoma\Documents\venv\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\thoma\Documents\venv\lib\site-packages\django\views\decorators\csrf.py", line 56, in wrapper_view return view_func(*args, **kwargs) File "C:\Users\thoma\Documents\venv\lib\site-packages\django\views\generic\base.py", line 104, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\thoma\Documents\venv\lib\site-packages\rest_framework\views.py", line 509, in dispatch response = self.handle_exception(exc) File "C:\Users\thoma\Documents\venv\lib\site-packages\rest_framework\views.py", line 469, … -
How to update Model attributes in production
I have a django app which I deployed three years ago that has been working perfectly and making our life in the laboratory easier. Recently there was a need that wasn't contemplated in the beginning, and I have added some functionality to the app. This involved modifying some Model methods and some AdminModel methods as well. Unfortunately web development is not my field and this was a single thing that I did with Python in my spare time and now I'm not sure what will happen If I pull the changes from the repository. I remember that in development I had to use manage.py migrate manage.py makemigrations after any changes to the models attributes. In this case it's only methods that I have modified. Do I still need to run these commands in the production server? Will I loose data (this can not be tolerated)? I'm using the sqlite standard database that django generates by default. Thanks a lot in advance. -
React Items wont render using Router
I am using routes in a react/django app and I have components that will not render. This is my app.js which renders my homepage. import React, { Component } from "react"; import { render } from "react-dom"; import HomePage from "./Homepage"; export default class App extends Component { constructor(props) { super(props); } render() { console.log("App Here"); return ( <HomePage /> ); } } const appDiv = document.getElementById("app"); render(<App />, appDiv); This is my homepage.js: import React, { Component } from "react"; import RoomJoinPage from "./RoomJoinPage"; import { Routes, Route, BrowserRouter } from "react-router-dom"; export default class HomePage extends Component { constructor(props) { super(props); } render() { console.log("homePage Here") return ( <BrowserRouter> <Routes> <Route path="/" element={<p>Test</p>} /> <Route path="/join" element={<RoomJoinPage />} /> </Routes> </BrowserRouter> ); } } And this is a component I am trying to render: import React from "react"; export default function RoomJoinPage() { console.log("RoomJoinPage component is rendering."); return <h1>Room Join Page</h1>; } I have it working with HTML, and have narrowed it down to the routing issue. Any insight would be helpful. Thanks! I have tried various different routing configurations. My versions are: "react": "^18.2.0", "react-router-dom": "^6.17.0". I would like the components to render on the correct routing. -
Database From An External API in Django
I am new to django I am trying to make an claorie tracker app in which, i want to fetch data from this api "https://api.api-ninjas.com/v1/nutrition?query=" but on checking my model it shows 0 objects.Iam not able to do it correctly, can someone tell me where is the issue and me solve it ` def index(request): if 'name' in request.GET: name = request.GET['name'] url = "https://api.api-ninjas.com/v1/nutrition?query=" + name headers = {'X-Api-Key': 'api key'} response = requests.get(url, headers=headers) if response.status_code == 200: data = response.json().get('data', []) for item in data: FoodItem.objects.get_or_create( name=item['name'], calories=item['calories'], carbohydrates=item['carbohydrates_total_g'], protein=item['protein_g'], fat=item['fat_total_g'], fibre=item['fiber_g'] ) print('saved') else: print(f"Error: {response.status_code}") return render(request, 'food.html') from django.db import models from django.contrib.auth.models import User # Create your models here. class FoodItem(models.Model): name = models.CharField(max_length=255) calories = models.PositiveIntegerField() carbohydrates = models.FloatField() protein = models.FloatField() fibre = models.FloatField() fat = models.FloatField() date = models.DateField() def __str__(self): return self.food_item class UserFoodConsumption(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) food_item = models.ForeignKey(FoodItem, on_delete=models.CASCADE) date = models.DateTimeField(auto_now_add=True) I want to store all information from api to my model "FoodItem" -
How to search multiple fields using objects.filter
I have the following 3 names in my db cid name email 1 | John Smith | jsmith@email.com 1 | June Bug | jbug@email.net 2 | Rick Ross | rross@email.com Is there a way to search 2 parameters as and 'OR' and the last parameter as an 'AND' so the query would be something like this if i pass it like 'm' and for it to search the name or email for the letter 'm', and the also passing it a '1' so that cid=1 So the result would come back as 1 | John Smith | jsmith@email.com 1 | June Bug | jbug@email.net And if i did the same search but passing it 'o', it would search the name or email for the letter 'o' and with cid=1 it would give me the following result 1 | John Smith | jsmith@email.com -
Trade-offs and considerations for conditional tuple unpacking in Python: primarily performance but also stylistic considerations for maintainability
I have a piece of logic in Python that involves tuple unpacking based on conditions. The code instantiates two variables, and assigns to these variables the unpacked values of a tuple. This tuple is defined conditionally: if a conditional_expression is true, then a function executes returning a tuple, else default values are provided and assigned. My understanding is there are two simple ways to implement this, as follows: # Method 1 # if conditional_expression: processed_data, context = tuple_returner(raw_data) else: processed_data, context = raw_data[0], None # Method 2 # processed_data, context = ( tuple_returner(raw_data) if conditional_expression else raw_data[0], None ) Now I have tried both ways, and both work well as expected. My question is two-fold: Is either method likely to be more performant than the other (in a standard CPython implementation)? I do not notice any substantial differences when running timeit tests (although method 2 seems ever so slightly faster), but I was wondering if anything deeper is happening under-the-hood that I'm not aware about. Is either method more Pythonic and generally preferred by the community than the other? I couldn't see anything specific inside PEP8 to guide me on this. Both seem readable to me but this code-base will … -
ORA-12170: TNS:Connect timeout occurred on docker container
Im building a project which connect to a oracleDB remotely using a VPN, the backend is python with django and I dockerized the project until fridays last week everything was working well, after that when i run docker compose up I get this error: django.db.utils.DatabaseError: ORA-12170: TNS:Connect timeout occurred The dockerfile has following structure: FROM python:3.10.12-alpine3.18 ENV PYTHONUNBUFFERED 1 RUN apk add --update --no-cache\ build-base jpeg-dev zlib-dev libjpeg\ gettext\ py3-lxml\ py3-pillow\ openldap-dev\ python3-dev\ gcompat\ && rm -rf /var/cache/apk/* RUN apk add --no-cache libaio libnsl libc6-compat curl bash WORKDIR /opt/oracle RUN wget https://download.oracle.com/otn_software/linux/instantclient/instantclient-basiclite-linuxx64.zip && \ unzip instantclient-basiclite-linuxx64.zip && \ rm -f instantclient-basiclite-linuxx64.zip && \ cd instantclient* && \ rm -f *jdbc* *occi* *mysql* *jar uidrvci genezi adrci && \ mkdir /etc/ld.so.conf.d && \ echo /opt/oracle/instantclient* > /etc/ld.so.conf.d/oracle-instantclient.conf RUN ldconfig /etc/ld.so.conf.d ENV LD_LIBRARY_PATH=/opt/oracle/instantclient_21_11 ENV PATH=/opt/oracle/instantclient_21_11:$PATH RUN echo 'INPUT ( libldap.so )' > /usr/lib/libldap_r.so The DB connection is: DATABASES = { "default": { "ENGINE": "django.db.backends.oracle", "NAME": ( f"{env('DATABASE_SERVER')}:{env('DATABASE_PORT')}/{env('DATABASE_SERVICE_NAME')}" ), "USER": env("DATABASE_USER"), "PASSWORD": env("DATABASE_PASS"), } } What seems more strange to me is that I can perfectly connect to the DB via DBeaver (client) and another test is that I pinged the IP of the DB server and I have a response but, if … -
How to upadate a text for H2 tag from views.py in django
I have the buttons defined in html file. When I click on the button iam sending the name of the button using post request using Ajax and getting it to the views.py , saving it in 'catogory_type'. When iam printing it in the terminal, it is getting printed. But when iam rendering the page, that H2 tag is showing empty without any text. How can I print that value in the page when I clicked on the button. Asper my understanding, after clicking the button in the page, it is not getting reloaded. Iam not sure how to refresh the page to re-render it with updated data again. Please suggest me on this. Thanks:) Need to get the the page refresh with updated data in django. -
python django factory set random locale and then create model based on this locale
I would like to create test models of people of different nationalities. During creation, factory would randomly select nationality from a list of "locale" attributes. It would then determine personal attributes based on the previously drawn nationality. Here is my code, which does not work. It mixes attributes of different nationalities class PersonModelFactory(factory.django.DjangoModelFactory): locale = factory.fuzzy.FuzzyChoice(["cs_CZ", "da_DK", "de_DE", "en_GB", "es_ES", "fr_FR", "hr_HR", "hu_HU", "it_IT", "nl_NL", "no_NO", "pt_BR", "pt_PT", "ro_RO", "sk_SK", "fr_CH", "pl_PL", "de_AT", "es_AR"]) class Meta: model = Person exclude = ("locale",) first_name = factory.Faker("first_name_male", locale=locale) last_name = factory.Faker("last_name_male", locale=locale) nationality = factory.Faker("current_country", locale=locale) ...and so on... In addition, it would be best if half of the people could be British, another half as other mixed nationalities. I tried this code to do so: locale = factory.fuzzy.FuzzyChoice(["en_GB", None]) if locale is None: locale = factory.fuzzy.FuzzyChoice([...]) Unfortunately, only the first line of code is is read and the program only chooses between en_GB and None (which is en_US by default). If statement is ignored. -
I want Small Modal but my modalis not worrk properley as I want
<!-- Modal --> <div class="modal fade" id="deleteItemModal" tabindex="-1" role="dialog" aria-labelledby="deleteItemModalLabel" aria-hidden="true"> <div class="modal-sm modal-dialog " role="document"> </div> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body confirm-delete text-center" > <div class="alert" id="delete_item_alert"></div> <div id="modal-message"></div> <hr> <form action="" method="post" id="form_confirm_modal"> {% csrf_token %} <button type="button" class="btn btn-danger" data-dismiss="modal" id="confirmButtonModal">Delete</button> <button type="button" class="btn btn-primary" data-dismiss="modal">close</button> </form> <input type="hidden" id="address_suppress"/> </div> </div> </div> <div class="modal-body confirm-delete text-center" > <div class="alert" id="delete_item_alert"></div> <div id="modal-message"></div> <script type="text/javascript"> document.addEventListener('DOMContentLoaded', () => { let form_confirm = document.querySelector('#form_confirm_modal') let buttons = document.querySelectorAll("[data-target='#deleteItemModal']"); buttons.forEach(button => { button.addEventListener("click", () => { // extract texts from calling element and replace the modals texts with i if (button.dataset.message) { document.getElementById("modal-message").innerHTML = button.dataset.message; } // extract url from calling element and replace the modals texts with it if (button.dataset.url) { form_confirm.action = button.dataset.url; } }) }); let confirmModal = document.getElementById("confirmButtonModal") confirmModal.addEventListener('click', () => { form_confirm.submit(); }); }); </script> I want modal popup delete confirmation ,The modal is work properley but it is too large i need small modal. I have the above modal ,I use class .modal-sm but it doesnot work .please help me. I want modal popup delete confirmation ,The modal is work properley but it … -
Errno 13 Permission denied: 'images' on Production environment
I'm facing an issue with file permissions when trying to access an AWS S3 bucket in my Django application. Everything works perfectly in my local development environment. However, when I deploy the application to my production environment, I encounter a "Permission Denied" error when trying to read/write from the 'images' directory in the S3 bucket. Locally, I see successful GET and POST requests in my logs, and the S3 URLs are generated as expected. In production, I get an error message saying "Exception in generate_diamond_painting_preview: [Errno 13] Permission denied: 'images'." I've checked my IAM policies and S3 bucket policies, and they seem to allow for the necessary actions. I'm at a loss for what could be causing this discrepancy between my local and production environments. Local Environment Testing: Verified that the S3 bucket interaction works as expected in my local development environment. Files are read and written without any issues. AWS IAM Policy: Reviewed the IAM policy attached to the role/user used by the Django application. The policy allows for full S3 access to the specific bucket and its contents (s3:*). Server Logs: Checked the logs in the production environment to pinpoint the error, which led me to the "Permission … -
Django forms Choicefield parameter session key
I am working on a project which bases operations on the session_key parameter. I would like to fetch data from the database and add the variables into a choicefield in forms. Using the ModelChoiceField(queryset=..., empty_label="(Nothing)") could be an option, but i still cant take in the session_key as a parameter to filter the queryset. so my question, how can i fetch the session_key from the request in views and pass it to the queryset in the forms class? Thx! -
Django Admin: IntegrityError When Adding New or Modifying Existing Models From Django Admin Panel in Browser
I'm encountering a peculiar issue when attempting to add or update existing models through the Django Admin panel. It results in the following error: IntegrityError at /admin/main/user/2/change/ FOREIGN KEY constraint failed Here are the details: Django Version: 4.2.4 Exception Type: IntegrityError Exception Value: FOREIGN KEY constraint failed Exception Location: C:\Users\Administrator\Desktop\oracle\Site #041\site\env\Lib\site-packages\django\db\backends\base\base.py, line 313, in _commit Occurred during: django.contrib.admin.options.change_view Python Version: 3.12.0 Python Executable: C:\Users\Administrator\Desktop\oracle\Site #041\site\env\Scripts\python.exe This error happens when I try to update or add data to an existing model. However, it's worth noting that when I update or add new data using my custom admin interface, everything works as expected. I'm seeking assistance in understanding the root cause of this issue and how to resolve it. Any guidance would be greatly appreciated. -
Htmx POST for Editable Row
I am trying to do an editable row with Django and HTMX. I have trouble editing rows. When I click the edit button, form appears instead of row. I click save after edit fields, nothing happens. Why is there no POST operation? Here is my code edit_link_form.html <td> <form hx-post="{% url 'link:link_update' pk=object.pk %}"> {% csrf_token %} {% load crispy_forms_tags %} {% for field in form %} <td colspan="{{ form|length }}"> <div class="form-row"> <div class="form-group col-md-12"> {{ field|as_crispy_field }} </div> </div> </td> {% endfor %} <td> <button type="submit" class="btn">Submit</button> </td> <td> <button class="btn btn-primary" type="button">Cancel</button> </td> </form> </td> Here is my row.html <tr id="link_list_{{link.pk}}"> <td>{{ link.title }}</td> <td>{{ link.get_full_url }}</td> <td> <span class="p-1 border fs-12 rounded text-light bg-primary"> <a href="{{ link.category.get_absolute_url }}" class="text-decoration-none text-light"> {{ link.category }} </a> </span> </td> <td> {% for shortcode, tags in tags_by_shortcode.items %} {% if shortcode == link.shortcode %} {% for tag in tags %} <li class="list-inline-item border p-1 text-muted fs-12 mb-1 rounded"> <a href="{{ tag.get_absolute_url }}" class="text-decoration-none text-muted"> {{ tag.title }} </a> </li> {% endfor %} {% endif %} {% endfor %} </td> <td> <button class="btn btn-warning" hx-get="{% url 'link:link_update' pk=link.pk %}" hx-target="#link_list_{{link.pk}}"> Edit </button> </td> <td> <button class="btn btn-danger btn-sm float-end" hx-delete="{% url … -
How to generate server code from an OpenAPI Specification (OAS) in Django Rest Framework?
I'm working on a Django Rest Framework project, and I have an OpenAPI Specification (OAS) file that I'd like to use for code generation. My goal is to automatically generate API endpoints, serializers, and views from this OAS file. I'm seeking guidance on how to generate Django Rest Framework code (serializers, views, URLs) based on the OAS file. I'd like to know which tools or libraries are commonly used for this purpose and any steps or configurations I need to follow. Additionally, any tips or best practices for integrating OAS with Django Rest Framework would be greatly appreciated. I've read through the documentation for Django Rest Framework and searched for relevant resources online, but I haven't found a clear path for integrating OAS with Django Rest Framework. Thank you for any guidance or suggestions you can provide! https://spec.openapis.org/oas/v3.1.0 -
displaying a product and all related comment to the product and add new comment form in a single template
I am creating a web store using Django. i want to have a page displays a chosen product and within that page i want to see all the comment related to that specific product and also want to have a form for customers to add new comment for the product. I used class-based list-view and detail-view but the problems are 1- i could not displays related comments using class-based views(actually i could display it by creating a query_set and using template tags) 2- i could not render add new comment form into my template here is my code models.py class Goods(models.Model): goods_main_band = models.ForeignKey( MainBranch, to_field='mb_code', on_delete=models.CASCADE, verbose_name='کد دسته اصلی', default=0 ) goods_sub_band1 = models.ForeignKey( SubBranch1, to_field='sb1_code', on_delete=models.CASCADE, verbose_name='کد دسته فرعی 1', default=0 ) goods_sub_band2 = models.ForeignKey( SubBranch2, to_field='sb2_code', on_delete=models.CASCADE, verbose_name='کد کالا', default=0 ) goods_properties = models.OneToOneField( GoodsProperties, on_delete=models.CASCADE, verbose_name='مشخصات کالا', null=True, blank=True ) goods_specifications = models.OneToOneField( GoodsSpecification, on_delete=models.CASCADE, verbose_name='معرفی کالا', default=0, null=True, blank=True ) name = models.CharField(verbose_name='نام کالا') image = models.ImageField(upload_to='photos/%Y/%m/%d', null=True, blank=True, verbose_name='تصویر کالا') quantity = models.PositiveIntegerField(default=0, verbose_name='تعداد موجود') price = models.DecimalField( decimal_places=0, max_digits=12, default=0, verbose_name='قیمت کالا' ) discount = models.SmallIntegerField(null=True, blank=True, verbose_name='میزان تخفیف') seller = models.ManyToManyField('Seller', verbose_name='کد فروشنده') def __str__(self): return self.name class Comments(models.Model): goods = models.ForeignKey(Goods, … -
Storing 'formattable' strings in database
I'm working on a project where I need to store certain descriptions in a database. These descriptions need to be strings akin to prepared statements in SQL, where I can later 'inject' my own values wherever necessary. The reason is that the data that goes in the fields needs to be generated by the backend on demand (also the descriptions will potentially be localized later on). Currently I'm simply storing the descriptions in the form of "This is the description for {} and {}" and in the backend I call .format on it to pass the generated values. It's probably worth noting that the user can't interact with this procedure, meaning it shouldn't really be a security hole. However, is there a better way of doing this in Django? Or is my design somehow flawed? Thanks. -
Maintaning isolation between modules in Django monolith
In our company, we have a monolith. Right now is not that big but we are already seeing some problems with the isolation between the modules we have. Our setup is pretty similar to other Django backends: we have a common User model and another UserProfile model where we store additional information about the user. As an additional thing, we also have a company model to group our users by company. These models are shared across all the modules, at least they are coupled as foreign keys in the models of the rest of the modules. They are contained in a companies module, where we have our business rules about how many users a company can have, invariants in their profile, etc. I think this is fine because we usually just do simple and fast join by user ID or filter by it, so we treat this dependency as read-only so we don't skip any business rules/boundaries related to the companies module. My problem comes when, for instance, some moduleA, needs to trigger an application service in moduleB. For instance, let's say moduleB needs to access a resource in moduleA. The code would be something like: # The GetResourceInterface is … -
Django Migrations are not Migrating on production
I am using MySql DB,I am having some problems with the migrations.When I am running python manage makemigrations it creates a migration file with the old field migrations also,and when I run python manage migrate I get "No migrations to apply",but when i check the db,fields are absent.I had this problem recently but --fake worked for it,Now when I am faking it also gives "No migrations to apply".I am working On production server so I don't think deleting migration files and resetting db is a good solution.Maybe someone can help me with that,Thank in advance! This is the migrations file which it created for me now,I only added cancellation_note and Iban fields now. class Migration(migrations.Migration): dependencies = [ ('auths', '0001_initial'), ] operations = [ migrations.RemoveField( model_name='customuser', name='bank_account_iban', ), migrations.RemoveField( model_name='customuser', name='bank_account_name', ), migrations.RemoveField( model_name='customuser', name='bank_account_name_on_card', ), migrations.RemoveField( model_name='customuser', name='social_media_account', ), migrations.AddField( model_name='customuser', name='cancellation_note', field=models.CharField(blank=True, max_length=255), ), migrations.AddField( model_name='customuser', name='iban', field=models.CharField(blank=True, max_length=255), ), migrations.CreateModel( name='payze_saved_cards', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('CardToken', models.CharField(max_length=255, null=True)), ('CardMask', models.CharField(max_length=255, null=True)), ('CardBrand', models.CharField(max_length=255, null=True)), ('CardCountry', models.CharField(max_length=255, null=True)), ('CardHolder', models.CharField(max_length=255, null=True)), ('ExpirationDate', models.CharField(max_length=255, null=True)), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), ] -
How to django orm get value anyone in query multi dictionary
Hi I want get model data with django orm. Mymodel, Security Field have multiple dictionary in list. if group_id = sg-1111222222 , i will get below data. So, I want to find a value that matches at least one of several dictionaries. [ { "GroupId": "sg-12345", "GroupName": "test1" }, { "GroupId": "sg-1111222222", "GroupName": "test2" } ]