Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What does the carat (^) operator do on Django Q objects?
The Django Query documentation mentions three operators which can be used to combine Q objects: Q objects can be combined using the &, |, and ^ operators. But the examples in the docs all focus on | (which is maybe understandable). The & and | operators are (to me at least) fairly obviously analogous to AND and OR. But what does ^ translate to in SQL? -
Getting this Error, while integrating stripe payments. You provide API key and more
I was following a YouTube video on building an Video Subscriptions Site in Django. However, while integrating stripe I got this error, "You did not provide an API key. You need to provide your API key in the Authorization header, using Bearer auth (e.g. 'Authorization: Bearer YOUR_SECRET_KEY'). See https://stripe.com/docs/api#authentication for details, or we can help at https://support.stripe.com/.)." I am beginner so I don't know much about it, here is the Models.py Code: The code is identical to the video import django.db.models.deletion from django.conf import settings from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Membership', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('slug', models.SlugField()), ('membership_type', models.CharField(choices=[('Enterprise', 'ent'), ('Professional', 'pro'), ('Free', 'free')], default='Free', max_length=30)), ('price', models.IntegerField(default=15)), ('stripe_plan_id', models.CharField(max_length=40)), ], ), migrations.CreateModel( name='UserMembership', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('stripe_customer_id', models.CharField(max_length=40)), ('membership', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='membership.membership')), ('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), migrations.CreateModel( name='Subscription', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('stripe_customer_id', models.CharField(max_length=40)), ('user_membership', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='membership.usermembership')), ], ), ] Urls.py from django.conf import settings from django.contrib import admin from django.conf.urls.static import static from django.urls import path urlpatterns = [ path('admin/', admin.site.urls), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Settings.py """ Django settings … -
Rebalancing problem with Faust Streaming consumer
Hello everyone hope I find you well! I'm facing an odd situation when using Faust Streaming in my consumer app. So I have a Kafka Consumer that connects to my Kafka GCP instance on my dev environment in Google Cloud. However when sometimes my Kafka instance restarts or goes down to lack of resources when my consumer tries to rebalance it stays stuck in a loop with the following errors logging: [2023-12-20 10:23:47,912] [11] [INFO] Discovered coordinator 2 for group myapp-dev-processor [2023-12-20 10:23:47,912] [11] [INFO] (Re-)joining group myapp-dev-processor [2023-12-20 10:23:47,915] [11] [WARNING] Marking the coordinator dead (node 2)for group myapp-dev-processor. This is happening frequently for us only on our dev environment but we are investigating what may be the root cause of this issue and how to tackle it so that if it occurs in prod we have an way to act fast. We know the consumer connects to our kafka instance with success but then this error happens and it stays stuck in an endless loop. We tried search for any error log on our kafka instances but we don't find anything so we think this may be a problem within the library somehow. Does anyone have any idea … -
Django built in Logout view `Method Not Allowed (GET): /users/logout/`
Method Not Allowed (GET): /users/logout/ Method Not Allowed: /users/logout/ [10/Dec/2023 12:46:21] "GET /users/logout/ HTTP/1.1" 405 0 This is happening when I went to url http://127.0.0.1:8000/users/logout/ urls.py: from django.contrib.auth import views as auth_views path('users/logout/', auth_views.LogoutView.as_view(), name='logout'), I am expecting user to logout -
I am using Django version 5.0 . At the stage of creating the superuser with the following command [closed]
python manage.py createsuperuser This command was supposed to ask me about my Phone and Password, though it does ask me the phone but after entering my phone, I got an error self.UserModel._default_manager.db_manager(database).get_by_natural_key( AttributeError: 'Manager' object has no attribute 'get_by_natural_key' from django.contrib.auth.base_user import BaseUserManager class UserManager(BaseUserManager): def create_user(self, phone, password=None, **extra_fields): if not phone: raise ValueError("Phone Number is required") extra_fields['email'] = self.normalize_email(extra_fields['email']) user = self.model(phone=phone, **extra_fields) user.set_password(password) user.save(using=self.db) return user def create_superuser(self, phone, password=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) return self.create_user(phone, password, **extra_fields) -
does pagination removed from coinbase wallet library in python?
I am using the Coinbase API to retrieve a list of accounts. According to the official documentation, I expected the response to include a pagination object alongside the data array. This pagination object is crucial for handling data systematically, especially when dealing with large datasets that require efficient navigation through multiple pages. Issue Encountered: However, in my recent interactions with the API, the responses lack the pagination object, and instead, only the data array is returned. This deviation from the documented response structure is causing significant issues in data handling and application functionality. Examples of Responses: Response from my Application: { "data": [ { "allow_deposits": true, "allow_withdrawals": true, "balance": { "amount": "0.00000000", "currency": "BIGTIME" }, "created_at": "2023-11-22T17:19:42Z", ... }, ... ] } Expected Response (Based on Documentation): { "pagination": { "ending_before": null, "starting_after": null, "limit": 25, "order": "desc", "previous_uri": null, "next_uri": null }, "data": [ { "id": "58542935-67b5-56e1-a3f9-42686e07fa40", "name": "My Vault", ... }, ... ] } Does any one have this issue or their is some issue with the old implementation? Solving the problem of the pagination. -
How to make an a formula field in django models?
I have got a model like: class Role(models.Model): name = models.CharField() salary_formula = models.CharField(max_length=255, blank=False, null=False) How can i make a field salary_formula to count values? -
Django Filtering Data Based on Relationship Absence or exclude problem
modes.py- from django.db import models from datetime import date class RocCompany(models.Model): company_name = models.TextField(db_column='CompanyName', blank=True, null=True) # Field name made lowercase. company_cin = models.CharField(db_column='CIN', primary_key=True, max_length=50) # Field name made lowercase. incorporation = models.DateField(db_column='Incorporation', blank=True, null=True) # Field name made lowercase. state = models.CharField(max_length=50,db_column='State', blank=True, null=True) # Field name made lowercase. city = models.CharField(max_length=50,db_column='City', blank=True, null=True) # Field name made lowercase. industry = models.CharField(max_length=50,db_column='Industry', blank=True, null=True) # Field name made lowercase. sector = models.CharField(max_length=50,db_column='Sector', blank=True, null=True) # Field name made lowercase. class Meta: managed = False db_table = 'cin_format' ordering=('company_name','state','city','sector',)# needed for sorting def __str__(self): return self.company_cin #bcz nedded for filter filer cin mixup from django.db import models EXISTING_OLD_CHOICES = [ ('existing', 'Existing'), ('old', 'Old'), ] class RocCharge(models.Model): id = models.IntegerField(primary_key=True) srn_no = models.CharField(max_length=50,blank=True, null=True) charge_id = models.IntegerField(blank=True, null=True) charge_holder_name = models.CharField(max_length=50,blank=True, null=True,db_index=True) date_of_creation = models.DateField(default=date.today) date_of_modification = models.DateField(blank=True, null=True) date_of_satisfaction = models.DateField(blank=True, null=True) amount = models.BigIntegerField(blank=True, null=True) address = models.TextField(blank=True, null=True) existing_old = models.CharField( max_length=8, choices=EXISTING_OLD_CHOICES, # Use the choices parameter ) cin = models.ForeignKey(RocCompany, on_delete=models.CASCADE, db_column='CIN', blank=True, null=True) # Field name made lowercase. class Meta: managed = False db_table = 'roc_web' ordering=('charge_holder_name','date_of_creation','amount',) def __str__(self): return self.charge_holder_name , my filters.py- from bootstrap_datepicker_plus.widgets import DateTimePickerInput import django_filters from .models import … -
Nginx cannot find protected media files. Django rest app
I want to reolve the issue is restrict an access to media files in DRF app on production for user that does not use my app. One of the solutions for this is redirect using **X-Accel-Redirect** (nginx) for that Here are some samples of my code. settings.py MEDIA_URL = '/api/media/' MEDIA_ROOT = BASE_DIR / 'media' url.py api = [ re_path('media/(?P<file_path>.*)$', MediaRetrieveAPIView.as_view(), name='media'), ] urlpatterns = [ path('api/', include(api)), path('admin/', admin.site.urls), ] views.py class MediaRetrieveAPIView(generics.RetrieveAPIView): def get(self, request, *args, **kwargs): try: file_path = request.query_params['file_path'] except BaseException: file_path = kwargs['file_path'] response = HttpResponse(status=status.HTTP_200_OK) del response['Content-Type'] response['Content-Disposition'] = f'attachment; filename={filename}' response['X-Accel-Redirect'] = f'protected/{file_path}' return response nginx config upstream api { server 172.17.0.1:8001; } upstream admin { server 172.17.0.1:8001; } upstream docs { server 172.17.0.1:8001; } upstream statics { server 172.17.0.1:8001; } upstream schema { server 172.17.0.1:8001; } upstream media { server 172.17.0.1:8001; } server { listen 8081; client_max_body_size 100M; location / { root /www/wwwroot/dev.{{mydomain}}.com; } location /api { proxy_pass http://api; proxy_set_header Host $http_host; } location /admin { proxy_pass http://admin; proxy_set_header Host $http_host; } location /docs { proxy_pass http://docs; proxy_set_header Host $http_host; } location /statics { proxy_pass http://statics; proxy_set_header Host $http_host; } location /schema { proxy_pass http://schema; proxy_set_header Host $http_host; } location /protected/ { … -
Django form validation with foreign keys from two different tables
I have a question with forms validation for Django that I suspect is trivial but I am not Getting what I am missing as I am diving in django without too much understanding of some fundamental aspects and a bit confused by the documentation or issue here. This is not my code but a simplified version of the core problem: So my model would be something like: class Parent(models.Model): class Meta: ordering = ('name',) name = models.TextField(max_length=255, primary_key=True, unique=True) clothing= models.ManyToManyField(Clothing, through='childs') class Clothing(models.Model): class Meta: ordering = ('name',) name = models.TextField(max_length=255, primary_key=True, unique=True) class Childs(models.Model): class Meta: ordering = ('amount',) parent = models.ForeignKey(Parent, db_column='name', on_delete=models.CASCADE) clothing = models.ForeignKey(Clothing, db_column='name', on_delete=models.CASCADE) amount = models.DecimalField(max_digits=5, decimal_places=0) class FamilyDressing(forms.ModelForm): class Meta: model = Childs fields = ('parent', 'clothing', 'amount') which hopefully is right. Lets imagine a way of uploading a csv file with a list of children, their associated parent and associated piece of cloth. To validate such form I thought I first can validate the Clothing model, that seems to work, then validate the childs model with the parent name, piece of cloth and amount but somehow I can only validate parent and amount together but not the three fields at … -
Django, MyPy: Incompatible types in assignment (UserManager)
I have following errors when I am running mypy checking: error: Cannot override class variable (previously declared on base class "User") with instance variable [misc] error: Incompatible types in assignment (expression has type "type[BuyerManager[Any]]", base class "User" defined the type as "UserManager[User]") [assignment] My code is following: class User(AbstractUser): ... class Buyer(User): objects = BuyerManager class BuyerManager(UserManager): def get_queryset(self) -> QuerySet: return super().get_queryset().filter(status="buyer") Can't find solution. So, any help or advice welcomed) -
AttributeError: 'ManyToOneRel' object has no attribute 'attname'
I changed a OnetoOnefield in a PostImage model to a ForeignKey and getting the said error. Here is what is changed : class PostImage(models.Model): # post = models.OneToOneField(Post, on_delete=models.CASCADE, related_name='image', null=True) post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='image', null=True) image = ProcessedImageField(verbose_name=_('image'), storage=post_image_storage, upload_to=upload_to_post_image_directory, width_field='width', height_field='height', blank=False, null=True, format='JPEG', options={'quality': 80}, The logs of docker-compose : my-api | Traceback (most recent call last): my-api | File "/usr/local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner my-api | response = get_response(request) my-api | File "/usr/local/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response my-api | response = wrapped_callback(request, *callback_args, **callback_kwargs) my-api | File "/usr/local/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view my-api | return view_func(*args, **kwargs) my-api | File "/usr/local/lib/python3.8/site-packages/django/views/generic/base.py", line 70, in view my-api | return self.dispatch(request, *args, **kwargs) my-api | File "/usr/local/lib/python3.8/site-packages/rest_framework/views.py", line 509, in dispatch my-api | response = self.handle_exception(exc) my-api | File "/usr/local/lib/python3.8/site-packages/rest_framework/views.py", line 469, in handle_exception my-api | self.raise_uncaught_exception(exc) my-api | File "/usr/local/lib/python3.8/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception my-api | raise exc my-api | File "/usr/local/lib/python3.8/site-packages/rest_framework/views.py", line 506, in dispatch my-api | response = handler(request, *args, **kwargs) my-api | File "/opt/my-api-core/my_posts/views/posts/views.py", line 55, in get my-api | return self.get_posts_for_authenticated_user(request) my-api | File "/opt/my-api-core/my_posts/views/posts/views.py", line 92, in get_posts_for_authenticated_user my-api | post_serializer_data = AuthenticatedUserPostSerializer(posts, many=True, context={"request": request}).data my-api | File "/usr/local/lib/python3.8/site-packages/rest_framework/serializers.py", line … -
Django puts https// in the beginning of url [closed]
In our project we use s3 storage. That's why i need to build link manually in admin panel. I implement it like this code: def video2(self): if self.video2: return settings.AWS_S3_CUSTOM_DOMAIN[8:] + self.video2.url return None But django puts https// not even https://. I use search to find out https// in project and it finds nothing. I made a conclusion that it came from django. What can I do with this? -
Django export data to file
I want to export my data of some models to csv/json/txt file. Is the 'dumpdata' function is the best way? What is the best option? I tried: Python3 manage.py dumpdata myapps > myapps.json Or copy from my DB tables Thanks a lot -
Login page not redirecting in Django
Building a Django project where in I want that the password is been set by the admin, anyone who wants to access the same needs to use that particular password only. to implement the same I made a custom User model and a custom authentication backend. But when putting in input in the login form the page isn't getting redirected. here is the backend.py file : from django.contrib.auth.backends import ModelBackend from django.contrib.auth import get_user_model from main.models import CustomUser class AdminSetPasswordBackend(ModelBackend): def authenticate(self, request, username=None, password=None, **kwargs): try: user = CustomUser.objects.get(username=username) if user.is_active and user.check_password(password) and user.admin_set_password: return user except CustomUser.DoesNotExist: return None Here is the CustomUser Model in my models.py: class CustomUser(AbstractUser): admin_set_password = models.BooleanField(default=True) name = models.CharField(max_length=255) adharcardNo = models.CharField(max_length=16) # Add any other fields you need # Provide unique related_name for groups and user_permissions groups = models.ManyToManyField( 'auth.Group', related_name='custom_user_groups', blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', verbose_name='groups', ) user_permissions = models.ManyToManyField( 'auth.Permission', related_name='custom_user_permissions', blank=True, help_text='Specific permissions for this user.', verbose_name='user permissions', ) def __str__(self): return self.username here is the views.py file handling the request : class CustomLoginView(LoginView): template_name ='main/login.html' # Update with the path to your … -
How to make the delete button delete the right post?
I have this delete button with a dialog on it but the button does not get the id of the post right and whatever i do it writes the title of the same post every time and I think it always starts to delete from the first post so I end up deleting them all and when I click to delete a post it gives this error what should I do? If I need to post another part of code please let me know Thanks in advance ValueError at /posts/delete/105 The view posts.views.delete didn't return an HttpResponse object. It returned None instead. views.py from django.forms.models import BaseModelForm from django.http import HttpResponse from django.shortcuts import render, redirect, get_object_or_404 from django.contrib.auth.decorators import login_required from .forms import PostForm from .models import post from django.contrib import messages from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from users.models import Profile from django.views.generic import UpdateView from django.views import View from django.contrib.auth import get_user_model def detail(request, id): poost = get_object_or_404(post, pk=id) return render(request, "posts/detail.html", {"post": poost}) @login_required() def delete(request, id): poost = get_object_or_404(post, pk=id) if request.user == post.author: poost.delete() messages.error(request, f'Post deleted!') return redirect("/") @login_required() def new(request): if request.method == "POST": form = PostForm(request.POST) if form.is_valid(): form.instance.author = request.user form.save() … -
Unable to replicate existing Svelte/Django SPA approach in migration to SvelteKit
I have a Svelte 3 SPA that sits in front of a Django API. Currently, it compiles the prod release into the static folder used by Django. The SPA is served by a Django template to let it take care of auth. Svelte is configured to use consistent names for the compiled artefacts: The Django template to show the svelte app is basically an empty page that links in the SPA: <link rel='stylesheet' href={% static 'svelte/build/bundle.css' %}> <link rel='stylesheet' href={% static 'svelte/build/vendor.css' %}> <script defer src={% static 'svelte/build/bundle.js' %}></script> Django is setup to handle a couple of URL paths and then pass anything else through to the svelte template. Because it's a Django template, if the user hasn't auth'd when viewing it it takes them through the login process first, then back to the app. This has been working great and has been easy to deploy & explain to others. I'm currently migrating to SvelteKit 2 before a handover (mostly due to the prominence of SK docs over vanilla svelte). I'm following the now recommended approach for SPAs and using adapter-static to produce the build artefacts. With the way the app currently authenticates, I can't fall through at the web … -
Return multiple values in Django Class-based View
I am working on a project for a Django course I am taking but currently struggling a bit with views. In the project I created a View using ListView to display a list of products in my template. By using query_set I am able to get all the objects and return them to display all the products and their attributes in the template by using a for loop. In the same query_set, I tried returning another variable that contains the total items in stock to display this data in the template as well, however, as soon as I add this variable to the return the template no longer receives the returned values. This is the code I tried to return both values: class ShopListing(ListView): template_name = "webshop/shop_listing.html" context_object_name = 'shop_listing' def get_queryset(self): #Get all products products = Product.objects.all() total_stock = products.aggregate(sum=Sum('stock'))['sum'] return products, total_stock In my template I added the value 'total_stock' as shown below but I get nothing, and even the values from 'products' stop working: <strong>{{total_stock}}</strong> items are currently available</p> If I remove 'total_stock' from the return everything goes back to normal. If I print "total_stock" I can see the right value in the logs, but this cannot … -
Using JWT from frontend MSAL to authenticate backend REST API (Django REST Framework, react.js)
My scenario is I have an existing frontend react project that authenticates with SSO using MSAL. This results in the frontend having a JWT token in it's session storage that contains the relevant signed information about the user. I need to create a backend REST API in Django that will be the backend to the react project. My question is: can I send the JWT token to the backend, check for a valid signature, and if it is valid use it to create a user in the database associated with that email? I'm not the most familiar with authentication methods and I'm struggling to find documentation that matches my use case. Although in my particular use case I'm implementing this in Django and React, my question is more on is this authentication method okay from a theoretical perspective? Any advice is appreciated. -
Django instance variables in custom form fields
I run into a weird behaviour (in my opinion) when using a custom forms.ChoiceField. Here is my code: class ChoiceField2(forms.ChoiceField): def __init__(self, *, choices=(), **kwargs): super().__init__(choices=choices, **kwargs) # Init in constructor #self._mydata = [] def add(self, val): # Init outside constructor #if not hasattr(self, "_mydata"): # self._mydata = [] self._mydata.append(val) pprint(self._mydata) class Create2(FormView): form_class = f.MyForm # this is the form that uses ChoiceField2 def get_form(self, form_class=None): form = self.form_class() import datetime form.fields["my_field"].add(datetime.datetime.now()) return form Now, when I initiate self._mydata in the constructor, at every page refresh data is constantly being added to self._mydata - it behaves basically as if it is a static variable. If I initiate self._mydata outside the constructor (in the add method for example) my datetime object is added only once - that is self._mydata contains only one object - as expected in my opinion since the whole thing is created at each refresh! Has anyone run into this before? What is the use case here? Should we not use __ init __ to create instance variables? -
Django upload_image function not showing properly at the api view. I can go into the Post for the view but the upload option is not there
function at models.py def grounds_driveway_image_file_path(instance, filename): """Generate file path for new grounds driveway image.""" ext = os.path.splittext(filename)[1] filename = f'{uuid.uuid4()}{ext}' return os.path.join('uploads', 'grounds-driveway', filename) def grounds_sidewalk_image_file_path(instance, filename): """Generate file path for new grounds sidewalk image.""" ext = os.path.splittext(filename)[1] filename = f'{uuid.uuid4()}{ext}' return os.path.join('uploads', 'grounds-sidewalk', filename) model at models.py class GroundsSideWalksPhotos(models.Model): """Grounds Sidewalks Model""" report_uuid = models.ForeignKey( ReportDetails, on_delete=models.CASCADE, null=True ) grounds_sidewalk_photos = models.ImageField( null=True, upload_to=grounds_sidewalk_image_file_path ) class GroundsDrivewayPhotos(models.Model): report_uuid = models.ForeignKey( ReportDetails, on_delete=models.CASCADE, null=True ) grounds_driveway_photos = models.ImageField( null=True, upload_to=grounds_driveway_image_file_path ) views.py def get_serializer_class(self): """Return the serializer class for request.""" if self.action == 'list': return serializers.InspectionReportSerializer elif self.action == 'grounds-driveway': return serializers.GroundsDrivewayPhotosSerializer elif self.action == 'grounds-sidewalk': return serializers.GroundsSidewalkPhotosSerializer return self.serializer_class @action(methods=['POST', 'GET'], detail=True, url_path='grounds-driveway') def upload_photo(self, request, pk=None): """Upload an image to report.""" report = self.get_object() serializer = self.get_serializer(report, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) @action(methods=['POST', 'GET'], detail=True, url_path='grounds-sidewalk') def upload_photo(self, request, pk=None): """Upload an image to report.""" report = self.get_object() serializer = self.get_serializer(report, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) serializers.py class GroundsDrivewayPhotosSerializer(serializers.ModelSerializer): """Serializer for uploading photos to grounds.""" class Meta: model = GroundsDrivewayPhotos fields = ['report_uuid', 'grounds_driveway_photos'] read_only_fields = ['report_uuid'] class GroundsSidewalkPhotosSerializer(serializers.ModelSerializer): """Serializer for uploading photos to grounds.""" class Meta: model … -
Issue with Updating Attendance Records in Django using MySQL
I am encountering an issue with updating attendance records in my Django application using MySQL. I have a handle_attendance_record function intended to update or create an AttendanceRecord for an employee based on check-in and check-out logs. However, the records are not updating as expected. Here is the code for my function: from datetime import datetime class AttendanceRecord(models.Model): # Model definition ... def handle_attendance_record(self, log_data, log_time): user_id = str(log_data["UserId"]).zfill(4) try: employee = Employee.objects.get(employee_matricule=user_id) except Employee.DoesNotExist: print(f"Employee not found for user_id {user_id}") return log_date = log_time.date() record, created = AttendanceRecord.objects.get_or_create( employee=employee, date=log_date, defaults={'check_in': None, 'check_out': None}) if log_data["Type"] == "CheckOut" and record.check_out is None: record.check_out = log_time.time() elif log_data["Type"] == "CheckIn" and record.check_in is None: record.check_in = log_time.time() if record.check_in and record.check_out: record.working_hours = datetime.combine(log_date, record.check_out) - datetime.combine(log_date, record.check_in) record.save() from datetime import datetime class AttendanceRecord(models.Model): # Model definition ... def handle_attendance_record(self, log_data, log_time): user_id = str(log_data["UserId"]).zfill(4) try: employee = Employee.objects.get(employee_matricule=user_id) except Employee.DoesNotExist: print(f"Employee not found for user_id {user_id}") return log_date = log_time.date() record, created = AttendanceRecord.objects.get_or_create( employee=employee, date=log_date, defaults={'check_in': None, 'check_out': None}) if log_data["Type"] == "CheckOut" and record.check_out is None: record.check_out = log_time.time() elif log_data["Type"] == "CheckIn" and record.check_in is None: record.check_in = log_time.time() if record.check_in and record.check_out: record.working_hours = datetime.combine(log_date, … -
hx-swap-oob creates duplicate dom element?
I have this workflow: new record is being inserted in database using HTMX, the row inserted should show up in table (the whole table gets reRendered) simuoultaneously with previous step, certain number should show up in a paragraph element (paragraph gets reRendered). I've tried to accomplish this using hx-swap-oob="true" argument on a paragraph element but the problem is that DOM element (paragraph) is being duplicated for some reason. Can someone tell me why is this happening and how to solve this? Template.html <table class="ui celled table"> <thead> <tr> <th>Col 1</th> <th>Col 2</th> <th>Col 3</th> </tr> </thead> <tbody hx-post="{% url 'books' book.id %}" hx-trigger="addBook from:body" hx-vals='{"action": "show_editions"}' id="book_list"> {% include "selling-books.html" %} </tbody> </table> ... ... # some other DOM elements ... <p id="book_number">{{ book.number }}</p> Selling-books.html {% for edition in editions %} <tr> <td>{{ edition.in }} pieces</td> <td>{{ edition.out }} pieces</td> <td>{{ edition.price }} USD</td> </tr> {% endfor %} <p hx-swap-oob="true" id="book_number">{{ book.number }}</p> Views.py def book_status(request, template_name = 'book.html', id=""): book = Book.objects.get(id=id) editions = Edition.objects.filter(book_id=id) if request.method == "POST": action = request.POST.get('action') if action == 'addBook': addEdition_form = AddBookForm(request.POST or None) if addEdition_form.is_valid(): ... some logic ... return HttpResponse(status=204, headers={'HX-Trigger': 'addBook'}) if action == 'show_editions': for edition in … -
History for ManyToMany tables not being tracked with django-simple-history
I have this model: class UserInfo(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) institution = models.ManyToManyField(Institution) history = HistoricalRecords() Django created this table to manage this: mysql> desc userinfo_institution; +----------------+------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +----------------+------+------+-----+---------+----------------+ | id | int | NO | PRI | NULL | auto_increment | | userinfo_id | int | NO | MUL | NULL | | | institution_id | int | NO | MUL | NULL | | +----------------+------+------+-----+---------+----------------+ I created this model to represent that table: class UserInfoInstitution(models.Model): userinfo = models.ForeignKey(UserInfo, models.DO_NOTHING) institution = models.ForeignKey(Institution, models.DO_NOTHING) history = HistoricalRecords() class Meta: managed = False db_table = 'userinfo_institution' unique_together = ('userinfo', 'institution') When userinfo_institution is updated I would expect historicaluserinfoinstitution to track that update, but it does not. I have seen some posts here and also on the project's github page that talk about support for this being added. Is there something I am missing to get this working? -
Can't retrieve token from angular side, but it works fine in postman - JWT not shown in 'application' browser tab - Django - Angular
I trying to make login page and home page with django and angular, it logged in well, but once i try to retrieve the logged in user from angular it shows me 403 (Forbidden) but it works fine in postman, it'll retrieve the logged in information I tried this below code, i expected to show me the logged in user, but it shows 403 error message. and it doesnt show the jwt on my web browser developer tool Application, it looks like it has not been stored. it logged in successfully from frontend and will show the token(JWT) with console.log , but when i try to use the jwt for another page it shows me 403 error. my server side - django: this what im trying to retrieve, but shows the error class UserView(APIView): def get(self,request): token = request.COOKIES.get('jwt') print(token) # this will retrieve null when i send request from angular, but retrieve the token when i send the request with postman if not token: raise AuthenticationFailed('UnAuthorized user!') try: payload = jwt.decode(token,'secret',algorithms=['HS256']) except jwt.ExpiredSignatureError: raise AuthenticationFailed('Expired Session') user = User.objects.get(id=payload['id']) serializer = UserSerializer(user) return Response(serializer.data) my urls.py urlpatterns = [ path('api/login/',LoginView.as_view(),name='login'), path('api/users/',UserView.as_view(),name='user'), ] and my settings.py INSTALLED_APPS = [ 'django.contrib.admin', …