Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How does token based authentication work?
I implement a web application (with Python+Django - to the extent that matters). Users can log in normally with username and password, but in addition I want to provide an API which users use to script the interaction with my site. For the API authentication my plan was to do something like this: In the database I create table with 'tokens' - i.e. random strings which point to the user database. The user gets a token string. For every API call the user passes the token string along with their request In the API implementation the code: Verify the token. Log the correct user in and execute the API function as the user matching the token. Log the user out again. Return the result Does this make sense? On the one hand it seems very simple - on the other hand it feels quite homemade, something I have heard is not recommended when it comes to security related topics? -
Django 'x' object has no attribute 'get_form'
I have a generic DetailView and I'm trying to do a form for the comment of an user after I display the details of the model but I keep getting the error 'ProductFeedbackView' object has no attribute 'get_form'. I don't know if the templates have any problem because the error is in the view when I try to get the form into a variable. Here is comment's model: class Comment(models.Model): service = models.ForeignKey(Product, on_delete=models.CASCADE, blank=True, null=True, related_name='comments') author = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True,) content = models.CharField(max_length=200, null=False, blank=True) ... def get_absolute_url(self): return reverse('product-feedback', kwargs={'pk': self.pk}) Comment's form: class CommentForm(forms.ModelForm): content = forms.CharField() class Meta: model = Comment fields = ['content'] View: class ProductFeedbackView(DetailView): model = Product template_name = 'services/product-feedback.html' form_class = CommentForm def get_success_url(self): return reverse('product-feedback', kwargs={'pk': self.object.id}) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['form'] = CommentForm(initial={'content': self.object}) return context def post(self, request, *args, **kwargs): self.object = self.get_object() form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) def form_valid(self, form): form.instance.author = self.request.user form.save() return super().form_valid(form) urls's: ... path('feedback/<int:pk>/', ProductFeedbackView.as_view(), name='product-feedback'), Template: <a href="{% url 'product-detail' product.id %}">Details</a> <a href="{% url 'product-feedback' product.id %}">Feedback</a> <p>{{ product.author }}</p> <h1>{{ product.title }}</h1> <p>{{ product.description }}</p> {% if user.is_authenticated %} <form method="POST"> … -
DRF filter/search return everything?
I'm currently doing self project inventory app and trying to implement filter and search. what I've done #views.py from django_filters.rest_framework import DjangoFilterBackend from rest_framework import filters class ListInventories(generics.ListAPIView): serializer_class = Inventory filter_backends = [filters.SearchFilter] search_fields = ['name'] filter_backends = [DjangoFilterBackend] filterset_fields = ['name', 'stock'] def get(self, request): inventories = Inventory.objects.all() serializer = InventorySerializers(inventories, many=True) return Response({'inventories': serializer.data}) class InventoryDetails(APIView): def get(self, request, pk): inventories = Inventory.objects.get(id=pk) serializer = InventorySerializers(inventories) return Response({'inventory': serializer.data}) in settings.py INSTALLED_APPS = [ ... 'django_filters', ... ] in url: http://127.0.0.1:8000/api/inventory?name=para I tried ?search=para and ?search=anynonsense . and the DRF would always return everything. just for the sake of clarification here is the screenshot(the total of item is just 3 for now, but even then filter/search should work): I expect the filter/search to function at least on a minimal level. What do I do to make this right? -
Django validation error from nested serializer
Inside a run_validation method I am calling another serializer's is_valid(raise_exception=True). If the input is not valid to the other serializer, then the program fails with the following error. super().__init__(*args, **kwargs) ValueError: need more than 0 values to unpack Here goes the code: def run_validation(self, data): modules = data.getlist("modules", []) if "modules" in data else [] if len(modules) > 0: sm_ser = SMSerializer(data=modules, many=True) sm_ser.is_valid(raise_exception=True) return super(CSSerializer, self).run_validation(data) Question 1. Is it ok to call validation for another object like this in this method? Question 2. How to make the run_validation raise the errors that are coming from the other serializer. sm_ser.errors is a list of errors which is not coming through. [ { "coordinates":{ "26":{ "1":[ "ErrorDetail(string=""Ensure that there are no more than 25 digits in total.", "code=""max_digits"")" ] }, "27":{ "1":[ "ErrorDetail(string=""Ensure that there are no more than 14 decimal places.", "code=""max_decimal_places"")" ] }, }, "c_coordinates":{ "50":{ "1":[ "ErrorDetail(string=""Ensure that there are no more than 14 decimal places.", "code=""max_decimal_places"")" ] } } }, ] -
How to exclude html from js export to xlsx with ExcellentExports.js?
Thanks in advance! In case it helps I am using Django3 and Python3 for the backend and javascript, html, and css for the front end. I am also using ExcellentExport.js to export html tables to excell. It works great with one caveat. It is exporting the entire html page instead of the two ids I specified. the html code snip of the tables to be exported: <div id="table1" class="position-absolute text-nowrap" style="max-width: 300px; max-height: 50px; right: 1600px; top: 145px;"> {% render_table tableP18 %} </div> <div id="table2" class="position-absolute" style="max-width: 100px; max-height: 10px; right: 1300px; top: 365px;"> {% render_table tableP17 %} </div> My js: function export() { return ExcellentExport.convert({ anchor:this, filename:'data_123.array',format: 'xlsx'}, [ {name: 'filename1', from: {table: 'table'}}, {name: 'filename2', from: {table: 'table2'}} ]); } What I'm trying to figure out is how to exclude certain html elements from the export in either the html or in js. Please let me know if you need any more information or code! -
Suitescript 2.x: Create a Customer Deposit upon Approval of Sales Order
Can you please check my code. I want to create a Customer Deposit upon approval of Sales Order. However, the Customer Deposit is both being created in Pending Approval and Pending Fulfillment. Can you please help fix my code. Thank you! /** *@NApiVersion 2.x *@NScriptType UserEventScript */ define(["N/record"], function (record) { try { function afterSubmit(scriptContext) { if (scriptContext.type == scriptContext.UserEventType.CREATE || scriptContext.type == scriptContext.UserEventType.EDIT) { var objSoRecord = scriptContext.newRecord; log.debug("Load the Sales Order", objSoRecord); var intsoId = objSoRecord.id; log.debug("Get the Sales Order Id: " , intsoId) var stCustomer = objSoRecord.getValue({ fieldId: 'entity' }); log.debug("Customer ", stCustomer) //Get Values var checkStatus = objSoRecord.getValue('status'); log.debug("SO status: " , checkStatus); if (checkStatus !== "Pending Approval"|| checkStatus == "Pending Fulfillment") { var objcustDeposit = record.create({ type: record.Type.CUSTOMER_DEPOSIT, isDynamic: true, defaultValues: { 'entity': stCustomer, 'salesorder': intsoId } }); //Insert Code here var saveCustDep = objcustDeposit.save(); } } } } catch (error) { log.debug("Capture Error:", error); } return { afterSubmit: afterSubmit } }); N/AN/AN/AN/AN/AN/AN/AN/AN/AN/A -
models in django. is many to many the best option?
I am trying to make my first website with django. Basically I'm making a website to check the bus schedule in my rural area. I think that the best thing is to make two models, one where all the bus stations are defined and the other where the route is established, for each route two stations are needed (origin and destination). I was wondering what was the best way to relate the two models. class BusStations(models.Model): bus_stations = models.CharField(max_length=80) bus_stations_identifier = models.IntegerField() def __str__(self): return self.bus_stations class Routes(models.Model): origin_station = models.ManyToManyField( BusStations, related_name='origin_station') destination_station = models.ManyToManyField( BusStations, related_name='destination_station') data = models.JSONField() slug = models.SlugField(unique=True, null=True) def __str__(self): return f'{self.origin_station} - {self.estacion_destino}' For now I was doing it with ManytoMany relationships, but this is giving me problems. For example, I am not able to return the origin and destination stations as str in the route model. I would also like it to be the slug. Thanks for advance. -
COMO PROTEGER URL DE FICHEROS ESTATICOS EN DJANGO
HOLAAAA BUENAS TARDES HE ESTADO TRABAJANDO EN UNA APP PARA REGISTRO DE DOCUMENTOS EN FORMATOS PDF, HASTA EL MOMENTO TODO MUY BIEN , PERO ME ENCUENTRO LA PROBLEMATICA DE QUE CUANDO GENERE MI TABLA DE CONSULTA Y CONFIGURO MI VISTA DE LOS ARCHIVOS DICHA VISTA NO ESTA PROTEGIDA, YA QUE CUANDO DESCONECTO EL SERVIDOR DE DJANGO Y COPIO LA URL ME DA ACCESO CON LOGUEO Y SIN LOGUEO COMO PUEDO PROTEGER ESA RUTA.. ALGUNA AYUDA POR FAVOR EL PROYECTO FUE HECHO EN DJANGO -
Multiple django databases and queries
good work. I have a database connection structure as follows. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'DATA', 'USER': 'postgres', 'PASSWORD': 'root', 'HOST': '127.0.0.1', 'PORT': '5432', }, "big_data": { "ENGINE": "mssql", "NAME": "DATABASE_NAME", "USER": "USER_NAME", "PASSWORD": "PASSWORD", "HOST": "HOST_ADDRESS", "PORT": "1433", "OPTIONS": { "driver": "ODBC Driver 17 for SQL Server", }, }, } I need to fetch and display data via mssql. And this, `from django.db import connections with connections['big_data'].cursor() as cursor: cursor.execute("SELECT * FROM [aab].[CENTER]")` but the page load is delayed. To get this with django orm python manage.py inspectdb --database=big_data > models.py i run it gives a blank output. It says on the internet that it doesn't receive it because of the database schema. How can I get around this how can I get it on django orm just to write a query. Page load speed is very good in queries performed with Django orm. Also, when I create the model file manually, it adds the application name to the beginning of the table and I can't ask what I did. This is a problem for me. The database I connect belongs to a different system, so I can't interfere too much because I only have the … -
Django create or update model only if field not equal to certain value
We have a potential race condition where multiple users can try to create or update a record. Wondering if there's a way to create a column, than when set (to say true), then an exception will be thrown, preventing the update. The underlying database is postgres, but since we're using django to wrap it, we would like to limit ourselves to something django offers, and not mess with very specific database settings. Thanks! -
Django filer - PolymorphicTypeInvalid ContentType 37 does not point to a subclass
I am using django-filer to handle uploading images in my Django app. I am currently trying to load data from MySQL to PostgreSQL database. I have used the following commands to get data from MySQL and move it t PostgreSQL: python manage.py dumpdata myapp> myapp.json set DJANGO_SETTINGS_MODULE=myproject.settings.production python manage.py loaddata "myapp.json" All content works fine and I can see in pgAdmin4 that it's been successfully exported however when I am trying to open a website that contains images I get Internal Server Error like this: PolymorphicTypeInvalid at /myapp/homepage ContentType 37 for <class 'django_comments_xtd.models.BlackListedDomain'> #205 does not point to a subclass! Or error like this: PolymorphicTypeInvalid at /admin/myapp/articles/30/change/ ContentType 37 for <class 'django_comments_xtd.models.BlackListedDomain'> #232 does not point to a subclass! How can I get rid of this error and how can I move all image paths from MySQL to PostgreSQL? -
Creating a model instance
I have two Models, (Doctor & Patient), the Doctor Model is the parent Model, How can I make (Service_doctor) field be an instance of the Doctor's Model so that I can get the Doctor's name into the Patient's Model using for loop in the HTML Template. This is what am trying to mean; Models.py class Doctor(models.Model): Doctor_Name = models.CharField(max_length=200) def __str__(self): return self.Doctor_Name class Patient(models.Model): Name = models.CharField(max_length=200) Telephone = models.CharField(max_length=100, unique=True) Service_doctor = models.ForeignKey(Doctor, on_delete=CASCADE) def __str__(self): return self.Doctor_Name Views.py def Newpatient(request): if request.method == 'POST': Name = request.POST.get('Name') Telephone = request.POST.get('Telephone') Service_doctor = request.POST.get('Service_doctor') formdata = Patient(Name=Name, Telephone=Telephone, Service_doctor=Service_doctor) formdata.save() return render(request, 'Adm.html') ``` Any help please? -
Django signal user_login_failed not working for Custom User model , Custom Backend
I am a beginner in Django and due to my project requirements, I came to conclusion that I have to implement Custom User model, and also due to this I also implemented Custom Backend. But, now I am unable to use user_login_failed Django Signal, as I am thinking to use it for restrict the user login attempt to 3. and also, I have both encrypted and non-encrypted password and I want to authenticate both for now, but in future only encrypted password will remain in my DB ex: - "pbkdf2_sha256$390----------------------------" Any help will be a great deal to me Thanks settings.py AUTH_USER_MODEL = 'accounts.Usermanagement' AUTHENTICATION_BACKENDS = [ 'accounts.backends.EmailAuthBackend', 'django.contrib.auth.backends.ModelBackend', ] modely.py class Usermanagement(AbstractBaseUser): emailid = models.CharField(db_column='EmailID', unique=True, max_length=45,default=1) ------------ --------- ----------- objects = UsermanagementCustomUserManager() USERNAME_FIELD = "emailid" EMAIL_FIELD = "emailid" managers.py class UsermanagementCustomUserManager(BaseUserManager): def create_user(self,emailid,firstname, password=None): """ Creates and saves a User with the given email, date of birth and password. """ if not emailid: raise ValueError('Users must have an email address') user = self.model( emailid=self.normalize_email(emailid), password=password, ) user.set_password(password) user.save(using=self._db) return user backends.py from django.contrib.auth.backends import BaseBackend from django.contrib.auth.hashers import make_password,check_password from django.contrib.auth import get_user_model Usermanagement = get_user_model() class EmailAuthBackend(BaseBackend): def authenticate(self,request,username=None,password=None): # print("Custom authenticate rqst: ",request) try: print("Trying the … -
Image upload leads to Server Error (500) Django app deployed on railway.app
I have deployed a django app on railway.app. In development I can upload images but when I go to deployed app and click on upload it leads me to Server Error (500). following is my settings.py code STATIC_URL = 'static/' # STATIC_ROOT = BASE_DIR / 'staticfiles' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') if 'XXX' in os.environ: # Bucket config AWS_STORAGE_BUCKET_NAME = 'xxx' AWS_S3_REGION_NAME = 'xxx' AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com' # Static and media files STATICFILES_STORAGE = 'custom_storages.StaticStorage' STATICFILES_LOCATION = 'static' DEFAULT_FILE_STORAGE = 'custom_storages.MediaStorage' MEDIAFILES_LOCATION = 'media' # Override static and media URLs in production STATIC_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{STATICFILES_LOCATION}/' MEDIA_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{MEDIAFILES_LOCATION}/' html code <div> <img src="{{user_profile.profile_img.url}}" alt="Profile Image"> </div> <a href="{% url 'profile-image' user_profile.user user_profile.profile_uuid %}"</a> -
TypeError: the 'package' argument is required to perform a relative import for './myapp/manage.py.test_settings'
Trying to run script inside AWS Linux: ./runtests.sh ./myapp/manage.py and get the below error. Does anyone know what this means and what I should do? manage.py and test_settings.py are both in the main directory ./deploy-scripts/runtests.sh ./myapp/manage.py Traceback (most recent call last): File "manage.py", line 18, in <module> execute_from_command_line(sys.argv) File "/usr/local/python37/lib/python3.7/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/usr/local/python37/lib/python3.7/site-packages/django/core/management/__init__.py", line 363, in execute settings.INSTALLED_APPS File "/usr/local/python37/lib/python3.7/site-packages/django/conf/__init__.py", line 82, in __getattr__ self._setup(name) File "/usr/local/python37/lib/python3.7/site-packages/django/conf/__init__.py", line 69, in _setup self._wrapped = Settings(settings_module) File "/usr/local/python37/lib/python3.7/site-packages/django/conf/__init__.py", line 170, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/local/python37/lib/python3.7/importlib/__init__.py", line 122, in import_module raise TypeError(msg.format(name)) TypeError: the 'package' argument is required to perform a relative import for './myapp/manage.py.test_settings' ./deploy-scripts/runtests.sh: line 57: flake8: command not found ------------------------ There were failed tests! Scroll up for details -
Transform python requests's exceptions to django-rest-framework's API exceptions
I'm developing a REST API using django-rest-framework that needs to interact with a 3rd party API. I use requests for comunication with this 3rd party API. Some recurrent pattern I get in my code is making a request from an APIView handler def calculate_order(order): url = f"https://api.anotherservice.com/orders/calculate/" try: response = requests.post(url, json=order.data) response.raise_for_status() # TODO: handle errors, just printing and re-raising for now except requests.exceptions.HTTPError as errh: raise errh except requests.exceptions.ConnectionError as errc: print(errc) raise errc except requests.exceptions.Timeout as errt: print(errt) raise errt except requests.exceptions.RequestException as err: print(err) raise err return response.json() # ... In my view def post(self, request, *args, **kwargs): # ... Some preprocessing code here order_calculated = calculate_order(order) return Response(order_calculated, status=HTTP_200_OK) DRF implements a mechanism that hanldes Subclasses of APIException raised inside REST framework. Django's Http404 exception. Django's PermissionDenied exception. I was wondering if there's a package for transforming requests's exceptions to exceptions objects that DRF can handle. Also I'll be glad to know any recomendation on how this should be implemented (best practices). I was googling it but terms with "Django" and "requests" drop results mostly of Django itself. -
Using an API to generate virtual numbers
I will build a website of virtual numbers, where the user can buy a number for a certain period of time and, after registering on a platform that requires a number to send a code, my website will receive the code through a webhook and return to the user. The central question is: which service fits my need? I thank. -
How to refresh token after expiry in django knox authentication?
I am running django application with django knox token authentication. I was able to do login with the package. But after the token expired, url response are throwing " Invalid Token". I don't understand how to refresh the token after expiry? whether i need to login again? if it is, the user will get irritated. How to do it in proper way? Which is the best token authentication for django rest framework? -
Django: Match two models by same field they have
I have 2 models. User model class User(TimeStampedModel): phone_number = models.CharField( _('Phone number'), null=True, blank=True, max_length=30, ) reservations = models.ManyToManyField( 'Reservation', related_name='Users', verbose_name=_('Reservations'), ) and Reservation model: class Reservation(TimeStampedModel): phone_number = models.CharField( _('Phone number'), null=True, blank=True, max_length=30, ) As you see there is ManyToManyField relationship between them. Here I need to get one user that phone_number is same with Reservation model's phone_number How can I get that one user -
Network: My web app goes down and I get "Connection Refused"
I have a serious network problem that is making me go crazy. My web application uses a Nginx web server, all deployed with Docker. We have two network cards with two different IP addresses. because 1 is for 100% uptime and providing external services like a static public IP address. And the other is for internal uses, like an SSH connection. And, therefore, I have a DNS service with two public IPs of type A to serve the website if one is unavailable. I have my nginx webserver configured to serve the two adresses, maybe I should change that. ` upstream app { server 192.168.1.84:5001; server 172.16.31.10:5001; } server { listen 443 ssl; ssl_certificate /etc/ssl/ssl.pem; ssl_certificate_key /etc/ssl/ssl-key.key; server_name example.com; root /var/www/example.com; resolver 127.0.0.11 ipv6=off; index index.html index.htm index.nginx-debian.html; charset utf-8; #max upload size client_max_body_size 75M; location /media { alias /app/media; } location /staticfiles { alias /app/assets; } location / { proxy_set_header Host $host; proxy_redirect off; proxy_pass http://app; # Add your own server port here instead of 5000. proxy_set_header X-Forwarded-Host $server_name; proxy_set_header X-Real-IP $remote_addr; include /etc/nginx/uwsgi_params; } } ` It worked at 100% uptime before; maybe this is related to having two networks now. I have a monitoring service that pings … -
Django testing UpdateView - object has no attribute 'object'
I am trying to write a test for an UpdateView I created. My view looks like this: class MutantUpdateView(UpdateView): context_object_name = "mutant" fields = ["mutation_level"] model = Mutant pk_url_kwarg = "mutant_id" template_name_suffix = "_update_form" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["admin"] = get_object_or_404( Person, id=self.kwargs["admin_id"] ) context["backstory"] = get_object_or_404( Backstory, id=self.kwargs["backstory_id"] ) context["evidences"] = self.object.evidences.all() return context def get_form(self, form_class=None): form = super().get_form(form_class) mutant = self.object mutation_levels = ( mutant.expectation.mutation_levels.all() ) form.fields["mutation_level"].queryset = mutation_levels return form def form_valid(self, form): form.instance.updated_by = = get_object_or_404( Person, id=self.request.user.person_id ) return super().form_valid(form) def get_success_url(self, **kwargs): return reverse_lazy( "mutants:mutant-update", kwargs={ "admin_id": self.kwargs["admin_id"], "backstory_id": self.kwargs["backstory_id"], "mutant_id": self.kwargs["mutant_id"], }, ) My test looks like this (per the documentation) def test_form_valid_posts_appropriately(self): new_level = MutantLevelFactory(short_description="Next Mutant Level") self.mutant.expectation.mutation_levels.add(new_level) data = { "created_by": self.admin_person.id, "updated_by": self.admin_person.id, "backstory": self.mutant.backstory.id, "expectation_level": new_level, "expectation": self.mutant.expectation.id, } kwargs = { "admin_id": self.admin_person.id, "backstory_id": self.mutant.backstory.id, "mutant_id": self.mutant.id, } request = self.factory.get( reverse("mutants:mutant-update", kwargs=kwargs) ) request.user = self.admin_user # simulate admin user logged in self.view.setup(request) context = self.view.get_context_data() self.assertIn('backstory', context) self.assertFalse(context["form"].errors) self.assertEqual(response.status_code, 302) It's giving me this error: def get_form(self, form_class=None): form = super().get_form(form_class) > mutant = self.object E AttributeError: 'MutantUpdateView' object has no attribute 'object' The model looks like this: class Mutant(models.Model): id = models.BigAutoField(primary_key=True) … -
Pass HTML as agrumnet within inclusion tag
I have created an inclusion tag for creating a certain number of columns within a row: <tr> {% for col in cols %}<td>{{ col }}</td>{% endfor %} </tr> My inclusion_tag function is: @register.inclusion_tag("row_with_cols.html") def row_with_cols(*cols): return {"cols": cols} So I can now pass as many values I want to my rows as I want with something like: {% row_with_cols "Full name" session.userinfo.name %} This is all well and good however to take this to the next level I would like to pass in arguments that are HTML arguments. For example, I want to turn something like this: <tr> <td>Image</td> <td> <img src="{{ session.userinfo.picture }}"> </td> </tr> into {% row_with_cols "Image" <img src="{{ session.userinfo.picture }}"> %} However, this gives me Could not parse the remainder: '<img' from '<img' I know I could modify the inclusion_tag function with some additional arguments that could provide the info but was hoping to keep that nice and generic. It would be helpful if someone can either tell me whether what I'm doing is not possible or if there is a clean/non-hacky way to do it. Thanks -
Display inline values in other app's admin model
I have been trying to figure it out but since I am not much experienced in this, I wanted to ask if there is a way to display the values from an inline at an other app's model.admin; In my case: accounts\admin.py: @admin.register(models.Customer) class CustomerAdmin(ImportExportModelAdmin, admin.ModelAdmin): list_display = ('first_name', 'last_name', 'customer_subscription', 'company') This is where I want to show inline values. core\admin.py: class ManageAddressInline(GenericStackedInline): model = AssignAddress class CustomCustomerAdmin(CustomerAdmin): inlines = [ManageAddressInline] admin.site.unregister(Customer) admin.site.register(Customer, CustomCustomerAdmin) address_reports\model.py: from django.db import models from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.fields import GenericForeignKey from django_countries.fields import Country, CountryField from accounts.models import Customer class AssignAddressManager(models.Manager): def get_tags_for(self, obj_type, obj_id): content_type = ContentType.objects.get_for_model(obj_type) return AssignAddress.objects \ .select_related('manage-address') \ .filter( content_type=content_type, object_id=obj_id ) class ManageAddress(models.Model): defined = models.ForeignKey(Customer, on_delete=models.CASCADE) apartment_or_suite = models.CharField(max_length=255) street = models.CharField(max_length=255) city = models.CharField(max_length=255, null=True) postal_code = models.CharField(max_length=20, blank=True) country = CountryField() class AssignAddress(models.Model): objects = AssignAddressManager() apartment_or_suite = models.CharField(max_length=255, null=True) street = models.CharField(max_length=255, null=True) city = models.CharField(max_length=255, null=True) postal_code = models.CharField(max_length=255, null=True) country = CountryField() content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey() address_reports\admin.py: from django.contrib import admin from address_reports.models import ManageAddress @admin.register(ManageAddress) class ManageAddressAdmin(admin.ModelAdmin): search_fields = ['defined', 'apartment_or_suite', 'street', 'city', 'postal_code', 'country'] list_display = ['defined', 'apartment_or_suite', 'street', 'city', 'postal_code', 'country'] … -
Django, spawn worker process on start generates django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet
Background: I have an app that scrapes through our IT infrastructure resources (vCenter, storage, and backup entities) to pull things into a central inventory for quick reference. Each collection spins up in its own thread, and I've taken measures to implement a producer/consumer setup to better scale for our resources. What I've noticed is that when I have collections running from multiple types (Ex: vCenter and storage), the web interface chugs. My thought is because I've got a ton of threads running from multiple sources and the GIL is causing everything to get queued up under one main thread. So, I thought that I could have the main producer/consumer model run as processes instead of threads since they are fairly independent of each other. What's wrong: When I made the code switch from spinning up threads to processes, the worker process tries to load up the models that it should, but it fails because the sub process is separate, and the applications aren't loaded up. It throws django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. What I have found is since this spawned process doesn't inherit anything from the Django main process, it's trying to access the models without having anything started. What … -
How to fetch the Finance Charge Preferences values using SuiteScript in NetSuite?
We need to perform calculations in SuiteScript using the values in Setup/Accounting/Finance Charge Preferences. Which record is this stored on? Specifically, we're looking for these finance charge fields: Annual Rate Minimum Finance Charge Grace Period We've tried to create saved searches in all of the obvious records but have not been able to find these fields.