Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
ReactJS. I can't submit image through Axios to Django Rest Framework
I really need your help. I'm trying to send image through Axios to Django Rest Framework field for my project but I'm always facing this error 'The submitted data was not a file. Check the encoding type on the form.' Here my code : models.py from django.db import models from django.db.models.signals import post_save from django.contrib.auth.models import AbstractUser class User(AbstractUser): pictureImage = models.ImageField(blank=True,null=True, verbose_name="pictureImage") serializer.py from api.models import User from django.contrib.auth.password_validation import validate_password from rest_framework_simplejwt.serializers import TokenObtainPairSerializer from rest_framework import serializers from rest_framework_simplejwt.serializers import TokenObtainPairSerializer import base64 from uuid import uuid4 from django.core.files.base import ContentFile class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'pictureImage') class MyTokenObtainPairSerializer(TokenObtainPairSerializer): @classmethod def get_token(cls, user): token = super().get_token(user) return token class RegisterSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id','pictureImage') def create(self, validated_data): user = User.objects.create( pictureImage=validated_data['pictureImage'] ) user.save() return user views.py from django.shortcuts import render from api.models import User from api.serializer import MyTokenObtainPairSerializer, RegisterSerializer from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework_simplejwt.views import TokenObtainPairView from rest_framework import generics from rest_framework.permissions import AllowAny from rest_framework.decorators import api_view class MyTokenObtainPairView(TokenObtainPairView): serializer_class = MyTokenObtainPairSerializer class RegisterView(generics.CreateAPIView): queryset = User.objects.all() permission_classes = (AllowAny,) serializer_class = RegisterSerializer @api_view(['GET']) def getRoutes(request): routes = [ '/api/token/', '/api/register/', '/api/token/refresh/' … -
why def delete(self, *args, **kwargs): method is not working in django
I have a Django model named Dates with a custom delete method as follows: from django.utils import timezone class Dates(models.Model): date = models.DateField() class Meta: verbose_name_plural = "Date" def delete(self, *args, **kwargs): if self.date < timezone.now().date(): super().delete() Could someone please help me understand why my custom delete method is not working as intended and how to make it work correctly to prevent the deletion of instances with past dates? or is this method only working in deployement? my timezone in settings.py LANGUAGE_CODE = 'en-us' TIME_ZONE = 'Asia/Kolkata' USE_I18N = True USE_TZ = True Thank you -
Is there a way to find all models that contain a GenericRelation to a particular model in Django?
Lets say we have the following model with a GenericForeignKey class Comment(models.Model): customer_visible = models.BooleanField(default=False) comment = models.TextField() content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() model = GenericForeignKey() And in several places it is referenced in other models: class Invoice(models.Model): ... comments = GenericRelation(Comment) ... class Contract(models.Model): ... comments = GenericRelation(Comment) Is it possible to get a list of the types that reference the Comment model? e.g. [Contract,Invoice] in this example? Similar functionality is possible in for instance C# with Reflection. I need something that will work when there are no references already, so Comment.objects.values('content_type') won't work. -
Which update method to override? in the mixin or the serializer?
While I am working on a project I find myself need to add some logic in the update of some entity in my model, but I don't know whether to add this logic in the update method in the UpdateModelMixin or the update method in the ModelSerializer. What is the difference between them? I searched everywhere and didn't find any specific or general answer to that question -
Dockerize Django Websocket Url not found
I have a project with Django using Websocket and I'm using a docker. I have configuration named local.yml and used uvicorn and channels. When I started to build my docker, the http request works fine but my websocket urls is not found 404 error. Here is my local.yml: version: "3" services: django: &django build: context: . dockerfile: ./compose/local/django/Dockerfile image: api_local_django container_name: api_local_django platform: linux/x86_64 restart: always depends_on: - postgres - redis volumes: - .:/app env_file: - ./.envs/.production/.django - ./.envs/.local/.postgres ports: - "8000:8000" # command: /start command: uvicorn config.asgi:application --host 0.0.0.0 # command: uvicorn config.asgi:application --bind 0.0.0.0:8000 --timeout 300 --chdir=/app # /usr/local/bin/gunicorn config.wsgi --bind 0.0.0.0:5000 --timeout 300 --chdir=/app postgres: build: context: . dockerfile: ./compose/production/postgres/Dockerfile image: api_production_postgres container_name: api_local_postgres volumes: - ./api_local_postgres_data:/var/lib/postgresql/data - ./api_local_postgres_data_backups:/backups env_file: - ./.envs/.local/.postgres ports: - "5432" redis: image: redis:6 container_name: api_local_redis celeryworker: <<: *django image: api_local_celeryworker container_name: api_local_celeryworker depends_on: - redis - postgres ports: [] command: /start-celeryworker celerybeat: <<: *django image: api_local_celerybeat container_name: api_local_celerybeat depends_on: - redis - postgres ports: [] command: /start-celerybeat flower: <<: *django image: api_local_flower container_name: api_local_flower ports: - "5555:5555" command: /start-flower Now above, I tried to start using uvicorn and it has no errors. Now here is my asgi file which handles the http … -
Django Session management with Vercel
I have a Django web app currently hosted on Vercel that displays a users top artists and tracks. It utilises the Spotify API to retrieve the access token and request the data. In my app the access token is saved using a class however I've come to a problem where if a user does not enter the site via the main page eg: spotify-app.vercel.app/ and goes straight to spotify-app.vercel.app/top-tracks they see the data of the last person who logged in because the token is saved in the class. I'm also assuming this site would not work when multiple users are on. How would I go about storing the access token for just the current user rather than saving it on the server. I have tried using the sessions library however vercel does not support it. How else can i manage my user sessions? class: class SpotifyAPI(object): access_token = None access_token_expires = datetime.datetime.now() access_token_did_expire = True client_id = None client_secret = None scope = None redirect_uri=None token_url = "https://accounts.spotify.com/api/token" def __init__(self, client_id, client_secret,redirect_uri,scope, *args, **kwargs): super().__init__(*args, **kwargs) self.client_id = client_id self.client_secret = client_secret self.redirect_uri = redirect_uri self.scope = scope def is_token_expired(self): # Check if the access token has expired access_token = …