Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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'} -
Encrypt using Fernet in Django and Decrypt in PHP - Error Decryption failed
I'm required to Decrypt value from DB in php, but the value Encrypt in Django using Fernet. I tried something but it doesn't work. I getting this error message Decryption failed: error:0606508A:digital envelope routines:EVP_DecryptFinal_ex:data not multiple of block length Here what i have tried $encryption_key = Using same key from django; $ekyc = Wallet::find('1'); $value= $ekyc->address; $decodedData = base64_decode(strtr($value, '-_', '+/')); echo "Decoded Data: " . bin2hex($decodedData) . "<br>"; // Extract the initialization vector (IV) and ciphertext $ivSize = openssl_cipher_iv_length('aes-128-cbc'); $iv = substr($decodedData, 0, $ivSize); $ciphertext = substr($decodedData, $ivSize); echo "IV: " . bin2hex($iv) . "<br>"; // Replace 'aes-128-cbc' with the appropriate cipher and mode if needed $decrypted_data = openssl_decrypt($ciphertext, 'aes-128-cbc', $encryption_key, OPENSSL_RAW_DATA, $iv); if ($decrypted_data === false) { die('Decryption failed: ' . openssl_error_string()); } dd($decrypted_data); I'm expected to get the decrypted value. Can please advice what is wrong and how can i solve this? Thank you so much -
Auto Login after email verification in djoser using JWTAuthentication
I'm using djoser in my django project and JWTAuthentication for authentication. I want to auto login user (i.e. create access and refresh token) after verifying email and redirecting to ACTIVATION_URL defined in settings. The problem is that they are 2 different actions each with its own endoint and view: 1- TokenObtainPairView which authenticates user and creates the tokens. 2- djoser activation function which just activates user if email is verified. My thought is to customize the activation view, authenticate user from there but also create and send the tokens, how to do so ? and Is it a good approach? -
Django: catch database integrityerror
I have a model with a unique field - something like: class UniquePerson(models.Model): name = models.CharField(max_length = 100, unique=True) ... The user can submit new persons; if the name already exists we should just return an error message - i.e. a view like this: def add_person(request, name): try: person = UniquePerson.objects.create(name = name) return HttpResponse(f"New person with name: {name} added") except ????? return HttpResponse(f"Error: person with name: {name} already registered in DB") But - I can not seem to catch the IntegrityError from the database when I try to add a name which already exists in the database? What is the idiomatic way to handle this situation? -
Django - How to disable syntax suggestion in VSCode?
Hello friend does anyone know how to disable this type of suggestion in VSCode? It always gives me "-> HttpResponse" (shadow-suggestion). It makes me confused sometimes -
how to read <class 'django.core.files.uploadedfile.InMemoryUploadedFile'> file using gencache.EnsureDispatch("Excel.Application")
I have been trying to read inmemory file using win32com.client named EnsureDispatch. but it gives error like this "pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, 'Microsoft Excel', "Sorry, we couldn't find QUANDA_USER_TEMPLATE_ver2.0.xlsx. Is it possible it was moved, renamed or deleted?", 'xlmain11.chm', 0, -2146827284), None)". But if I give the proper local file path then it is able to read. from win32com.client import Dispatch, gencache import pythoncom import time import os import io pythoncom.CoInitialize() myxlsx = gencache.EnsureDispatch("Excel.Application") myxlsx.Visible = 1 myxlsx.Workbooks.Open(tmp_file) # tmp_file is the InMemoryUploadedFile which is uploaded by django rest # #framework api above code is giving error as mentioned above. but if i give the local file path then it works fine as below local_path = "myexcel.xlsx" myxlsx.Workbooks.Open(local_path) now I dont want to save file in my local as there will be 100th s of users who will be uploading the file. how can I read that inmemory file using win32.com. please help if any better solution is available. Thanks in advance. -
Django custom-user error: HINT: Add or change a related_name argument to the definition for 'custom_auth.CustomUser.groups' or 'auth.User.groups'
I need help. I'm creating an registration/login app in Django and I'm having some trouble making migrations of my CustomUser class. Below is the error: SystemCheckError: System check identified some issues: ERRORS: auth.User.groups: (fields.E304) Reverse accessor 'Group.user_set' for 'auth.User.groups' clashes with reverse accessor for 'custom_auth.CustomUser.groups'. HINT: Add or change a related_name argument to the definition for 'auth.User.groups' or 'custom_auth.CustomUser.groups'. custom_auth.CustomUser.groups: (fields.E304) Reverse accessor 'Group.user_set' for 'custom_auth.CustomUser.groups' clashes with reverse accessor for 'auth.User.groups'. I tried adding a related name as was a suggestion to a similar question here, but it still throws the same error when I makemigrations. The code for my models.py is as below: # custom_auth/models.py from django.contrib.auth.models import AbstractUser from django.db import models # Create your models here. class CustomUser(AbstractUser): phone_number = models.CharField(max_length=15) designation = models.CharField(max_length=100) # Add a related_name to the user_permissions field user_permissions = models.ManyToManyField( to='auth.Permission', related_name='custom_users', blank=True, ) -
Problem while using django Prefetch object
In my django application I have three models that are class Restaurant(models.Model): class TypeChoices(models.TextChoices): INDIAN = 'IN','Indian' CHINESE = 'CH','Chinese' ITALIAN = 'IT','Italian' GREEK = 'GR','Greek' MEXICAN = 'MX','Mexican' FASTFOOD = 'FF','Fast Food' OTHERS = 'OT','Other' name = models.CharField(max_length=100,validators=[validate_name]) website = models.URLField(default='') date_opened = models.DateField() latitude = models.FloatField( validators=[MinValueValidator(-90),MaxValueValidator(90)] ) longitude = models.FloatField( validators=[MinValueValidator(-180),MaxValueValidator(180)] ) restaurant_type = models.CharField(max_length=2,choices=TypeChoices.choices,default='') def __str__(self): return self.name class Rating(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) restaurant = models.ForeignKey(Restaurant,on_delete=models.CASCADE,related_name='ratings') rating = models.PositiveSmallIntegerField( validators=[MinValueValidator(1), MaxValueValidator(5)] ) class Sale(models.Model): restaurant = models.ForeignKey(Restaurant,on_delete=models.SET_NULL,null=True, related_name='sales') income = models.DecimalField(max_digits=8,decimal_places=2) datetime = models.DateTimeField() I want to get total sales of all restaurant within a month which have five star rating My view is like this def index(request): month_ago = timezone.now() - timezone.timedelta(days=30) monthly_sales = Prefetch('sales',queryset=Sale.objects.filter(datetime__gte=month_ago)) restaurant = Restaurant.objects.prefetch_related('ratings',monthly_sales).filter(ratings__rating=5).annotate(total=Sum('sales__income')) context = {'restaurants':restaurant} return render(request,'index.html',context) Template I used is {% for restaurant in restaurants %} <p>{{restaurant.name}} - {{restaurant.total}}</p> {% endfor %} The problem her is I'm getting sales before one month. I want only the sales within a month. -
How to creat & deploy react & django project to Elastic Beanstalk?
I want to creat a web application using React as frontend & Djanog as backend, and deploy that web application to Elastic Beanstalk. What should I do (separate frontend from backend folder?) to make Easy deployment to Elastic Beanstalk. I don't find any resource that provide step by step on deployment of React & Django to Elastic Beanstalk.