Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
nested forloop: list items sorted by outer one
I have a nested forloop like this: {% for category in categories %} {% for task in tasks %} {% if task.category == category.id %} // show category name if it was not already printed {% endif %} {% endfor %} {% endfor %} I have a list of categories and some tasks. Each task has a foreignkey to a category. Now I want to list the tasks sorted by categories. So for each category I want to print a title. How can I achieve this? I don't know if it is possible to use simple variables in django template to distinguish if I already printed the category name? Or what is best practice to do this? -
Best opensource ML model for matching clash of clans bases
I have a small database containing images of clash of clans bases. What I want is to upload a clash of clans base to the system and the system should search into the database images and return some similar bases based on the input image. A very simple matching AI sort of thing. I am using Django and an opensource model called "Deep Image Search" from this repo: https://github.com/TechyNilesh/DeepImageSearch.git its code snippet is following: from pathlib import Path from DeepImageSearch import Load_Data, Search_Setup import os image_list = Load_Data().from_folder(['media/images/']) ST = Search_Setup(image_list=image_list, model_name='vgg19', pretrained=True, image_count=100) ST.run_index() metadata = ST.get_image_metadata_file() The model loads in settings so that I dont have to load it on every request. I use the model as follows: class CheckLink(APIView): permission_classes = (AllowAny,) def post(self, request): fs = FileSystemStorage(location=settings.MEDIA_ROOT, base_url=settings.MEDIA_URL) image_file = request.FILES['image'] saved_image = fs.save(image_file.name, image_file) images = settings.ST.get_similar_images(os.getcwd()+fs.url(saved_image), number_of_images=3) files = [] for image in images: image_ = StrategySerializer(Strategy.objects.get(picture__icontains=image)).data["picture"] files.append("localhost:8000/"+image_) # image = StrategySerializer(image).data return Response(files) This returns a link of similar images found in the database folder. The problem is it is not accurate at all. I dont know if I am using it right or not. Following is an image in my database: This … -
404 problems when using persian slugs in django
Hi i am using django and some slug fields . But when I use persian slugs I got 404 errors ! when I use English slugs , I got no error . here is the urls.py : re_path(r'^details/(?P<slug>[\w-]+)/', Details_view , name="Details_page"), I am not sure that I am using right regular expression ! -
'WSGIRequest' object has no attribute 'is_ajax' ,Error while adding ajax to django project
AttributeError at /order 'WSGIRequest' object has no attribute 'is_ajax' error occurred while adding ajax to django project whole project stuck. I am creating a django project and I tried with a guide. I have my code working in Development, but once I ajax added to code code get errors on ajax requests. In development, using this for submission of quizzes works perfectly well, but in development, it doesn't. I tried using pk for the submission and it returns errors and is unable to create an accurate result instance. Below are below order.html cart.js and views. while doing my restaurant Django project is added ajax for passing message to server . but server shows error and no output shown. Messege shown if request.is_ajax(): error cart.js function order(){ var test='Ajax test'; var ur='food/order'; var orderData={}; orderData['test']=test; $.ajax({ url:ur, type:'POST', data:orderData, success:function(data){ console.log("Data sent")} }) } views.py @csrf_exempt def order(request): if request.is_ajax(): test=request.POST.get['test'] print(test) ctx= {'active_link':'order'} return render(request,'food/order.html',ctx) cart.js function order(){ var test='Ajax test'; var ur='food/order'; var orderData={}; orderData['test']=test; $.ajax({ url:ur, type:'POST', data:orderData, success:function(data){ console.log("Data sent")} }) } orders.html {% extends 'food/base.html' %} {% load static %} {% block title %}Order Food here {% endblock %} {% block content %} <div class="container-fluid m-4"> … -
Avoid n+1 queries in django admin nested detail inlines
I currently have a model in my admin with a child inline: class ChildInline(admin.StackedInline): # displays fields that load other associations @admin.register(Statistic) class ParentAdmin(admin.ModelAdmin): inlines = ( ChildInline, ) This results in an n+1 problem, that could easily be solved with prefetch_related if I could get it to work! I've tried to use prefetch_related on both the child and the parent get_queryset method (among other things) with no luck in eliminating the n+1 issue. Anyone have any working code for this? -
What can cause JSON serialization error during django bulk create
I am getting a weird error when performing a bulk_create. MyModel is a ForeignKey on Item model. It's code that was working perfectly fine. Just made some changes that clean up the objects to be bulk-created, the data on the item themselves is what has been there before. items are unsaved instances of Item model. I see in the traceback that the item objects are being dumped to JSON at some point. I just don't understand why it's becoming problematic now when it wasn't before. Here is the traceback: File "/home/user/Documents/software/work/my-project/apps/myapp/importer.py", line 574, in bulk_write_to_db Item.objects.bulk_create(items, batch_size) File "/home/user/Documents/software/work/my-project/venv/lib/python3.10/site-packages/django/db/models/manager.py", line 87, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/user/Documents/software/work/my-project/venv/lib/python3.10/site-packages/django/db/models/query.py", line 803, in bulk_create returned_columns = self._batched_insert( File "/home/user/Documents/software/work/my-project/venv/lib/python3.10/site-packages/django/db/models/query.py", line 1831, in _batched_insert self._insert( File "/home/user/Documents/software/work/my-project/venv/lib/python3.10/site-packages/django/db/models/query.py", line 1805, in _insert return query.get_compiler(using=using).execute_sql(returning_fields) File "/home/user/Documents/software/work/my-project/venv/lib/python3.10/site-packages/django/db/models/sql/compiler.py", line 1822, in execute_sql cursor.execute(sql, params) File "/home/user/Documents/software/work/my-project/venv/lib/python3.10/site-packages/debug_toolbar/panels/sql/tracking.py", line 246, in execute return self._record(super().execute, sql, params) File "/home/user/Documents/software/work/my-project/venv/lib/python3.10/site-packages/debug_toolbar/panels/sql/tracking.py", line 167, in _record return method(sql, params) File "/home/user/Documents/software/work/my-project/venv/lib/python3.10/site-packages/django/db/backends/utils.py", line 67, in execute return self._execute_with_wrappers( File "/home/user/Documents/software/work/my-project/venv/lib/python3.10/site-packages/django/db/backends/utils.py", line 80, in _execute_with_wrappers return executor(sql, params, many, context) File "/home/user/Documents/software/work/my-project/venv/lib/python3.10/site-packages/django/db/backends/utils.py", line 89, in _execute return self.cursor.execute(sql, params) File "/home/user/Documents/software/work/my-project/venv/lib/python3.10/site-packages/psycopg2/_json.py", line 78, in getquoted s = self.dumps(self.adapted) File "/home/user/Documents/software/work/my-project/venv/lib/python3.10/site-packages/psycopg2/_json.py", line 72, in … -
REMITA API integration with DJANGO for receiving payment from users
Good day all, am currently working on a project with django(python) that involves payments with remita(only). I have gone throuh remita documentations, but ... Users will create account and make payment, Get a response with json response instead of webhook, and save to django model am able to make payment but am not getting response from the transact performed. Please i need help. Thanks in anticipation payment.html <title>make Payment</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.2/dist/css/bootstrap.min.css" rel="stylesheet"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.2/dist/js/bootstrap.bundle.min.js"></script> <script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script> <style type="text/css"> .button {background-color: #1CA78B; border: none; color: white; padding: 15px 32px; text-align: center; text-decoration: none; display: inline-block; font-size: 16px; margin: 4px 2px; cursor: pointer; border-radius: 4px;} input { max-width: 30%;} </style> <div class="container mt-3"> <h2>Remita Checkout Demo</h2> <p>Try out our Payment Gateway</p> <form onsubmit="makePayment()" id="payment-form"> <div class="form-floating mb-3 mt-3"> First Name: {{request.user.first_name}} </div> <div class="form-floating mb-3 mt-3"> Surname: {{request.user.surname}} </div> <div class="form-floating mb-3 mt-3"> <input type="text" class="form-control" id="js-email" placeholder="Enter Email" name="email"> <label for="email">Email</label> </div> <div class="form-floating mt-3 mb-3"> <input type="text" class="form-control" id="js-narration" placeholder="Enter Narration" name="narration"> <label for="pwd">Narration</label> </div> <div class="form-floating mt-3 mb-3"> <input type="text" class="form-control" id="js-amount" placeholder="Enter Amount" name="amount"> <label for="pwd">Amount</label> </div> <input type="button" onclick="makePayment()" value="Submit" button class="button"/> </form> </div> <script type="text/javascript" src="https://remitademo.net/payment/v1/remita-pay-inline.bundle.js"></script> <script> function … -
Django testing of PDFs - single test passes but same test fails when all tests are run
I have a Django app in which I have been using Reportlab to produce various PDFs. These are all functioning correctly. However, tests are failing in an odd manner. in various tests I'm using pypdf2.PDFReader like this: response = self.client.get(pdf_url) reader = PdfReader(BytesIO(response.content)) text = '' for page in reader.pages: text += page.extract_text() self.assertTrue("Apples" in text) I have one test which fails when I run the whole test suite. self.assertTrue("Apples" in text) AssertionError: False is not true The strange thing is, if I run the single test on it's own, or one single TestCase, everything passes. Also, if I run tests in reverse, I get 2 failures instead of 1. I checked the content being sent to Reportlab and it contains the string "Apples". PDFReader finds all the other content, but not "Apples". -
Add django package dependency to project setting installed app
i write django package name example and it has dependency to other package like rest-frame work. i want to my dependencies be added to installed app of project that using this app, text,ihave seen this question and answers but i want to add the dependencies to setting not make the user manually add them. so is it possible to add them to INSTALLED_APPS ? i have try : from django.apps import AppConfig class MyPackageAppConfig(AppConfig): name = 'example_package' def ready(self): import importlib from django.apps.registry import apps for dependency in self.get_dependencies(): try: importlib.import_module(dependency) except ImportError: pass def get_dependencies(self): # Define your package's dependencies dependencies = [ 'django-foo', 'django-bar', ] return dependencies but it didnt work i also try this: from django.apps import AppConfig class MyPackageAppConfig(AppConfig): name = 'example' def ready(self): from django.conf import settings # Add your package to INSTALLED_APPS settings.INSTALLED_APPS.append("django-foo") and in both case i add them to my inint.py file to run -
Where is my Django project on an Azure Web App
I've successfully deployed a Django app on Azure. For the time being, it's based on SQLLite, but I plan to migrate to MySQL or PostgreSQL. I connected to the Kudu console to locate my project folder. But I cannot see it. I would need that to access manage.py and launch some makemigrations, migrate and createuser for my database server to come. Is that due to the fact I am using a basic (and free) susbscription? Any other hint? Any help is welcome Richard -
How can I take the password from the card and automatically transfer it to a form on another page?
I have a history of generated passwords. Each password has its own frame with ID. Each password has login, website and date of creation in models ( Django Database). Of course when generating a password all fields except date and password are empty. On each password in the password history there is a "Save" button that would give some password a login and a website where it is used. I want that when I go to the form with saving, the password would be automatically written in the form for the corresponding field. In other words, on the history page I want to take the password id, and insert the required password, the id of which matches in the save field on the form page. history.html: <h2 class="text-center mb-4">Passwords History</h2> {% for password in passwords %} <div class="card text-center mb-4"> <div class="card-header">Password ID {{ password.id }}</div> <div class="card-body"> <h5 class="card-title">{{ password.password }}</h5> <h6 class="card-title">{{ password.login }}</h6> <p class="card-text">{{ password.website }}</p> <a href="{% url 'save_pass' password.id %}" class="btn btn-info" >Save to your Passwords</a> </div> <div class="card-footer text-muted">{{ password.date }}</div> </div> {% endfor %} In history.html every card of Password has its own "save" button. This button links to "save_pass" form in … -
ProtocolTypeRouter.__call__() missing 1 required positional argument: 'send'
I have Django application with websockets (channels). When i run this application with gunicorn core.asgi:application i experience this error Traceback (most recent call last): Sep 18 02:20:16 PM File "/opt/render/project/src/.venv/lib/python3.11/site-packages/gunicorn/workers/sync.py", line 135, in handle Sep 18 02:20:16 PM self.handle_request(listener, req, client, addr) Sep 18 02:20:16 PM File "/opt/render/project/src/.venv/lib/python3.11/site-packages/gunicorn/workers/sync.py", line 178, in handle_request Sep 18 02:20:16 PM respiter = self.wsgi(environ, resp.start_response) Sep 18 02:20:16 PM ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Sep 18 02:20:16 PM TypeError: ProtocolTypeRouter.__call__() missing 1 required positional argument: 'send' I tried looking at all of the stackoverflow or gh issues pages that were in similiar situation but nothing helped (they mostly talk about adding .as_asgi() which i already done). Also it's important to add that when i run my app with python manage.py runserver it does work fine, only on gunicorn it does not. chat/routing.py from django.urls import path from .consumers import ChatConsumer websocket_urlpatterns = [ path(r"ws/chat/<str:streamer_username>/", ChatConsumer.as_asgi()), ] core/asgi.py import os from django.core.asgi import get_asgi_application from channels.security.websocket import AllowedHostsOriginValidator from channels.routing import ProtocolTypeRouter, URLRouter os.environ.setdefault("DJANGO_SETTINGS_MODULE", "streamx.settings") asgi_application = get_asgi_application() from chat import routing # noqa: E402 from chat.middleware import JwtAuthMiddlewareStack # noqa: E402 application = ProtocolTypeRouter( { "http": asgi_application, "websocket": AllowedHostsOriginValidator( JwtAuthMiddlewareStack(URLRouter(routing.websocket_urlpatterns)) ), } ) chat/consumers.py import json from django.contrib.auth import … -
CORS issue when making GET requests to Django server behind Caddy reverse proxy
I'm encountering a CORS (Cross-Origin Resource Sharing) issue when making GET requests to my Django server, which is hosted behind a Caddy reverse proxy. Here's the situation: I have a Django server running, serving an API. The Django server is behind a Caddy reverse proxy. I'm trying to make GET requests to my Django API from a front-end application hosted at a different domain. Using JS And Ajax requests I have already tried the following: Enabled the django-cors-headers package and added it to my INSTALLED_APPS and MIDDLEWARE settings in the correct order. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', # Added this app ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', # Placed CorsMiddleware here 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] Configured CORS settings in my Django project's settings.py. DEBUG = True ALLOWED_HOSTS = ["*"] USE_X_FORWARDED_HOST = True CORS_ALLOW_ALL_ORIGINS = True CORS_ALLOW_METHODS = [ 'GET', 'POST', ] CORS_ALLOWED_ORIGINS = [ "https://www.example.net", "http://localhost:5000", "http://127.0.0.1:5000", "http://127.0.0.1:5501" ] Despite these configurations, I'm still encountering a CORS-related error when making GET requests to my Django API. Here's the error message: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://www.example.net/nodeData/?nid=13. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 200. … -
Django Rest-Framework Token Authentication not working
Hello everyone I am trying to create simple signup, login and logout page. When I enter details of signup in postman it is working I checked on admin page but when logging in it always says Invalid credentials These are all the codes I have written If you want anything more please comment on this I will provide the info ASAP settings.py INSTALLED_APPS = [ .... 'app', 'rest_framework', ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', ], } AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.ModelBackend', ] serializers.py from rest_framework import serializers from django.contrib.auth.models import User class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'email', 'password', 'first_name', 'last_name') extra_kwargs = {'password': {'write_only': True}} class UserLoginSerializer(serializers.Serializer): username = serializers.CharField() password = serializers.CharField(write_only=True) views.py from django.shortcuts import render from rest_framework import generics, permissions, status from rest_framework.response import Response from django.contrib.auth import login, logout from django.contrib.auth.models import User from rest_framework.permissions import AllowAny from .serializers import UserSerializer, UserLoginSerializer from rest_framework.authtoken.models import Token from rest_framework.authtoken.views import ObtainAuthToken class UserRegisterView(generics.CreateAPIView): queryset = User.objects.all() serializer_class = UserSerializer permission_classes = [permissions.AllowAny] class UserLoginView(generics.CreateAPIView): serializer_class = UserLoginSerializer permission_classes = [permissions.AllowAny] def post(self, request, *args, **kwargs): serializer = self.serializer_class(data=request.data, context={'request': request}) if serializer.is_valid(): user = serializer.validated_data.get('user') if user: login(request, user) token, created … -
How to add a confirmation popup dialog when saving an object in Django admin?
I have a model with name and email as fields. I want to show a warning popup to the user if there is already an entry with the same name. The user is allowed to create the entry once they acknowledge the warning. I'm looking to implement two specific features in this Django admin interface: Conditional Confirmation Pop-up: I want to display a confirmation pop-up dialog before saving data, but I want it to appear based on a specific condition. This condition is determined by user input. Confirmation for Data Saving: After clicking the 'Save' button, I want to see a confirmation dialog. Data should only be saved if the user confirms the action. I've attempted to use messages to achieve this, but I couldn't find a way to display a warning or error message before saving the data. -
How can I create tables dynamically in Django admin panel
i want to make a table for each event automaticly ,each table contains the participants of this event the result should look like this : models.py: class Student(models.Model): email = models.EmailField(unique=True) phone = models.CharField(max_length=10, blank=True) first_name = models.CharField(max_length=30, blank=True) last_name = models.CharField(max_length=30, blank=True) gender = models.BooleanField(default=1 ) ... class Event(models.Model): name = models.CharField(max_length=50) poster = models.ImageField(upload_to=get_poster_image_path,null=True,blank=True,default="events\posters\default.png") description = models.TextField(null=True,blank=True) event_date = models.DateField(null=True,blank=True) ... registrations = models.BooleanField(default=True) is_active = models.BooleanField(default=True) class EventParticipant(models.Model): event = models.ForeignKey(Event, on_delete=models.CASCADE) participant = models.ForeignKey(student, on_delete=models.CASCADE) join_date = models.DateTimeField(blank=True,null=True,default=timezone.now) ... -
Need Help Speeding Up Django and DRF with Celery TaskResult Table
I am currently working on an application that utilizes Django, Django Rest Framework (DRF), and Celery, with React in the frontend. I've been encountering a significant performance issue where loading the task results through the DRF API takes more than 10 seconds, as indicated by the debug toolbar. This issue becomes even more pronounced when multiple users attempt to access and display task results concurrently, leading to an API slowdown. In some cases, after sending around 10-15 such requests, my API becomes unresponsive for up to a minute and that causes error 499 in my nginx container making the app unusable for a minute or two. To provide some context, I am using the get_task_result_info function to update my custom SpiderTaskResult model. I've had to introduce additional fields to the default Celery TaskResult model to support the specific requirements of my Celery tasks. Here are the steps I've taken thus far to address the issue: Actions Taken: Implemented pagination in React to display a limited number of items (10 per page) in the APIView. While this approach has improved performance somewhat, it required some refactoring in the React code. Experimented with using Django's JsonResponse instead of a typical DRF APIView, … -
Should Django enumeration types like TextChoices be compared with `is` or `==`?
The Django Enumeration Types documention says that fields like models.TextChoices ... work similar to enum from Python’s standard library, but with some modifications. It's recommended to compare Enumeration members by identity (with is): >>> Color.RED is Color.RED True But the Django docs don't seem to say anything about comparing TextChoices values. Which of these two options is preferred? from django.db import models class FooChoices(models.TextChoices): FOO = "foo" BAR = "bar" class FooModel(models.Model): type = models.CharField(max_length=50, choices=FooChoices.choices) @property def is_foo(self): # Either... return self.type == DatapointDefinitionType.FOO # ... or return self.type is DatapointDefinitionType.FOO -
Why getting the "CSRF token is missing" when is already plugged in template?
I wanted to post a login form through AJAX Post request using JQuery: Even i sent the csrf token along the others however somehow Django fails to validify with the token inside a cookie. $(function(){ $(document).on('submit', 'form', function(event){ event.preventDefault(); $.ajax({ type: 'POST', url: 'login', data: JSON.stringify({ username: $('input[name=username]').val(), password: $('input[name=password]').val(), csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val() }), success: function(response){ console.log(response); } }); }); Here is the view function that url goes to: def login(request): if request.method == "POST": username = request.POST["username"] password = request.POST["password"] user = auth.authenticate(username=username, password=password) if user: auth.login(request, user) return HttpResponse("Successfully logged in!") else: return HttpResponse("Username or Password is incorrect") else: return render(request, "login.html") 1.I thought that it would be solved if i didn't use {% csrf_token %} and i tried to get token and send to be rendered in the template in view.py: from django.middleware.csrf import get_token csrf_token = get_token(request) return render(request, 'login.html', {'csrf_token':csrf_token} it didn't solve the problem i still got that error. 2.I thought that it might be something related to the csrf cookie value. Everytime i registered a user to the database just the sessionid cookie's value changed and the csrf cookie remained same but i don't know how can i go about that. Any help would … -
Django - zappa issue
"{'message': 'An uncaught exception happened while servicing this request. You can investigate this with the zappa tail command.', 'traceback': ['Traceback (most recent call last):\n', ' File "/var/task/handler.py", line 572, in handler\n with Response.from_app(self.wsgi_app, environ) as response:\n', ' File "/var/task/werkzeug/wrappers/base_response.py", line 287, in from_app\n return cls(*_run_wsgi_app(app, environ, buffered))\n', ' File "/var/task/werkzeug/test.py", line 1119, in run_wsgi_app\n app_rv = app(environ, start_response)\n', "TypeError: 'NoneType' object is not callable\n"]}" I got this error on Django Admin when I deployed Django after updating DB model. I tried to redeploy the project from scratch. sometimes it works but this issue occurs every hour. -
Using Django's Redis settings in the Langchain chat memory
I want to use Langchain inside Django and use Redis for chat memory. But I want Langchain to use the Redis settings I set in Django and not connect to Redis directly. How can I implement something like this? I use Django version 4.1 and Langchain version 0.0.275. -
Django test parallel fails while clone database
I have weird behavior of Django tests in parallel mode: Command to run tests: python manage.py test --parallel Sometimes it works fine but in random moments I got error during cloning DB. Cloning test database for alias 'default'... ERROR 1062 (23000) at line 237: Duplicate entry '0' for key 'auth_permission.PRIMARY' mysqldump: Got errno 32 on write I did it on empty DB (ran python manage.py drop_test_database before running tests) Migrations applied successfully. And after that I got error with cloning, and tests that ran on failed copies raised the next error MySQLdb.ProgrammingError: (1146, "Table 'test_dbname_8.django_content_type' doesn't exist") This is very strange because sometimes I have successful test runs. Maybe the reason is MySQL, which does not support parallel execution well? without --parallel flag tests work fine -
ktor - make a post request with different naming of the keys of the JSON in kotlin and django
I want to make a post request with different naming of the JSON keys in Ktor and django. It is not a big deal but I want to follow the convention of naming the vals in Kotlin and django. This is how my user post request body looks in Kotlin/Ktor: @Serializable data class UserPostRequest( val username: String, val email: String, val password: String, val password_check: String ) The problem with this on is the "password_check" val, which is not named by convention Property name 'password_check' should not contain underscores When I try to change it to passwordCheck, make post request, it returns me an error that the passwords do not match. I assumed this is because django expects 'password_check' as a JSON key. -
Django custom middleware doesn't caches sometime
I am trying to make a multi tenant website. For example a.com and b.com websites runs same home.html but it's values changes by it's domain name. But my middleware doesn't caches sometimes. I added my cache_tenant_mw.py and redis in settings.py MIDDLEWARE = [ ... 'rhsuite.cache_middleware.cache_tenant_mw', ] CACHES = { "default": { "BACKEND": "django.core.cache.backends.redis.RedisCache", "LOCATION": "redis://127.0.0.1:6379", } } and added the code which caches tenant values in cache_tenant_mw.py from rhsuite.models import Tenants, Themes, Settings, Metas, Languages from django.shortcuts import get_object_or_404 from django.core.cache import cache from rhsuite.helpers.utils import get_metas def cache_tenant_mw(get_response): def middleware(request): response = get_response(request) def get_hostname(request): host = request.get_host().split('.') popped = host.pop() joined = ".".join(host) return joined def get_tenant(request): hostname = get_hostname(request) tenant_obj = get_object_or_404(Tenants, name=hostname) # get metas and languages tenant_obj.metas = get_metas(Metas.objects.filter(meta_able_type="tenants", meta_able_id=tenant_obj.id)) tenant_obj.languages = Languages.objects.filter(id__in=list(tenant_obj.metas['languages'].values())) # cache tenant cache_key = "tenant" cache.set(cache_key, tenant_obj) cached_tenant = cache.get('tenant') # cache tenant settings settings_obj = Settings.objects.filter(tenant_id=tenant_obj.id) settings_key = "settings" cache.set(settings_key, settings_obj) # cache theme theme_obj = Themes.objects.get(tenant_id=cached_tenant.id) theme_key = "theme" cache.set(theme_key, theme_obj) return True get_tenant(request) return response return middleware How can i make it able to make my middleware cache every page everytime? -
What is the minimal setup for a Django Custom User Model?
I would like to install, as recommended, a custom user model for a new project early in the process, to avoid complications in migrating further down the line. But since the project is under development and acts as a testbed, I don't yet know which additional fields and methods I will require. I therefore want to get a custom user model up and running with the minimal required information so that the default registration (signup, login, etc) functions all work. I used the following code class User(AbstractUser): def __str__(self): return self.email I inherited from AbstractUser in order to obtain the default functionality, which seems to work. However, the (default) signup produces the following error in the browser: Manager isn't available; 'auth.User' has been swapped for 'accounts.User' So it seems to me that I must also define a UserManager for the custom User. Now there is much advice available about how to do this if additional functionality is required (eg make the email the username, supply extra fields, and so on). But at this stage, I don't want any additional functionality. That will come later. At this point I simply want to ensure that users can sign up, login, change passwords, …