Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
results from ajax doesnt show up in my html template rendered with django
before I go into details about my problem, I just want to say I'm new in DJANGO/AJAX world, so if you think I can do what I want, with an easier/more efficient way, I'd be more than happy to hear it, thank you so much in advance. I have a web page which contains a search bar, and a sort of complex table structure, we are supposed to be able to search an item using the search bar and show the relative result in the table using AJAX, without the page reload, I managed to write the AJAX CALL, send it to the view, get the result data in view, so far everything works well, I print the results in view, and it works fine I get the result, but once I render the template with the result data, the table's fields are empty. I don't know where did I go wrong. any help would be much appreciated. this is the script that make the Ajax call(I use an AJAX call to show live search result, something like what google does on search, and gave every result a class name of 'SearchResultItem') $(document).on('click', 'a.SearchResultItem', e=>{ e.preventDefault(); targetAuthorityId = e.target.parentElement.id $.ajax({ … -
Django Deployment Failed during build process on Railway
I tried to deploy my django project on railway but it failed without any build or deploy logs i made procfile,requirements.txt, runtime.txt and staticfiles but this didn't change the results i created the django project and made another app called Portfolio and updated everything needed and made sure the website works locally well then uploaded everything on github repository here is a screenshot of the repository main branch -
Please enter the correct username and password for a staff account & CSRF token missing or incorrect
I am using forms.py to create a profile and using signals.py. There's a OneToOneField relationship between the profile and user. However, when I try to log in at http://127.0.0.1:8000/admin after filling out the form, that receive the following message: "Please enter the correct username and password for a staff account. Note that both fields may be case-sensitive." Additionally, when I refresh the page, sometimes get a "CSRF token missing or incorrect" error. Forbidden (CSRF token from POST incorrect.): /admin/login/ [14/Sep/2023 17:23:18] "POST /admin/login/?next=/admin/ HTTP/1.1" 403 2518 here is what I wrote: profile_form.html {% extends 'main.html' %} {% block content %} <h1>Edit Account</h1> <form method="POST" action="{% url 'edit-account' %}" enctype="multipart/form-data"> {% csrf_token %} {{form.as_p}} <input type="submit" value="Submit" /> </form> {% endblock content %} forms.py from django.forms import ModelForm from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from .models import Profile class CustomUserCreationForm(UserCreationForm): class Meta: model = User fields = ['first_name', 'email', 'username', 'password1', 'password2'] labels = { 'first_name':'name', } def __init__(self, *args, **kwargs): super(CustomUserCreationForm, self).__init__(*args, **kwargs) for name, field in self.fields.items(): field.widget.attrs.update({'class': 'input'}) class ProfileForm(ModelForm): class Meta: model = Profile fields = ['name', 'email', 'username', 'location', 'bio', 'short_intro', 'profile_image', 'social_github', 'social_linkedin', 'social_youtube','social_twitter', 'social_website'] signal.py from django.contrib.auth.models import User # Create your … -
Can I assign a combination of variables using one "with" template tag?
I have the template code value="{{ key|slice:":4" }}-{{ suggestion.pk }}" which slices the variable key, appends a "-" and the value of suggestion.pk. I now want to assign this combined value to the name id using the built-in with template tag. Is there a way to do this using one with tag or do I have to use a custom template tag? Using {% with id={{ key|slice:":4" }}-{{ suggestion.pk }} %} {{ id }} {% endwith %} doesn't work and throws the error Could not parse the remainder: '{{' from '{{'. I also tried doing something like {% with id= key|slice:":4"-suggestion.pk %} {{ id }} {% endwith %} or adding some extra quotes, which also didn't work. -
Permissions error in Docker even after giving user proper permissions
If I run uWSGI as root I get an error: | *** WARNING: you are running uWSGI as root !!! (use the --uid flag) *** and rightfully so since it is unsafe. So I create a user and give it permissions to the relevant folders: RUN adduser --disabled-password --gecos '' django-user && \ mkdir -p /vol/web/media && \ mkdir -p /vol/web/static && \ chown -R django-user:django-user /vol && \ chmod -R 755 /vol && \ chmod -R +x /scripts However, after running I run into PermissionError: [Errno 13] Permission denied: for files within /vol directory. Since it is flagged -R, this doesn't make sense. -
Django: self symmetrical intermediate model
I'm trying to make a symmetrical intermediate relationship between same models class Person(models.Model): name = models.CharField(max_length=128) friendship = models.ManyToManyField('self', through="Friendship") intermediate model: class Friendship(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE, related_name='friend1') person2 = models.ForeignKey(Person, on_delete=models.CASCADE, related_name='friend2') date_befriended = models.DateField() reason = models.CharField(max_length=64) I tried solving it by adding adding through_fields=("person", "person2") to Person(friendship), but it didn't work as expected... Note for future solution seekers:related_name is, I'm pretty sure, obligatory in the Intermediate model to avoid errors: myapp.Friendship.person2: (fields.E303) Reverse query name for 'myapp.Friendship.person2' clashes with field name 'myapp.Person.friendship which also occurs for Friendship(person/friend1) -
Configure docker-compose logging log file path and name for Celery worker
Is it somehow possible to define the path and file name of the logfiles? Because otherwise they are somewhere on the system and the requirement is to have them in the mapped logs folder. celery_worker: container_name: 'celery_worker' env_file: - .env environment: - CELERY_WORKER_NAME=celery_worker_mdx logging: driver: "json-file" options: max-size: 1k max-file: "3" build: context: backend dockerfile: Dockerfile command: sh -c "./wait-for.sh rabbitmq:5672 -- celery -A backend worker --queues=myqueue.queueA --hostname=celery-worker --concurrency=10 --pool threads" restart: unless-stopped depends_on: - rabbitmq volumes: - ./backend/backend/customer_settings/backend.py:/code/backend/customer_settings/backend.py - ./logs/backend:/code/logs When I add the --logfile parameter to the celery command then I get the logfile in the desired folder, but all other docker compose related logging settings are ignored and I still run into the problem with huge logfiles. My second approach: I also tried to define the logger and handler in settings.py, but the logger writes only to the file, if I open the django shell within the worker and log from there. If the worker is triggered via RabbitMQ rpc, the logging outputs in the same functions are only written to the console. Even the files are created properly according to settings.py for the celery worker. The loglevels are set to debug in the loggers section and … -
Use Django messages framework when a webhook is called
I have set up an URL in Django that is being used as webhook from another service. It has implemented like: @csrf_exempt @require_POST def hoof_alert(request): json_rx = json.loads(request.body.decode("utf-8")) if json_rx["alerts"][0]["status"] == "firing": messages.error("Alarm fired") else: messages.success("No more alarm") returns HttpResponse(status=200) Now, the main issue is that, even if the function is called, as I see it happens on the console and my service get back the code 200 status, I can't see the message popping up on the front end. My guess is that, the message is attached to the request done on the webhook, which is not the request an user will do when access the website. So, my question is, how do I make the message being visible on the front end when the hook is called? -
Send Sms and Mms to users with my company numbers
Is it possible to utilize a third-party API in Python for sending both MMS and SMS messages? I'm looking to avoid sending SMS messages using the purchase numbers provided by the third-party platform. Instead, I intend to send SMS and MMS using my personal phone numbers or a list of numbers that I can add to the platform. I've attempted to send messages using Python with Twilio or Click Send, but it seems they only allow sending messages from the numbers they provide on their platforms. What I'm aiming for is to send MMS from my company's specific number. -
Djongo library error when adding an object to database
I am getting a djongo library error when I am trying to add an Station object in my admin panel. The error page says there is no exception message supplied so I am facing difficulty to pinpoint what is causing the error. The error is of RecursionError File "C:\Users\Admin\Envs\routemaster\lib\site-packages\sqlparse\tokens.py", line 19, in __contains__ return item is not None and (self is item or item[:len(self)] == self) RecursionError: maximum recursion depth exceeded in comparison I asked chatgpt about the same and it suggested me to check my models.py file for any loops in relationship with other models but I did and I think my models.py file is not causing this, So can it be a bug on djongo's side? models.py from djongo import models class City(models.Model): name = models.CharField(max_length=100) class Station(models.Model): name = models.CharField(max_length=100) # Add other station-related fields as needed city = models.ForeignKey(City, on_delete=models.CASCADE) def __str__(self): return self.name class Bus(models.Model): number = models.CharField(max_length=10) # Add other bus-related fields as needed # Define a Many-to-Many relationship with Station stations = models.ManyToManyField(Station) def __str__(self): return self.number -
Django test for JWT Api
I am writing test for JWT Api Django and receiving the error '..in test_refresh_token self.assertIn("refresh", resp.json()). AssertionError: 'refresh' not found ' Could you please help to understand what I am doing wrong? class TestJWTAuth(APITestCase): @classmethod def setUpTestData(cls): faker = Faker() profile = faker.simple_profile() cls.user_pass = faker.password(8) cls.user = User.objects.create_user( username=profile["username"], password=cls.user_pass, email=profile["mail"], ) def test_no_data(self): resp = self.client.post(reverse("token_obtain_pair")) self.assertEqual(resp.status_code, status.HTTP_400_BAD_REQUEST) data = resp.json() self.assertIn("username", data) self.assertIn("password", data) def test_with_valid_user_data(self): resp = self.client.post( reverse("token_obtain_pair"), data={ "username": self.user.username, "password": self.user_pass, }, ) self.assertEqual(resp.status_code, status.HTTP_200_OK) data = resp.json() self.assertIn("access", data) self.assertIn("refresh", data) def test_with_invalid_user_data(self): resp = self.client.post( reverse("token_obtain_pair"), data={ "username": self.user.username, "password": "INVALID_PASSWORD", }, ) self.assertEqual(resp.status_code, status.HTTP_401_UNAUTHORIZED) self.assertDictEqual( resp.json(), { "detail": "No active account found with the given credentials", }, ) def test_refresh_token(self): resp = self.client.post( reverse("token_obtain_pair"), data={ "username": self.user.username, "password": self.user_pass, }, ) self.assertEqual(resp.status_code, status.HTTP_200_OK) refresh_token = resp.json()["refresh"] resp = self.client.post(reverse("token_refresh"), data={"refresh": refresh_token}) self.assertEqual(resp.status_code, status.HTTP_200_OK) self.assertIn("refresh", resp.json()) -
How to encrypt and store confidential, financial data with Django with readable data on the Admin interface?
I want to create a Django model in a way, where the data is stored encrypted in the default database, with a secondary lookup database. I would like to ask what should I implement and how to still be able to show readable data on the admin interface. This is my first try for implementation: from cryptography.fernet import Fernet from django.db import models, connections key = Fernet.generate_key() class EncryptedBankAccountModel(models.Model): encrypted_bank_account_number = models.BinaryField() def save(self, *args, **kwargs): cipher_suite = Fernet(key) temp_encrypted_bank_account_number = cipher_suite.encrypt(self.encrypted_bank_account_number) lookup_db = connections['lookup_db'] with lookup_db.cursor() as cursor: # what code should work here? cursor.execute("INSERT INTO core_lookupbankaccount (encrypted_bank_account_number,bank_account_number) VALUES (%s)", [temp_encrypted_bank_account_number , self.encrypted_bank_account_number]) encrypted_bank_account_number = temp_encrypted_bank_account_number super(EncryptedBankAccountModel, self).save(*args, **kwargs) class LookupBankAccountModel(models.Model): encrypted_bank_account_number = models.BinaryField() bank_account_number = models.CharField(max_length=255) Is my approach secure enough? How should I implement the Admin class, should I save the key out (if so where and how)and use it to decrypt the default database model, or should I use the lookup (if so how)? Thank you for answering in advance! -
How can we clone a html form with its data and styling?
I have a form which is used for data entry. the entire system is built using Django and here is what it contains as of now 1.it has a button which dynamically duplicates the form without(without the value) so that users can enter multiple data and use a single Submit(Achieved using HTMX) 2. a deleterow button which will delete each of the newly generated rows so that unwanted rows can be deleted 3. These functionalities are working fine 4. the form is basically inside a html table which allows it to maintain the shape and structure What i want is that i want a duplicate button alongside each form which upon clicking will duplicate the form inside a div with the table structure with values so that users can use easily fill similar data . like if one row is filled and we hit duplicate it will create a clone below that and when we hit duplicate on the next row it will create that rows duplicate below it 5. it also has a combination of Select fields, Textfields and date fields Attaching picture of my form layout Picture of form layout what i want is similar to this but … -
how to schedule notifications using flutter and firebase cloud messaging
im working on a project using flutter and django rest framework, I want notify the user of the app daily like a remainder to do his daily missions my problem is how to schedule the notification daily. i have hosted my django project in pythonanywhere. -
How to fix SMTPSenderRefused at /register/ in Django
I'm developing an application in Django with a friend, and we've implemented account activation functionality by sending an activation email with a link. Unfortunately, we've encountered an issue where I can register successfully, and the activation email is sent without any errors, but my friend receives an error like the one shown in the image below upon registration and clicking 'Register.' Error screenshot This is my code in settings: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_FROM = os.environ.get('EMAIL_LOGIN') EMAIL_HOST_USER = os.environ.get('EMAIL_LOGIN') EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_PASSWORD') EMAIL_PORT = 587 EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = os.environ.get('EMAIL_LOGIN') How can we resolve this issue? -
Need to output each item from a list in a for loop in jinja (python)
I have a list {{category_masks}} And i have a code {% for pansion in pansions %} <div class="card"> <a href="{{ pansion.get_absolute_url }}"> <img src="{{ pansion.preview_picture.url }}" alt="{{ pansion.title}}" class="preview-picture"> </a> <div class="pe-3 ps-3 d-flex flex-column h-100"> <p class="name mb-3"> <a href="{{ pansion.get_absolute_url }}"> {% if pansion.title_mask and category_masks %} {{category_masks.0}} {{pansion.title_mask}} {% else %} {{ pansion.title }} {% endif %} </a> </p> </div> </div> {% endfor %} I need to output each item from {{category_masks}} to the pansion element in turn. If the list of {{category_masks}} ends, then the loop is repeated {{category_masks.0}} just output first element in all pansions, it's a test for me now, it's doesn't matter for now Note. I don't need to output all {{category_masks}} in one pansion element Anyone have an ideas? Increments are not work in jinja, i am already tried -
How to serialize DRF ManyToManyField "through" model?
I cannot make DRF serialize intermediate "through" model properly. Here's an example code. Models class Track(models.Model): title = models.CharField(max_length=200) duration = models.PositiveIntegerField() def __str__(self): return {self.title} class Album(models.Model): title = models.CharField(max_length=200) tracks = models.ManyToManyField(Track, through="AlbumTrack") def __str__(self): return self.title class AlbumTrack(models.Model): album = models.ForeignKey(Album, on_delete=models.CASCADE) track = models.ForeignKey(Track, on_delete=models.CASCADE) score = models.PositiveIntegerField(default=0) class Meta: unique_together = ('album', 'track') def __str__(self): return f"{self.album.title} - {self.track.title} ({self.score})" Serializers class AlbumTrackSerializer(serializers.ModelSerializer): track_id = serializers.IntegerField(source='track.pk') track_title = serializers.CharField(source='track.title') track_score = serializers.CharField(source='score') class Meta: model = AlbumTrack fields = ('track_id', 'track_title', 'track_score') class AlbumSerializer(serializers.ModelSerializer): tracks = AlbumTrackSerializer(many=True) class Meta: model = Album fields = ('title', 'tracks') When I access /api/albums/ I get an exception: Got AttributeError when attempting to get a value for field `id` on serializer `AlbumTrackSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `Track` instance. Original exception text was: 'Track' object has no attribute 'track'. DRF appears to be resolving tracks to a Track QuerySet before serializing it. Is it possible to prevent that? I need to serialize AlbumTrack model in order to access score field. -
django: Updating multiple object in one view
I'm trying to make a page in my website for reviewing comments and accepting them. I also want to paginate it. But I don't know how can I update multiple objects of one model in on page. this is my comment model: class Comment(models.Model): YES_NO_CHOICES = ( ('y', 'بله'), ('n', 'خیر'), ) author = models.ForeignKey(to=get_user_model(), on_delete=models.CASCADE, related_name='comments', verbose_name='نویسنده', null=False, blank=False) post = models.ForeignKey(to=Post, on_delete=models.CASCADE, related_name='comments', verbose_name='پست', null=False, blank=False) text = models.TextField(max_length=480, verbose_name='متن', null=False, blank=False) datetime_created = models.DateTimeField(auto_now_add=True, verbose_name='زمان نوشتن', null=False, blank=False) accepted = models.CharField(max_length=1, choices=YES_NO_CHOICES, verbose_name='تایید شده', default='n', null=False, blank=False) checked = models.CharField(max_length=1, choices=YES_NO_CHOICES, verbose_name='بررسی شده', default='n', null=False, blank=False) class Meta: verbose_name = 'کامنت' def __str__(self): return self.text[:20] It also should trun checked to y after checking and accepting or not accepting the comment. I have no idea of how should I do something like this and that's why there is no code of my attempts. -
How to optimize Django's model's string representation database hits in browsable API
I am currently trying to optimize my API and noticed that the browsable API is responsible for N+1 queries. This only happens when I add the parent-class in the child's __str__ method. Comparison using django-debug-toolbar: f"{self.name} ({self.client.name})": default 531.44 ms (370 queries including 358 similar and 348 duplicates ) f"{self.name}": default 130.54 ms (24 queries including 12 similar and 2 duplicates ) My (simplified) models are the following: class Client(models.Model): """Model for a Client.""" name = models.CharField(max_length=128, unique=True, verbose_name="Company name") class Meta: """Set ordering.""" ordering = ["name"] def __str__(self): """Return a good string representation for a Client.""" return f"{self.name}" class Budget(models.Model): """Model for representing a budget of a client.""" name = models.CharField(max_length=128, verbose_name="Budget name") client = models.ForeignKey(Client, related_name="budgets", on_delete=models.PROTECT) class Meta: """Set ordering.""" constraints = [models.UniqueConstraint(fields=["client", "name"], name="unique_client_budget_name_combination")] ordering = ["name"] def __str__(self): """Return a good string representation of a Budget.""" # self.client.name triggers multiple database hits return f"{self.name} ({self.client.name})" I have also tried using select_related("client") in the view, but this did not help. It seems like the browsable API is not using the view's queryset. How can I make the browsable API make more efficient? Is that even possible? -
Django Subscription
Razor pay dashboardI am trying to implement the subscription feature in my Django website, and I am using Razor pay payment gateway. My payment method is working fine as the payment details are showing in Razor pay dashboard, but after successful payment, membership is not getting assigned to user based on purchased. Please help me out as I am stuck here, not getting proper solution when doing search. I want to fix it, not getting any solution. Please help me out here. #models.py # Create a membership type model class MembershipType(models.Model): name = models.CharField(max_length=100) description = models.TextField() def __str__(self): return self.name # Create a membership plan model class MembershipPlan(models.Model): membership_type = models.ForeignKey(MembershipType, on_delete=models.CASCADE) name = models.CharField(max_length=100) price = models.IntegerField() duration = models.PositiveIntegerField(null=True) features = RichTextField() def __str__(self): return self.name # Create a user membership model class UserMembership(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) membership_plan = models.ForeignKey(MembershipPlan, on_delete=models.SET_NULL, null=True) start_date = models.DateTimeField(default=timezone.now) end_date = models.DateTimeField(null=True) payment_id = models.CharField(max_length=100, null=True) def __str__(self): return self.user.username def activate(self, payment_id): # Set the payment id and end date based on the plan duration self.payment_id = payment_id self.end_date = self.start_date + timezone.timedelta(days=self.membership_plan.duration) self.save() def is_active(self): # Check if the current date is within the start and end date … -
User Registration Fails In Keycloak
I am performing User Registration process in Django with Keycloak for which I deployed Keycloak docker container (JBoss/Keycloak Version: 16.1.1) and Python version 3.8 and Django Version 4.2.5 .When I was performing the registration process I came across the error as shown in the image below , it shows "Error registering user", for more reference image attached below, enter image description here I couldn't able to register user in Keycloak through Django as the access token generated is not send with user data for registering, couldn't figure out the possible reason for it, also adding the piece of code for better understanding which I have implemented def register(request): if request.method == 'POST': username = request.POST.get('username') email = request.POST.get('email') firstname = request.POST.get('firstName') lastname = request.POST.get('lastName') password = request.POST.get('password') client_id = KEYCLOAK_CLIENT_ID client_secret = KEYCLOAK_CLIENT_SECRET # Request access token from Keycloak data = { 'grant_type': 'client_credentials', 'client_id': client_id, 'client_secret': client_secret, } token_url = f'{KEYCLOAK_TOKEN_URL}' r = requests.post(token_url, data=data) logger.info('success') if r.status_code == 200: access_token = r.json()['access_token'] headers = { 'Authorization': f'Bearer {access_token}', 'Content-Type': 'application/json' } user_url = f'{KEYCLOAK_USER_URL}' #Posting The User Data To Keycloak user_data = { 'username': username, 'email': email, 'firstName': firstname, 'lastName': lastname, 'enabled': True, 'credentials': [{ 'type': 'password', 'value': … -
Internal server error when DEBUG=False in Wagtail
hello you beautiful people! As soon as I set DEBUG=False, my website returns an internal server error. Going to /admin works, and I see the admin panel, however without any static files (CSS, JS) applied. the error I am getting: [14/Sep/2023 10:47:31] "GET /favicon.ico HTTP/1.1" 500 369 With DEBUG=True, I get no errors whatsoever. I have already tried: redefining STATIC_ROOT and MEDIA_ROOT in production.py as detailed here running collectstatic (in my pythonanywhere console, where my website is deployed. if I run the command locally and then push the code to pythonanywhere, I additionally get a merge conflict because the static files manifest cannot be found). setting up logging in my base.py. The resulting logfile contains no errors, only a lot of lines like the below: [13/Sep/2023 14:10:50] DEBUG [django.utils.autoreload:394] File /home/username/.virtualenvs/mysite-virtualenv/lib/python3.10/site-packages/wagtail_localize/locale/ta/LC_MESSAGES/djangojs.mo first seen with mtime 1692563590.7096848 path of the favicon: mysite\static\img\favicon.ico from base.html: <link rel="shortcut icon" href="{% static 'img/favicon.ico' %}" /> from base.py: STATICFILES_DIRS = [ os.path.join(PROJECT_DIR, "static"), ] STATICFILES_STORAGE = "django.contrib.staticfiles.storage.ManifestStaticFilesStorage" STATIC_ROOT = os.path.join(BASE_DIR, "static") STATIC_URL = "/static/" MEDIA_ROOT = os.path.join(BASE_DIR, "media") MEDIA_URL = "/media/" Very thankful for any pointers!! -
django.core.exceptions.FieldError: Cannot compute Foo('Bar'): 'Bar' is an aggregate
I have some models in django like this: class Activity(models.Model): type = models.CharField(verbose_name=_('type'), choices=ActivityTypeChoices.choices) class UserActivity(BaseLogged): activity = models.ForeignKey(to='Activity', on_delete=models.CASCADE) user = models.ForeignKey(to='UserInterface', on_delete=models.CASCADE) class Rule(models.Model): activity = models.ForeignKey(to=Activity, on_delete=models.CASCADE) condition = models.IntegerField() class RuleSet(models.Model): """ This model is used for checking one or more rule together. If all the rules are done, the set of rules is considered done """ rules = models.ManyToManyField(to=Rule) class RuleSetGroup(models.Model): """ This model is used for checking one rule set among multiple rule sets. If one of the rule sets are done, the whole group of rule set is considered done. """ rule_sets = models.ManyToManyField(to=RuleSet) A Rule is done when the number of UserActivities with the same activity is more than the condition. A RuleSet is done when all of its rules are done. A RuleSetGroup is done when one of its rule_sets is done How can I check if a RuleSetGroup is done or not? I did something like this: RuleSet.objects.annotate(done=Min(Case(When(Q( rules__condition__lte=Count('rules__activity__useractivity__user_id') ), then=1), default=0, output_field=IntegerField()))) But it raises this error: django.core.exceptions.FieldError: Cannot compute Min('<Case: CASE WHEN <Q: (AND: ('rules__condition__lte', Count(F(rules__activity__useractivity__us er_id))))> THEN Value(1), ELSE Value(0)>'): '<Case: CASE WHEN <Q: (AND: ('rules__condition__lte', Count(F(rules__activity__useractivity__user_id))))> THEN Value(1), ELSE Value(0)>' is an aggregate Although I did … -
Hybrid-Search Architecture for E-Commerce Website
My question might be a little vague, but I am asking for best practice when it comes down to setting a search architecture for e-commerce website. Our current, relevant stack consists of; Django/Python/DRF for the Backend Vue3 for the Frontend At the moment, all our search is done via TypeSense (think Elasticsearch, but less bloated) search engine, that is populated from Postgres database. We have lots of Records (Django model) entries in the database and those records can have a lots of different attributes. Instead of EAV structure, we solved this by simply putting all those attributes into json field on the model. from django.db.models import JSONField class Record(BaseModel, NonDeletableMixin): ... other fields attributes = JSONField(default=dict, blank=True, null=True)` Now, there are few requirements that we have. We want to support faceted search, but only for a small subset of Record attributes - Record Overview Page We also want to be able to search through all attributes in json field - Search Page The question and the problem we are having is that we don't want to implement search functionality twice, once for TypeSense and once for Postgres. Postgres allowed precice search in json field but does not offer faceted search. … -
Does `select_for_update()` method combine with `filter()` method & chain with `update()` method explicitly lock records in table?
I use select_for_update() method to lock record in table for updating. The https://docs.djangoproject.com/en/4.2/ref/models/querysets/#select-for-update Django 4.2 documentation states that "when the queryset is evaluated, all matching records will be locked until the end of the transaction block". When I use select_for_update() method chain with filter() method & update() method to update the queryset in one line of code, I figure out that the 'SELECT ... FOR UPDATE' exists in the SQL code (I am using Postgresql) without evaluating. So does my code explicitly lock records without evaluating the queryset when combining select_for_update() method with filter() method? Here is my testing function: def testing_select_for_update(): accounting_period_obj = AccoutingPeriod.objects.latest('id') product = Product.objects.get(name='Cebraton') with transaction.atomic(): accounting_period_inventory_obj = AccountingPeriodInventory.objects.select_related('accounting_period_id', 'product_id').select_for_update().filter( accounting_period_id=accounting_period_obj, product_id__name=product.name ) accounting_period_inventory_obj.update(starting_inventory=10) connection_queries = connection.queries for connection_query in connection_queries: print(connection_query) The SQL code in the transaction block is: {'sql': 'UPDATE "major_features_accountingperiodinventory" SET "starting_inventory" = 10 WHERE "major_features_accountingperiodinventory"."id" IN (SELECT U0."id" FROM "major_features_accountingperiodinventory" U0 INNER JOIN "major_features_product" U2 ON (U0."product_id_id" = U2."sku") WHERE (U0."accounting_period_id_id" = 4 AND U2."name" = \'Cebraton\') FOR UPDATE)', 'time': '0.000'}