Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to show/hide a bootstrap spinner on a button WITHOUT jQuery?
How can I show spinner on a button after clicking, disabled the button after clicking? I am using Django templates. I do not want to use jQuery at all. Looked at many other posts, most of them depend on jQuery. <link rel="stylesheet" type="text/css" href="{% static 'css/bootstrap.min.css' %}"> <script src="{% static 'js/bootstrap.bundle.min.js' %}"></script> Template submit button <!-- Submit button --> <div class="d-grid gap-2 col-6 mx-auto"> <input type="submit" value="Sign in" class="btn btn-primary btn-block mb-4" /> </div> Bootstrap example <button class="btn" type="button"> <span class="spinner-border spinner-border-sm" role="status"></span> Loading... </button> -
Django & Pycharm keep giving me URL error
I keep geeting this Login although in my project I make zero mention of log inPage not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/login/ Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: admin/ The current path, login/, didn’t match any of these. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. my actual code project django-admin mysite settings""" Django settings for mysite project. Generated by 'django-admin startproject' using Django 4.1.3. from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = "secret code" # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions. Run 'python manage.py migrate' to apply them. July 04, 2024 - 17:36:23 Django version 4.2.13, using settings 'mysite.settings' Starting … -
Performance Error with Django Import/export
I am experiencing a performance issue with Django import-export in my production environment. When importing a spreadsheet with around 3k rows, the process ends up with an Internal Server Error However, when I run the tests in the production environment, despite the delay, it successfully completes the upload of the rows. Am I missing any configuration, or does it really need to be faster to work correctly? Here are my configurations: class AtivosAssetAllocationResource(resources.ModelResource): class Meta: use_bulk = True batch_size = 1000 model = AtivosAssetAllocation fields = ('id', 'grupo', 'ticker', 'siglacmd', 'ativo', 'nomeComercial', 'conservador', 'moderado', 'agressivo', 'descricao', 'aprovado', 'classe', 'subclasse', 'range', 'previdencia') And for reference, here is the model: class AtivosAssetAllocation(models.Model): ticker = models.CharField(max_length=40, unique=True) siglacmd = models.CharField(max_length=20, blank=True, null=True) ativo = models.CharField(max_length=100) nomeComercial = models.CharField(max_length=100, blank=True, null=True) conservador = models.FloatField(blank=True, null=True) moderado = models.FloatField(blank=True, null=True) agressivo = models.FloatField(blank=True, null=True) descricao = models.TextField(blank=True, null=True) classe = models.CharField(max_length=100, blank=True, null=True) subclasse = models.CharField(max_length=100, blank=True, null=True) range = models.FloatField(blank=True, null=True) previdencia = models.BooleanField(default=False) aprovado = models.BooleanField(null=True, blank=True, default=None) def __str__(self): return self.ativo Previously, the import was done normally, but due to this error, I ended up adding the method bulk use_bulk = True batch_size = 1000 And in settings.py: # Import Export IMPORT_EXPORT_USE_TRANSACTIONS … -
Forbidden (CSRF cookie not set.) Django 4.1
I was trying to add a chatbot (dialogflow) to my current Django webpage. However, I encounter a problem. I get this message: Forbidden (CSRF cookie not set.): /. My first attempt at finding out the problem was to comment the following line in settings.py: django.middleware.csrf.CsrfViewMiddleware And got this message: Method Not Allowed (POST) So I thought, that my post routing was wrong. I was testing using Postman: Then got the following result: I will add my github with how the files are exactly located. My guess is that my routing is wrong but the other files work perfectly.food_website -
Resolve http URI for azure data lake
For the current PR, I am not able to successfully create the pre-signed urls, any suggestions? - name: stage request: method: GET url: '{django_live_url}/api/projects/{project_pk}/next' response: json: data: image_url: !re_match "/tasks/\\d+/presign/\\?fileuri=YXp1cmUtYmxvYjovL3B5dGVzdC1henVyZS1pbWFnZXMvYWJj" status_code: 200 This test above fails, the endpoint returns "azure-spi://<path/to/file>" instead of "/tasks/\d+/presign/?fileuri=YX..." -
Django Auth LDAP - Group search not working
I've been trying to get LDAP to integrate to Django without success for about a week. My problem comes on the group search. It simply does not give me any output, even though everything is correct. The user search works fine. Here's the settings.py file: AUTH_LDAP_SERVER_URI = 'xx' AUTH_LDAP_BIND_DN = 'xx' AUTH_LDAP_BIND_PASSWORD = 'xx' AUTH_LDAP_USER_SEARCH = LDAPSearch( "ou=xx,dc=xx,dc=xx", ldap.SCOPE_SUBTREE, "(sAMAccountName=%(user)s)" ) AUTH_LDAP_GROUP_SEARCH = LDAPSearch( 'ou=xx,dc=xx,dc=xx', ldap.SCOPE_SUBTREE, "(objectClass=group)" ) AUTH_LDAP_GROUP_TYPE = GroupOfNamesType(name_attr="CN") The server output: Invoking search_s('ou=xx,dc=xx,dc=xx', 2, '(sAMAccountName=luiz.moura)') search_s('ou=xx,dc=xx,dc=xx', 2, '(sAMAccountName=%(user)s)') returned 1 objects: cn=luiz moura,ou=xx,ou=xx,ou=xx,ou=xx,dc=xx,dc=xx Binding as cn=luiz moura,ou=xx,ou=xx,ou=xx,ou=xx,dc=xx,dc=xx Populating Django user luiz.moura The user is saved on the database, but no group information. Worth to mention i've tried a lot of stuff on the AUTH_LDAP_GROUP type. These are my AD configs: dn: CN=xx,OU=xx,OU=xx,OU=xx,OU=xx,OU=xx,DC=xx,DC=xx objectClass: top objectClass: group member: CN=xx,OU=xx,OU=xx,OU=xx,OU=xx,OU=xx,DC=xx,DC=xx ... -
TimedRotatingFileHandler creates logs at random timestamps
{‘file’: {‘level’: ‘DEBUG’, ‘class’: ‘logging.handlers.TimedRotatingFileHandler’, ‘filename’: os.path.join(LOG_PATH, ‘temp.log’), ‘when’: ‘s’, ‘interval’: 10, #rotates/creates new logs every 10 seconds } I have the above piece of code as a handler in my LOGGING configuration. The logging doesn’t work as expected, new log files are created at random timestamps and not every 10 seconds. How to resolve this. My project runs in a docker container and there are many files that use logging. As additional info LOG_PATH is in the /opt directory of linux filesystem -
How to Implement a Guest Login in Django REST Framework
I currently have a backend setup where users can register by providing an email, name, and password. These fields are required for registration. I want to implement a guest login feature where a guest account is deleted when the browser is closed or the guest logs out. How should I proceed to create a guest account, and what information should I include for the guest account (email, name, password)? Here is the current code: class CreateUserView(generics.CreateAPIView): """Create a new user in the system.""" serializer_class = UserSerializer authentication_classes = [TokenAuthentication] permission_classes = [permissions.UpdateOwnProfile] filter_backends = (filters.SearchFilter,) search_fields = ('name', 'email',) class UserViewSet(viewsets.ModelViewSet): """List all users.""" queryset = User.objects.all() serializer_class = UserSerializer authentication_classes = [TokenAuthentication] permission_classes = [IsAuthenticated] class CreateTokenView(ObtainAuthToken): """Create a new auth token for user.""" serializer_class = AuthTokenSerializer renderer_classes = api_settings.DEFAULT_RENDERER_CLASSES class UserLoginApiView(ObtainAuthToken): """Handle creating user authentication tokens.""" renderer_classes = api_settings.DEFAULT_RENDERER_CLASSES class LogoutView(APIView): """Logout the authenticated user.""" authentication_classes = [TokenAuthentication] permission_classes = [IsAuthenticated] def post(self, request, *args, **kwargs): request.user.auth_token.delete() return Response(status=status.HTTP_200_OK) class ManageUserView(generics.RetrieveUpdateAPIView): """Manage the authenticated user.""" serializer_class = UserSerializer authentication_classes = [TokenAuthentication] permission_classes = [IsAuthenticated] def get_object(self): """Retrieve and return the authenticated user.""" return self.request.user -
Django distinct and group_by query using the ORM and MySQL
I'd like to obtain a QuerySet containing all the latest comments for each post using Django ORM. The comments can be ordered ordered by the when field. Suppose the following example: class Post(models.Model): name = models.TextField() class Comment(models.Model): title = models.TextField() when = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(Post, on_delete=models.CASCADE) This in raw SQL could be achieved, so I assume Django may have its own way too. I'd like to avoid using raw queries (discouraged by Django documentation). I cannot use distinct() with fields names as I am using MySQL. Any indication is appreciated. -
How can anonymous users interact with Vue3 frontend, using GraphQL and Django backend?
While building a blog app, I want to create a user interaction such as like, dislike and share. However, I want the users to be anonymous (not authenticated). How can I achieve this to display counts for like, dislike and share in Vue 3 JS? I want to fetch the interactions from the backend, as the app mounts (onMounted) lifescycle hook. But when I refresh the page it displays the initial values like(0), dislike (0) and share(0). SocialMediaButtons.vue: <template> <div> <button @click="likePost" :disabled="isLiked"> <font-awesome-icon icon="thumbs-up" style="color: green; font-size: 24px; margin-right: 50px;" /> Like ({{ interactions.like }}) </button> <button @click="dislikePost" :disabled="isDisliked"> <font-awesome-icon icon="thumbs-down" style="color: red; font-size: 24px; margin-right: 50px;" /> Dislike ({{ interactions.dislike }}) </button> <button @click="sharePost" :disabled="isShared"> <font-awesome-icon icon="fa-solid fa-share" style="color: #0077B5; font-size: 24px; margin-right: 50px;" /> Share ({{ interactions.share }}) </button> <div class="social-media-icons" style="display: flex; justify-content: center; align-items: center; height: 10vh;"> Share this post on: <button @click="shareOnFacebook"> <font-awesome-icon :icon="facebookIcon" class="fa-2x icon-facebook" style="margin-right: 50px;" /> </button> <button @click="shareOnLinkedIn"> <font-awesome-icon :icon="['fab', 'linkedin']" class="fa-2x icon-linkedin" style="margin-right: 50px;" /> </button> </div> </div> </template> <script setup> import { ref, computed, watch, onMounted } from 'vue'; import { useRoute } from 'vue-router'; import { useQuery } from '@vue/apollo-composable'; import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome'; import … -
How to implement a mobile_no to be passed inorder to access tokens and not the default username and password
I'm not using password, by default simplejwt requires a default user so it prompts me for username, password and mobile_no - but I only want to user mobile no. I tried to override the TokenObtainpairSerializer - but to no success -
ModuleNotFoundError: No module named 'photo_app.wsgi'
I'm trying to deploy my Django application using Gunicorn and systemd on an Ubuntu server. However, the Gunicorn service fails to start with the following error. **ModuleNotFoundError: No module named 'photo_app.wsgi' ** ModuleNotFoundError: No module named '*.wsgi'.](https://i.sstatic.net/yNykpB0w.png) In my folder the passport_photo_maker module exists and contains a wsgi.py file. #gunicorn.service [Unit] Description=gunicorn daemon After=network.target [Service] User=gopikumarkaushik9065 Group=www-data WorkingDirectory=/home/gopikumarkaushik9065/Passport-Size-Photo-Maker ExecStart=/home/gopikumarkaushik9065/Passport-Size-Photo-Maker/venv/bin/gunicorn --workers 3 --bind unix:/home/gopikumarkaushik9065/Passport-Size-Photo-Maker/gunicorn.sock passport_photo_maker.wsgi:application [Install] WantedBy=multi-user.target if there is no mention of photo_app.wsgi in gunicorn.service then why error is occuring? -
Trying to redirect user from a booking page in django
This is my first Django project and I am really struggling. It is a simple booking app where the logged in user is on a page with a form to make a booking and a list of current bookings. I can make the page work and make a booking but the info in the form isnt cleared and if the page is refreshed it makes the booking again. To solve this, I think I need the page to redirect to a success page after the booking is made. When I try to do this, I get a "NoReverseMatch" error and am told that it is "not a valid view function or pattern name." Here are the url patterns of booking.urls.py: from django.urls import path from . import views urlpatterns = [ path("", views.home, name='home'), path("booking/", views.booking, name='booking'), path('my_bookings/', views.my_bookings, name='my_bookings'), path('edit_booking/<int:booking_id>', views.edit_booking, name='edit_booking'), path('delete_booking/<int:booking_id>', views.delete_booking, name='delete_booking'), path('success_booking/', views.success_booking, name='success_booking'), ] Here are some parts of the booking.views.py: def my_bookings(request): bookings = Booking.objects.filter(user=request.user) booking_form = BookingForm() if request.method == "POST": booking_form = BookingForm(data=request.POST) if booking_form.is_valid(): booking = booking_form.save(commit=False) booking.user = request.user booking.save() return HttpResponseRedirect(reverse('/booking_delete/')) return render( request, "booking/booking_list.html", { 'booking_form' : booking_form, 'bookings': bookings, }, ) And here is the snippet … -
How to convert a web application built in django framework into desktop stand-alone application
I have a django based web application which is working fine. Recently one customer asked for the offline version of the application. Offline means simple stand-alone desktop application. Can we convert or existing Django application into desktop application or do i need to develop the application from scratch using some other framework. There is one solution to the problem is to deploy the application locally on the desktop. But in that case our source code will be available to the customer. Please help me to find out the solution of this problem. Thanks & Regards -
How do I add a prefetch (or similar) to a django queryset, using contents of a JSONField?
Background I have a complex analytics application using conventional relational setup where different entities are updated using a CRUD model. However, our system is quite event driven, and it's becoming a real misery to manage history, and apply data migrations respecting that history. So we're moving toward a quasi-noSQL approach in which I'm using JSON to represent data with a linked list of patches representing the history. As far as data structure goes it's a very elegant solution and will work well with other services. As far as django goes, I'm now struggling to use the ORM. My database is PostgreSQL. Situation Previously I had something like (pseudocode): class Environment(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) class Analysis(models.Model): created = models.DateTime(auto_now_add=True) environment = models.ForeignKey( "myapp.Environment", blank=True, null=True, related_name="analyses", ) everything_else = models.JSONField() Whereas I now will have: class Environment(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) class Analysis(models.Model): created = models.DateTime(auto_now_add=True) everything = models.JSONField() Where everything might be a JSON object looking like... { "environment": "2bf94e55-7b47-41ad-b81a-6cce59762160", "other_stuff": "lots of stuff" } Now, I can still totally get the Environment for a given Analysis because I have its ID, but if I do something like this (again pseudocode): for analysis in Analysis.objects.filter(created=today).all(): print(Environment.objects.get(id=analysis.everything['environment']) I … -
Efficiently query django Query
We are working on newspaper with django. Before read further Let me show you the code. # Fetch lead, top, and other filtered news news_objects = news.objects.filter(website=host, is_published__in=[True], published_date__lt=current_datetime).only('Category','title','news_brief','image','img_caption','published_date','news_id') lead = news_objects.filter(status='lead').order_by('-published_date').first() top = news_objects.filter(status='top').order_by('-published_date')[:4] filtered_news = news_objects.exclude(status__in=['lead', 'top']).order_by('-published_date') # Fetch filtered categories and prefetch limited news related to filtered categories categories_with_news = catagory.objects.filter(website=host, show_front__in=[True]).prefetch_related( Prefetch('catagory', queryset=filtered_news, to_attr='limited_news') ) # Limit the news to the first 5 for each category for category in categories_with_news: category.limited_news = category.limited_news[:6]` Below code will fetch all news in specific domain. News contains more then 10k news_objects = news.objects.filter(website=host, is_published__in=[True], published_date__lt=current_datetime).only('Category','title','news_brief','image','img_caption','published_date','news_id') Below code will get only 5 news from news_objects lead = news_objects.filter(status='lead').order_by('-published_date').first() top = news_objects.filter(status='top').order_by('-published_date')[:4] below code will get all the category which will display in front along with their data. categories_with_news = catagory.objects.filter(website=host, show_front__in=[True]).prefetch_related( Prefetch('catagory', queryset=filtered_news, to_attr='limited_news') ) Again below code will fetch 6 news per category. for category in categories_with_news: category.limited_news = category.limited_news[:6] Here my problem is I don't think so this is good idea to fetch all the news for cause I will need not more then 60 news. How to do it efficiently. I tried limiting the query to 300 but there also a problem may be in some category … -
Python Set Context precision for Decimal field
from decimal import Decimal, setcontext, getcontext class MyNewSerializer(serializers.Serializer): total_value_base = serializers.SerializerMethodField() total_outgoing_value_base = serializers.DecimalField( max_digits=38, decimal_places=8, source="value_sent", ) total_incoming_value = serializers.DecimalField( max_digits=38, decimal_places=4, source="value_received", ) def get_total_value_base(self, obj): total = Decimal(obj.value_received) + Decimal( obj.value_sent ) # Values of above objects # obj.value_received = 425933085766969760747388.45622168 # obj.value_sent = 0 # total = 425933085766969760747388.4562 dec = Decimal(str(total)) return round(dec, 8) But this is throwing error: return round(dec, 8) decimal.InvalidOperation: [<class 'decimal.InvalidOperation'>] This get's fixed when i do the following: def get_total_value_base(self, obj): # the below line fixes the issue getcontext().prec = 100 total = Decimal(obj.value_received) + Decimal( obj.value_sent ) # Values of above objects # obj.value_received = 425933085766969760747388.45622168 # obj.value_sent = 0 # total = 425933085766969760747388.4562 dec = Decimal(str(total)) return round(dec, 8) I want to increase precision for all the values in the class as well as other similar classes. How can i do that using a base class or overriding the Decimal class for the whole file or for various classes in the file? I am expecting to increase the decimal precision for 100's of variables that are present in a file in various different classes. -
Upload multiple photos for a product in the store
I am loading a store site with Django. I need to upload 4 photos for one product But I can only upload one photo can you help me? my models in products: class Product(models.Model): Name = models.CharField(max_length=60) Descriptions = models.TextField() Price = models.IntegerField() Image = models.ImageField(upload_to='product') category = models.ManyToManyField(Category, null=True, blank=True) Discount = models.SmallIntegerField(null=True, blank=True) Size = models.ManyToManyField(ProductSize, related_name='product') Color = models.ManyToManyField(ProductColor, related_name='product', blank=True) Property = models.ManyToManyField(ProductProperty, related_name='product') My Views in products: class ProductDetail(DetailView): template_name = 'product/single-product.html' model = Product -
Django Form Processing - how to create a record and add it as ForeignKey
I would like to solve a problem in form handling my views.py. I would like to process a ModelForm. Instead of letting the user fill the field Field fk_transaction I would like to create a new Record of Transaction and add it as a ForeignKey in the background to the CcountBooking. The Form is displayed correctly in the the template. Also a Transaction is successfully created. However when I want to add and save it to the form in views.py it throws an error telling me that the field is not existing. Thanks for any help! My views.py: from django.http import HttpResponse from django.shortcuts import render from forms import AccountBookingForm from models import Transaction def deposit(request): context = {} if request.method == "POST": form = AccountBookingForm(request.POST) t = Transaction() form.fk_transaction = t form.save() return render(request, "deposit_success.html", {"form": form}) else: form = AccountBookingForm() return render(request, "deposit.html", {"form": form}) My models.py: class Transaction(models.Model): type = models.CharField(max_length=11, choices=TR_TYPE_CHOICES, default=DEPOSIT) status = models.CharField(max_length=11, choices=TR_STATUS_CHOICES, default=DRAFT) text = models.TextField(max_length=500, default="", blank=True) class AccountBooking(models.Model): fk_bankaccount = models.ForeignKey( BankAccount, on_delete=models.CASCADE, blank=False) fk_transaction = models.ForeignKey(Transaction, on_delete=models.CASCADE, blank=False) value = models.DecimalField(max_digits=14, decimal_places=2, blank=False) My forms.py from django.forms import ModelForm from .models import AccountBooking class AccountBookingForm(ModelForm): class Meta: model = … -
How can i add additional Data (ETIM-Featurecodes) to a existing Field [closed]
I have build a model which should representate our Products at work. Our products are different sorts of luminaires. Some of these with different variations like different colour-temperature, different housing-colour, different power, sensors or dimmable. at the moment my model looks (a little shortend) like this class ProductID(models.Model): product_id = models.CharField(max_length=100, unique=True) base_model = models.BooleanField(default=True) active = models.BooleanField(default=True, choices=CHOICES) possible_as_option = models.BooleanField(default=False, choices=CHOICES) product_variant_data = models.ForeignKey('ProductVariantData', on_delete=models.PROTECT) ... class ProductVariantData(models.Model): short_text = models.CharField(max_length=300, null=True, blank=True) packaging_unit = models.IntegerField(validators=[MinValueValidator(1)]) guarantee = models.IntegerField() product = models.ForeignKey('Product', null=True, on_delete=models.PROTECT) ... class Product(models.Model): enec = models.BooleanField(default=False) ce = models.BooleanField(default=True) min_ambient_temperature = models.IntegerField() max_ambient_temperature = models.IntegerField() ip_code = models.ForeignKey(IPCode, on_delete=models.PROTECT) ik_code = models.ForeignKey(IKCode, on_delete=models.PROTECT) dimensions = models.ForeignKey(Dimensions) cutout_dimensions = models.ForeignKey(CutoutDimensions, null=True) product_type = models.ForeignKey(ProductType, on_delete=models.PROTECT) .... class LEDData(models.Model): led_changeable = models.BooleanField(default=True) average_lifespan = models.IntegerField(null=True, blank=True) dimmable = models.BooleanField(default=False) voltage = models.DecimalField(max_digits=5, decimal_places=2, null=False) flicker_metric = models.DecimalField(max_digits=2, decimal_places=1, null=True) stroboscopic_effect_metric = models.DecimalField(max_digits=2, decimal_places=1, null=True) class LEDData(models.Model): average_lifespan = models.IntegerField() dimmable = models.BooleanField(default=True) voltage = models.DecimalField(max_digits=5, decimal_places=2, null=False) flicker_metric = models.DecimalField(max_digits=2, decimal_places=1, null=True) stroboscopic_effect_metric = models.DecimalField(max_digits=2, decimal_places=1, null=True) class Luminaire(models.Model): product = models.OneToOneField(Product, primary_key=True) control_gear_included = models.BooleanField(default=True) external_control_gear = models.BooleanField(default=True) control_gear_changeable = models.BooleanField(default=True) control_gears = models.ManyToManyField('ControlGear', through='LuminaireControlGearDetails') led_data = models.ForeignKey(LEDData) lighting_technology = models.CharField(max_length=15, choices=LightingTechnology, default=LightingTechnology.LED) ... class … -
Django App is delayed or does not reflect the changes in the new code
We have a django app deployed to AWS EC2 instances (autoscaled) via codedeploy. The deployment is successful, and I can see the new code when connected to the instances. However, the django app did not reflect the changes in the new code. Why is that? We also had a case when we did a database migration and the new fields only showed up 1 day later. WE foudn the DNS Time-To-Live (TTL) value is set to 2 days by default, which we have now updated it to a shorter timeframe. However, it hasn't made any progress. Have also restarted the servers etc. -
How to validate JWT tokens on Angular Frontend?
Please help me! I have a study project. There is a Frontend based on Angular 17 and a Backend based on Django Rest Framework. The user should be able to login through a third party API (like Google login). In my code, when a user on Fronend clicks the “log in via API” button, I redirect him to the Backend, then to a third-party service, he logs in there and the backend receives a response from the third-party service that everything is OK. Then on the Backend I create 2 JWT tokens and send them to the query string GET request to the Frontend. Frontend catches this request and authorizes the user, but it DOES NOT CHECK the tokens that they were issued by the backend and that they are correct, but only stores them in the user’s browser. That is, if I make the same request directly from the browser but with a fake secret in the token, then the user is still authorized! The question is - how to fix this? How to check tokens to ensure that they are not fake and send by backend? chatgpt and google a lot -
How to remove duplicated migration having same content in django
if we created a procedure in django project and then we need to changed variables or any changes in content. then same named procedure duplicates . we need to remove it 0002_remove_whocanapprove_approver_level_and_more 0004_remove_whocanapprove_approver_level_and_more this 2 are same then remove first one -
Django Admin - show a secondary table of related objects in the admin list view
I'm having a Django project which applies Admin pages only, i.e. no User pages at all. I'm specifically applying the Admin-UnFold flavor, with a slightly enhanced UI. Assume having 2 classes named AAA and BBB, where BBB has a ForeignKey named aaa. ( AAA may have multiple related BBBs ) Now, when listing the AAA instances, is it possible to maintain a secondary (new) table below the main one, which previews all related BBB objects for a selected AAA? The selection may be achieved with a new designated column in the main table, with "preview" button/hyperlink. From the user perspective (UI), clicking on the "preview" in the main table will allows a quick look on the corresponding related objects. Thanks ahead, Shahar -
Django GenerateSeries return same row multiple times
I've an appointment model with starts_at, repeat_duration I want to annotate the repeating values returned from a generated series the sum duration field till the end date so if date of appointment on 14-07-2024, end_date is 25-07-2024 and duration is 3 days it return 14, 17, 20, 23 as an array annotation but what I'm getting is the same object, returned multiple times and each time it has one value of the series result for the example it'll be returned four times one for each value and repeat_days will be this value object_1.repeat_days = 14 object_2.repeat_days = 17 how to make it return only one object and the values as an array tried arrayagg to wrap the GenerateSeries but I'm getting aggregate function calls cannot contain set-returning function calls class AppointmentQuerySet(models.QuerySet): def annotate_repeated_days(self, end_date): return self.annotate( repeat_dates=ArrayAgg( GenerateSeries( models.F("starts_at"), models.F("repeat_duration"), end_date ) ) ) function: from django.db import models class GenerateSeries(models.Func): function = 'generate_series' output_field = models.DateTimeField() def __init__(self, start, step, stop, **extra): expressions = [ start, stop, step ] super().__init__(*expressions, **extra) any ideas?