Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Detecting if a site is refreshed on a mobile phone
I developed this js code, that should detect when a site is loaded for the first time or is refreshed. I send this information tho a django view. The problem is that it works on PC but not on mobile devices like phones, tablets, etc... Here is the javascript code: window.addEventListener('load', function() { // Check if the page has been reloaded var isReloaded = sessionStorage.getItem('isReloaded'); if (!isReloaded) { // It's the first visit or a new session sessionStorage.setItem('isReloaded', 'true'); // Perform actions for the first visit here } // Send the reload information to the server var isRefreshed = isReloaded ? 'true' : 'false'; var csrfToken = '{{ csrf_token }}'; $.ajax({ type: "POST", url: '', data: { 'is_refreshed': isRefreshed, 'csrfmiddlewaretoken': '{{ csrf_token }}' // Include CSRF token for security }, dataType: 'json', success: function(data) { // Handle the response from the server here, if needed console.log(data.message); }, error: function(xhr, status, error) { // Handle errors here, if needed console.error(error); } });// Replace with your CSRF token // Make an AJAX request here to send 'isRefreshed' and 'csrfToken' to the server. }); -
Django TypeError: issubclass() arg 1 must be a class when trying to create a simple tag
When trying to create a simple tag in django to reassign a variable in a django template, I am getting the error TypeError: issubclass() arg 1 must be a class. custom_templates.py: from django import template register = template.Library() @register.simple_tag def define(val=None): return val part of my settings.py: ... INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "crispy_forms", "crispy_bootstrap4", "main.apps.MainConfig", "register.apps.RegisterConfig", "main.customtemplates.custom_templates.define" ] ... I believe this is everything interacting with my simple tag, if any other information is required, please let me know. Any help is appreciated! I've tried giving the val argument in my define function a preset value, I've tried removing this, and I've tried giving type suggestions, e.g., def define(val:bool): -
Messing up the event handler in django, help me figure it out
My models: class Product(models.Model): name = models.CharField(max_length=255) owner = models.ForeignKey(User, on_delete=models.PROTECT, related_name='owner') allowed_users = models.ManyToManyField(User) def __str__(self): return self.name class Lesson(models.Model): name = models.CharField(max_length=255) link = models.URLField() time = models.PositiveIntegerField() products = models.ManyToManyField(Product) def __str__(self): return self.name class UserLessons(models.Model): user = models.ForeignKey(User, on_delete=models.PROTECT) lesson = models.ForeignKey(Lesson, on_delete=models.PROTECT) is_view = models.BooleanField(default=False) view_time = models.PositiveIntegerField(default=0) date_view = models.DateField(null=True) def __str__(self): return f'{self.user.username} - {self.lesson.name} I am implementing an event handler that should create a record in the DB when creating a Lesson record @receiver(post_save, sender=Lesson) def create_user_lessons(sender, instance, **kwargs): products = instance.products.all() allowed_users = [] for product in products: for user in product.allowed_users.all(): if user not in allowed_users: allowed_users.append(user) for user in allowed_users: UserLessons.objects.create(user=user, lesson=instance) But I came across the fact that instance.products.all() outputs an empty QuerySet, although it is not empty when creating a record. What is the reason for this behavior and how to solve it? I tried to redefine the save() method, but it didn't help in any way, but an important clarification appeared, instance.products.all() gives an empty qs only for the record that was created at the moment, the rest of the records work fully, when choosing another, everything is saved as needed -
dajngo pagination for products, problem with pagination when query
I'm working on a Django project for building a website, and I'm facing an issue when filtering through a search bar by name; the pagination is not working correctly. When filtering def mart(request): query = request.GET.get('q') temperature = request.GET.get('temperature') if temperature is None: temperature = 150 products = Product.objects.all() if query: products = products.filter(Q(name__icontains=query)) for product in products: latest_log = Log.objects.filter(product_uuid=product).order_by('-date').first() if latest_log: temp = latest_log.course_temp product.temperature = temp else: product.temperature = 0 products = sorted(products, key=lambda x:x.temperature, reverse=True) paginator = Paginator(products, 20) page_number = request.GET.get('page') page_products = paginator.get_page(page_number) product_info_list = [] for product in page_products: latest_log = Log.objects.filter(product_uuid=product,course_temp__lte=temperature).order_by('-date').first() all_productbadges = Productbadge.objects.filter(product_uuid=product) badges_urls = [] if all_productbadges: for productbadge in all_productbadges: badge_id = productbadge.badge_id badge_instance = Badge.objects.filter(label=badge_id).first() if badge_instance: badge_url = badge_instance.url badges_urls.append(badge_url) if latest_log: product_info = { 'product': product, 'latest_log': latest_log, 'badges_urls': badges_urls } product_info_list.append(product_info) print("@@@@@@@@@") print(page_products.next_page_number) context = {'product_info_list': product_info_list, 'page_products': page_products} return render(request, 'courses/mart.html', context=context) paginator = Paginator(products, 20) page_number = request.GET.get('page') page_products = paginator.get_page(page_number) product_info_list = [] for product in page_products: latest_log = Log.objects.filter(product_uuid=product,course_temp__lte=temperature).order_by('-date').first() all_productbadges = Productbadge.objects.filter(product_uuid=product) badges_urls = [] if all_productbadges: for productbadge in all_productbadges: badge_id = productbadge.badge_id badge_instance = Badge.objects.filter(label=badge_id).first() if badge_instance: badge_url = badge_instance.url badges_urls.append(badge_url) if latest_log: product_info = { 'product': product, 'latest_log': … -
Django app on Google App Engine not connecting to Google Cloud SQL
I've encountered an issue when deploying my Django application on Google App Engine and trying to connect it to Google Cloud SQL. The application works perfectly on my local system, but when deployed, I get the following connection error: could not connect to server: Connection refused Is the server running on host "127.0.0.1" and accepting TCP/IP connections on port 5432? This is the code snippet for my settings.py file: DATABASES = {"default": env.db()} # If the flag as been set, configure to use proxy if os.getenv("USE_CLOUD_SQL_AUTH_PROXY", None): DATABASES["default"]["HOST"] = "127.0.0.1" DATABASES["default"]["PORT"] = 5432 # [END gaestd_py_django_database_config] # [END db_setup] # Use a in-memory sqlite3 database when testing in CI systems # TODO(glasnt) CHECK IF THIS IS REQUIRED because we're setting a val above if os.getenv("TRAMPOLINE_CI", None): DATABASES = { "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": os.path.join(BASE_DIR, "db.sqlite3"), } } I have followed this guide for setting up my application on google app engine. These are all the troubleshooting steps I have tried so far - Enabled the Cloud SQL Admin API. Added Cloud SQL Admin role to the App Engine service account. Tested Connectivity from App Engine to SQL instance. Tried Restarting the Cloud SQL instance and App Engine Instance. Checked … -
External database in django Admin Panel
Is it possible to manipulate External database through django admin panel without migration? I have such database: 'cook_db': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'cook_db', 'USER': 'postgres', 'PASSWORD': '123456', 'HOST': '127.0.0.1', 'PORT': '5432' } All tables I added into model.py: ... class Recipes(models.Model): id_subcategory = models.ForeignKey( Categories, models.DO_NOTHING, db_column='id_subcategory') id_recipe = models.AutoField(primary_key=True) name = models.TextField() img_url = models.TextField() grade = models.IntegerField(blank=True, null=True) time = models.IntegerField(blank=True, null=True) class Meta: managed = False db_table = 'recipes' ... But When I tried to register that model (admin.site.register(Recipes)), I catch that error: OperationalError at /admin/MainSite/recipes/. no such table: recipes -
DJANGO HTML Elements and Javascript
I'm trying to implement a "hover image" effect on a website drive by Django. Each model in my database contains 2 distinct images. I'd like to have the image change when the user hovers over the "default image" and have it change to the "hover image". What's happening instead is only the first image is changing to the hover image. If the user hovers over any other image on the page, the first image at the top of the page is the one that changes. Here's my HTML {% for element in records %} <div class = "model"> <img src="{{element.default_image}}" onmouseover="hoverImage();" onmouseout="defaultImage();" width="120"></div> Here's my JS const imgElements = document.querySelectorAll('.model'); for (let i = 0; i < imgElements.length; i++) { const currentElement = imgElements[i]; function hoverImage() { currentElement.src = '{{element.hover_image}}'; } function defaultImage() { currentElement.src = '{{element.default_image}}'; } } This only changes the first element in the model no matter what image the user hovers over -
Why don't frameworks like Django, Express and others often use class diagrams with UML?
Which software engineering and systems design tool to use in framworks like Django? I see that languages like Java, C# and C++ use UML class diagrams. But I don't see it in Python and Javascript. How then to architect these systems? I've been searching for a approach to deal with django project with UML tools, but without success. Keep in mind that I'm a beginner in Django. -
Response times long for multiple users in Cloud Run for a Django application
I have a Django Rest Framework application which is hosted in Cloud Run. The normal response times for requests are around 100-200ms but no matter what I try I cannot get the same response times for multiple users. I have conducted load testing with Jmeter: for 200 users the best I can get is 1500ms average response time and for 500 around 4000ms (these are for "hot" instances). I have tried setting different values for gunicorn workers and thread (such as setting the max concurrency the same as # of cores * # of threads and setting the workers count the same as the number of CPUs and 2 * # of CPUs + 1) as well as trying with different CPU, memory and max instances and concurrent requests settings. I also checked that the Cloud SQL has sufficient CPU. What could be the bottleneck here? -
Email service with python + django deployment
I have a personal project, it's email service on django I already made it, but i have one question How can i connect this service to the web of other emails? Like i can send email from my service to gmail, and from gmail to my service There are nothing about it in the internet. The only one i saw, that i need to configure email server (?) Can you give me a roadmap of how can i do this? BIG NOTICE: IF YOU HAVE A BAD DAY OR SOMETHING ELSE, DO NOT ANSWER THIS QUESTION, OR DO NOT GIVE ANSWERS LIKE "YES YOU NEED TO CONFIGURE A EMAIL SERVER" THANKS IN ADVANCE -
Django HttpResponseNotFound Not Displaying Correctly in View
I am working on a Django project where I have a view called 'chapterPage' that is supposed to display a specific chapter. If the chapter with the given primary key (pk) doesn't exist, I want to return an HttpResponseNotFound response. However, I am encountering an issue where the "Chapter not found" is not being displayed when the chapter is not found. Code snippets: views.py: from django.http import HttpResponseNotFound from .models import Chapter def chapterPage(request, pk): try: chapter = Chapter.objects.get(id=pk) except Chapter.DoesNotExist: return HttpResponseNotFound("Chapter not found") urls.py: urlpatterns = [ path("chapter/<str:pk>/", views.chapterPage, name="chapter"), ] The chapter link on the other webpage: <div> <a href="{% url 'chapter' chapter.pk %}">{{chapter.number}}</a> </div> I made sure that the chapter exists in the database with the intended pk. Also, when I'm trying to search for a chapter using the URL 'http://127.0.0.1:8000/chapter/5933/' the terminal returns 'Not Found: /chapter/5933/m' or 'Not Found: /chapter/5933/n', basically an intended URL with a random character afterward. I am expecting to get HttpResponseNotFound("Chapter not found") if the chapter is not found. P.S. I have just started learning so any help is apreciated! -
Transfer the Django project to another computer and create a local network
I have created a Django project on my laptop with Pycharm and now I want to transfer it to a computer on the local network and use it as a network. All steps including: 1- Installing Python with the same version on the laptop 2- Creating a virtual environment with the same name as the virtual environment of the project 3- Copy the whole project in the new project 4- Of course, copy the packages of the virtual environment (do I have to install them?) 1- ALLOWED_HOSTS=['*'] 2-py manage.py runserver 0.0.0.0:8000 I have done it correctly. But the speed of running the project in the browser is very low. please guide me. Thanks for your help dear friends -
My PostUpdateView does not send any data to form update template
error I have exactly the same structure for updating forum's posts, so they do work, but the article's ones don't. My article_update_form template simple does not receive any data from the view and therefore the slug is empty. My UpdateView class ArticlePostUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = ArticlePost template_name = 'articles/article_form_update.html' form_class = ArticlePostForm def form_valid(self, form): form.instance.author = self.request.user messages.success(self.request, 'The article has been updated') return super().form_valid(form) def test_func(self): post = self.get_object() if self.request.user.id == post.article_users.user.id: return True return False urls: urlpatterns = [ path("posts/<slug>/", articles, name="articles"), path('<int:page_id>', pages.views.articles, name='page'), path("detail/<slug>/", detail, name="article_details"), path("new_article", new_article, name="new_article"), path("new_article/create_post", login_required(ArticlePostCreateView.as_view()), name="create_article"), path("post/<slug:slug>/update/", ArticlePostUpdateView.as_view(), name="update_post_article"), path('categories_list', categories_list, name="categories_list"), path("search_article_post", search_article_post, name="search_article_post"), path("category/<slug>/", category_articles, name="category_articles"), path("sort_by/<str:typesort>", articles_sort, name="articles_sort"), ] forms: class ArticlePostForm(forms.ModelForm): class Meta: model = ArticlePost fields = ("title", "categories", "content", "article_tags", 'article_image') exclude = ["article_users"] widget = { 'title': forms.TextInput(attrs={'class': 'form-control'}), 'content': forms.TextInput(attrs={'class': 'form-control'}), 'categories': forms.Select(attrs={'class': 'form-control'}), 'article_tags': forms.Select(attrs={'class': 'form-control'}), 'article_image': forms.Select(attrs={'class': 'form-control'}), } def __setitem__(self, i, elem): self.list[i] = elem form template: <div class="form-group"> <form method="POST" action="{% url 'update_post_article' slug=post.slug %}"> {% csrf_token %} <div class="centered_create_post"> {% render_field form.title placeholder="Enter title" class+="form-control each_post_create" %} {% render_field form.content placeholder="Enter content" class+="form-control each_post_create pst_create_categories " %} {% render_field form.categories class+="form-control each_post_create pst_create_categories " … -
trying to set cookie in jsonresponse django
Hello I am trying to set a JWT token in a cookie in a jsonresponse when people login. this is my current code. response = JsonResponse({'status': 'success', 'user': user}) response.set_cookie( key='access_token', value=tokens["access"], max_age=900, domain='localhost', path='/', # secure=False, # httponly=True, # samesite='Lax' ) return response In my browser the cookie is never set. in my netwerk tab when i look at the login request i do see the cookie. Here are the headers of my request. And here you can find the cookies that are set in the browser. all help is greatly apprectiated. -
flutterwave standard integration Key error, Please, what could be wrong with my code?
Here is the view to my flutter_api view. def flutter_api(request,username,email,phone_no,price): auth_token= get_env_variable('SECRET_KEY')#env('SECRET_KEY') hed = {'Authorization': f"Bearer {auth_token}"} data = { "tx_ref":''+str(math.floor(1000000 + random.random()*9000000)), "amount":price, "currency":"NGN", "redirect_url":"http://localhost:8000/payments/verify_payment", "payment_options":"card, ussd, mobilemoneynigeria", "meta":{ "consumer_id":23, "consumer_mac":"92a3-912ba-1192a" }, "customer":{ "email":email, "phonenumber":phone_no, "name":username }, "customizations":{ "title":"ADi meals limited", "description":"Your Number one Food and Soup service", "logo":"https://getbootstrap.com/docs/4.0/assets/brand/bootstrap-solid.svg" } } url = 'https://api.flutterwave.com/v3/payments' response = requests.post(url, json=data, headers=hed) response_data=response.json() link=response_data['data'], response_data['link'] return link it throws this error after running server Internal Server Error: /payments/flutter_api/sharperleinado/dannyhance7420@gmail.com/0815 667 7751/650.0 Traceback (most recent call last): File "C:\Users\USER\Documents\ADi meals mobile\my_site\venv\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\USER\Documents\ADi meals mobile\my_site\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\USER\Documents\ADi meals mobile\my_site\payments\views.py", line 95, in flutter_api link=response_data['data'], response_data['link'] KeyError: 'link' [23/Sep/2023 16:16:35] "GET /payments/flutter_api/sharperleinado/dannyhance7420@gmail.com/0815%20667%207751/650.0 HTTP/1.1" 500 69757 -
Python, Django: django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'accounts.Usuarios' that has not been installed
Good morning! Although questions similar to this have been posted here, I have not been able to resolve my issue yet. I have tried all proposed solutions. The problem started after I put, or at least tried to put, "email" as the username, removing the username from the model. I will share the points that I think are relevant. If you need more, you can ask. problem: PS C:\SocialFacil\socialfacil_web> python manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\SocialFacil\lib\site-packages\django\apps\config.py", line 235, in get_model return self.models[model_name.lower()] KeyError: 'usuarios' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\SocialFacil\lib\site-packages\django\contrib\auth\__init__.py", line 170, in get_user_model return django_apps.get_model(settings.AUTH_USER_MODEL, require_ready=False) File "C:\SocialFacil\lib\site-packages\django\apps\registry.py", line 213, in get_model return app_config.get_model(model_name, require_ready=require_ready) File "C:\SocialFacil\lib\site-packages\django\apps\config.py", line 237, in get_model raise LookupError( LookupError: App 'accounts' doesn't have a 'Usuarios' model. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\Victor\AppData\Local\Programs\Python\Python310\lib\threading.py", line 1009, in _bootstrap_inner self.run() File "C:\Users\Victor\AppData\Local\Programs\Python\Python310\lib\threading.py", line 946, in run self._target(*self._args, **self._kwargs) File "C:\SocialFacil\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\SocialFacil\lib\site-packages\django\core\management\commands\runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "C:\SocialFacil\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\SocialFacil\lib\site-packages\django\core\management\__init__.py", line … -
Please how to solve NoReverseMatch
Reverse for 'student_detail' with keyword arguments '{'student_id': 'STUD/1/230922'}' not found. 1 pattern(s) tried: ['students/STUD/(?P<student_id>[0-9]+)/(?P<current_date>[0-9]+)/\Z'] this is how I set my urls.py path('STUD/int:student_id/int:current_date/', views.StudentDetailView.as_view(), name='student_detail'), -
Is it possible to save a class using django redis cache to use it after the user reconnects
I need to save a class to use it if the websocket disconnects and assign it to the websocket again if it reconnects. But when saving i get this error: "Exception inside application: Can't pickle local object" which i think is because i cant save a class to the cache. Is it possible to overcome this and save the class in the cache? -
How can I give input with getpass to a Django app when deploying using Nginx, Gunicorn and systemd?
I have a Django app that has key on disk which is encrypted using AES Cypher, and must be unencrypted in memory for use during the processes. I have this line in settings.py: AES_CIPHER_KEY = getpass("Enter AES cipher key: (leave blank if you don't need decryption)") This is my gunicorn.socket: [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target This is my gunicorn.service: [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=root Group=www-data WorkingDirectory=/root/samir/src/samirpy ExecStart=/root/samir/venv/bin/gunicorn --access-logfile --workers 3 --bind unix:/var/log/gunicorn/samir.sock samir.wsgi:application [Install] WantedBy=multi-user.target This is my nginx.conf: server { listen 80; server_name example.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /var/www; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } This is wsgi.py: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'samir.settings') application = get_wsgi_application() What I would like to happen is when I update the code and restart the service using: sudo systemctl restart gunicorn it prompts for the key before starting the main process. -
Daphne websocket stop responding after somtime
Project Specs: Django 3.2.4 , Channels 3.0.5 , Channel-redis 3.4.1 , Daphne 3.0.2. I setup a chat system, which communicate using websocket. On page load, everything works fine, but after few seconds only (~20-30 sec), data sending and receiving halt. On refresh page, it again start working. I am not sure, this issue araise from Consumers file or Daphne from my server. below is my --access-log of daphne enter image description here I tried debugging consumers.py and found nothing, but not sure how to debug daphne or server side issue. Please guide me some checklist to trace issue. I want the connection stay ALIVE for 30 minutes atleast. For setting up daphne on nginx, i followed this tutorial. -
Django threaded comments (MPTT) optimization issue
I'm using MPTT model to build a nested comments system in my Django Rest project. Everything works so far but I experience a huge performance issue when querying a database for API response. The schema of comments layout: Root Comment / \ Comment Comment / \ Child Child Whenever I'm querying all comments as an array in API response recursively: { "comments": [ { "id": 1, "children": [ "id": 4, "children": [ "id": 5, "children": ... ] ] } In this case even with "prefetch_related" and "select_related" I'm getting over 50 queries for 2 parent(root) comments (which have children comments and so on). Is there an efficient way to optimize this query? Even 2 levels comments system is acceptable for me but I can't figure out the right implementation for this: Comment \ Child1, Child2, Child3, Child4 My code for reference: class Comment(MPTTModel): profile = models.ForeignKey(Profile, related_name="comments", on_delete=CASCADE) post = models.ForeignKey(Post, related_name="comments", on_delete=CASCADE) parent = TreeForeignKey("self", related_name="children", null=True, on_delete=models.CASCADE) text = models.TextField(max_length=350) date_published = models.DateTimeField(auto_now_add=True, verbose_name="Date published") comments = Comment.objects.filter(level=0) \ .select_related("profile", "post", "profile__specialization") \ .prefetch_related("children", "parent") \ .order_by("-date_published") -
Python Django Updating object IntegrityError, NOT NULL constraint failed
I'm trying to create view for my Food Tracking App where I can first pick a given date and then add items to the FoodLog object, however while viewing macros work after picking date, I can't really add any new other objects becuase of the following error: django.db.utils.IntegrityError: NOT NULL constraint failed: accounts_foodlogfooditem.food_log_id [23/Sep/2023 13:56:08] "POST /accounts/food-log/ HTTP/1.1" 500 153768 I want to make it so that first I'll be able to pick a date and then either show what's in the FoodLog or be able to add new objects to it. My View: def food_log(request): food_log = None total_macros = {} if request.method == 'POST': date_form = DateForm(request.POST) food_item_form = FoodLogFoodItemForm(request.POST) if date_form.is_valid(): selected_date = date_form.cleaned_data['date'] food_log, created = FoodLog.objects.get_or_create(user=request.user, date=selected_date) total_macros = food_log.calculate_total_macros_log() if food_item_form.is_valid(): food_log_food_item = food_item_form.save(commit=False) food_log_food_item.food_log = food_log food_log_food_item.save() else: today = timezone.now().date() food_log = FoodLog.objects.filter(user=request.user, date=today).first() date_form = DateForm(initial={'date': today}) if food_log: total_macros = food_log.calculate_total_macros_log() food_item_form = FoodLogFoodItemForm() return render(request, 'food_log.html', {'food_log': food_log, 'date_form': date_form, 'food_item_form': food_item_form, 'total_macros': total_macros}) Models I have: class FoodLog(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) foods = models.ManyToManyField(FoodItem, blank=True, through='FoodLogFoodItem') meals = models.ManyToManyField(Meal, blank=True, through='FoodLogMeal') date = models.DateField() def calculate_total_macros_log(self): log_total_kcal = 0 log_total_carbohydrates = 0 log_total_fats = 0 log_total_proteins = … -
Why i can't use migrations with user_account in my INTERNAL APPS
When creating a custom model, when I register the app in INTERNAL APPS, the program doesn't allow me to perform migrations and throws an error: "ModuleNotFoundError: No module named 'user_account'." (Python Django). I have tried cleaning the database as we did in the class and recreating it, but with the 'user_account' line in INTERNAL APPS, it refuses to perform the migration, and without it, it says that 'user_account' is uninstalled. -
What options are available for performance tuning a soundx query?
I was recently asked about improving website performance for a peers website. What options are typically used for performance tuning sites enabled with Soundx? Overview Using the homophones Smith/Smythe, I was able to reproduce the behavior of the website query response time described. These are measured at the browser so there's a lot that could go into the number, but generally speaking the values were what we would expect, less for the non-Soundex search and more for Soundex search. Smith - Not Soundex - (1705 results) - 6.62s server wait Smythe - Not Soundex - (8 results). - 5.51s server wait Smith - Soundex - (4446 results) - 9.47s server wait Smythe - Soundex - (4446 results) - 10.85s server wait Technical Stack language - python - 2.7.5 framework - Django - 1.3 database - not yet known - not yet known NOTE: Database type and version will most likely play a role in what solutions are viable. Sources Performance: Put soundex in DB or translate it after the query? https://support.ancestry.com/s/article/Searching-with-Soundex Similar Questions Using soundex feature w/django search engine -
Using django_debug_toolbar alongside drf_spectacular
I'm using drf_spectacular as swagger for my django projects since drf_yasg is deprecated. I tried to use django_debug_toolbar alongside drf_spectacular and I followed all of the instructions. The debug_toolbar's icon appears in swagger but when I try to call any api, a 'Not Found' error keeps showing up repeatedly! What is the problem? What should I do?