Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to configure VSCode + Django + WindiCSS
I installed the 'WindiCSS IntelliSense' extension for VSCode and I don't know what to do next. To make it work I open each .html file separately, run the 'Compile CSS [Interpretation mode]' command, rename the output file to match with the .html file I compiled it for and then manually move it to my static directory + the extension doesn't read the windi.config.js file. How to make it compile a single .css file for all .html files in the template directory and automatically move it to the static directory? -
Python: Return pre stored json file in response in Django Rest Framework
I want to write an API, which on a GET call , returns pre-stored simple json file. This file should be pre-stored in file system. How to do that? register is app name. static is folder inside register. There I keep stations.json file. register/static/stations.json. Content of this "stations.json" file should be returned in response. settings.py: STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'register/static/') ] STATIC_URL = 'static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') views.py: from django.shortcuts import render # Create your views here. from django.contrib.auth.models import User from .serializers import RegisterSerializer from rest_framework import generics from django.http import JsonResponse from django.conf import settings import json class RegisterView(generics.CreateAPIView): queryset = User.objects.all() serializer_class = RegisterSerializer def get_stations(request): with open(settings.STATICFILES_DIRS[0] + '/stations.json', 'r') as f: data = json.load(f) return JsonResponse(data) urls.py: from django.urls import path from register.views import RegisterView from . import views urlpatterns = [ path('register/', RegisterView.as_view(), name='auth_register'), path('stations/', views.get_stations, name='get_stations'), ] setup/urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('api/', include('register.urls')), ] When I hit GET request from Postman: "http://127.0.0.1:8000/api/stations/", I get error: 500 Internal server error. TypeError at /api/stations/ -
Django: How to calculate the uptime and downtime of a shop in the last hour, day, and week based on its business hours and status updates?
I have a Shop model that represents a retail store. Each store has ShopHour objects that define its business hours for each day of the week. The ShopHour model has the following fields: class ShopHour(models.Model): DAY_CHOICES = [ (0, 'Monday'), (1, 'Tuesday'), (2, 'Wednesday'), (3, 'Thursday'), (4, 'Friday'), (5, 'Saturday'), (6, 'Sunday'), ] store = models.ForeignKey( Shop, on_delete=models.CASCADE, related_name='business_hours' ) day_of_week = models.IntegerField(choices=DAY_CHOICES) start_time_local = models.TimeField() end_time_local = models.TimeField() I also have a Status model that records the status of each shop at a given time. The Status model has the following fields: class Status(models.Model): STATUS_CHOICES = [ ('active', 'Active'), ('inactive', 'Inactive'), ] store = models.ForeignKey( Shop, on_delete=models.CASCADE, related_name='updates' ) timestamp_utc = models.DateTimeField() status = models.CharField(max_length=10, choices=STATUS_CHOICES) I would like to create a hourly report Report for each Shop that shows its uptime and downtime in the last hour, day, and week, based on its business hours and status updates. Additionally if a shop has missing business hours, it's assumed to be open for 24*7. Specifically, I would like to know: How much time the shop was active and inactive in the last hour, day, and week How can I calculate this information efficiently and accurately? I would appreciate any … -
A user mapped to verifyPhone and VerifyEmail via OneToOneField using fastapi tortoise-orm. but if I run the server. It'll pop error show in the pix
main fastapi The error it displays I tried to Map User to its EmailVerify and PhoneVerify using OneToOneField as shown in here and also this is the modelenter image description here -
Clarification Regarding Pip Package Sub Dependencies Getting Upgraded
I have a doubt regarding pip installation. Suppose i have a requirements.txt file in python project as below Django==4.1.7 While downloading Django it also downloads sub dependencies. └─$ pip show Django Name: Django Version: 4.1.7 Summary: A high-level Python web framework that encourages rapid development and clean, pragmatic design. Home-page: https://www.djangoproject.com/ Author: Django Software Foundation Author-email: foundation@djangoproject.com License: BSD-3-Clause Location: /home/sunil/Desktop/pypro/venv/lib/python3.10/site-packages Requires: asgiref, sqlparse Required-by: From the above output we can notice that asgiref, sqlparse sub dependencies also got installed. Below is the output of pip freeze └─$ pip freeze asgiref==3.6.0 Django==4.1.7 sqlparse==0.4.3 since asgiref, sqlparse aren't pinned in requirements.txt, In future if i reinstall these packages from above mentioned requirements.txt is it possible that asgiref, sqlparse get upgraded to different versions ?? Or these sub dependency packages has their versions pinned with Django itself ?? Any docs or pointers could be helpful :) -
How to sort variables in order from highest to lowest in Python Django
So I do have variable that I need to sort and I have some difficulties to solve that: Problem is that I have {{new.likes.count}} that gave me just: 1 4 5 8 .... views.py from "post app" def news(request): queryset = News.objects.order_by('-created_date') tags = News_Tag.objects.order_by('-created_date') page = request.GET.get('page', 1) paginator = Paginator(queryset, 9) try: news = paginator.page(page) except EmptyPage: news = paginator.page(1) except PageNotAnInteger: news = paginator.page(1) return redirect('news') context = { "news": news, "tags": tags, "paginator": paginator } return render(request, 'news.html', context) def like_news(request, pk): context = {} new = get_object_or_404(News, pk=pk) if request.user in new.likes.all(): new.likes.remove(request.user) context['liked'] = False context['like_count'] = new.likes.all().count() else: new.likes.add(request.user) context['liked'] = True context['like_count'] = new.likes.all().count() return JsonResponse(context, safe=False) models.py class News(models.Model): user = models.ForeignKey( User, related_name='user_news', on_delete=models.CASCADE ) category = models.ForeignKey( News_Category, related_name='category_news', on_delete=models.CASCADE ) tags = models.ManyToManyField( News_Tag, related_name='tag_news', blank=True ) likes = models.ManyToManyField( User, related_name='news_user_likes', blank=True ) title = models.CharField( max_length=250 ) slug = models.SlugField(null=True, blank=True) banner = models.ImageField(upload_to='news_banners') description = RichTextField() created_date = models.DateField(auto_now_add=True) def __str__(self) -> str: return self.title def save(self, *args, **kwargs): updating = self.pk is not None if updating: self.slug = generate_unique_slug(self, self.title, update=True) super().save(*args, **kwargs) else: self.slug = generate_unique_slug(self, self.title) super().save(*args, **kwargs) {{new.likes.count}} variable has 4 … -
Django signal was not triggered after Apscheduler job updates Model record
I have an Apscheduler job that updates the active field in my subscription model and sets it to False. I created a post_save signal that should be triggered when the subscription model is updated, but it doesn't work. Here's my code. --job.py-- from django.conf import settings from subscription.models import AccountSubscription from django.utils import timezone def schedule_api(): try: data = {'is_active':False} AccountSubscription.objects.filter(expiry_date__lte=timezone.now(), is_active=True).update(**data) except Exception: pass -- signals.py-- @receiver(post_save, sender=AccountSubscription) def post_save_user_subscription_expired(sender, instance, created, **kwargs): """Notifies users of subscription expiration.""" try: if not created: if not instance.is_active: print("Notified users") except Exception as ex: print(ex) # context = { # 'status': 'error', # 'message': 'A subscription expiration notification error has occurred.' # } # raise exceptions.ParseError(context) Please is there something that I am doing wrongly? -
I can't display my data on the client side of the screen
I'm working on a simple Full CRUD app using react and Django. I'm having a problem seeing my data on the client side. const URL = 'http://localhost:8000/blog/'; const Main = () => { const [blogs, setBlogs] = useState(null); // Index const getBlogs = async () => { const data = await fetch(URL).then((res) => res.json()); setBlogs(data); }; // Create const createBlogs = async (blog) => { await fetch(URL, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(blog) }); getBlogs(); } // Update const updateBlogs = async (blog, id) => { await fetch(URL + id , { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(blog) }); getBlogs(); } // Delete const deleteBlogs = async (id) => { await fetch(URL + id , { method: 'DELETE' }); getBlogs(); } useEffect(() => { getBlogs(); }, []); return ( <main> <Routes> <Route path='/' element={<Index blogs={blogs} createBlogs={createBlogs} />} /> <Route path='/blog/:id' element={<Show blogs={blogs} />} updateBlogs={updateBlogs} deleteBlogs={deleteBlogs} /> </Routes> </main> ); } export default Main; I checked everthing is working on postman and it is working. I can create,edit,update and delete on postman. -
Django authentication on home page
How can i compare the name of the logged in user on a django home page template with any other string this is what i tried -
Error in running Plotly Dash Plot in Django with UWSGI and NGINX
I have a Django project with UWSGI and NGINX. There are multiple pages and the page with Interactive Plotly Dash Plot cannot work. For the other pages, they work fine. When I go to some of the Interactive Plotly Dash Plot, some of them can only loads the frame only. enter image description here Some of them simply get a Server Error(500) I check the log and get the following: Traceback (most recent call last): File "/opt/python-virtual-env/web_project/lib64/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/opt/python-virtual-env/web_project/lib64/python3.8/site-packages/django/utils/deprecation.py", line 119, in __call__ response = self.process_response(request, response) File "/opt/python-virtual-env/web_project/lib64/python3.8/site-packages/django/contrib/sessions/middleware.py", line 63, in process_response raise SessionInterrupted( django.contrib.sessions.exceptions.SessionInterrupted: The request's session was deleted before the request completed. The user may have logged out in a concurrent request, for example. The request's session was deleted before the request completed. The user may have logged out in a concurrent request, for example.: /django_plotly_dash/app/vis1/_dash-update-component Traceback (most recent call last): File "/opt/python-virtual-env/web_project/lib64/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/opt/python-virtual-env/web_project/lib64/python3.8/site-packages/django/db/backends/sqlite3/base.py", line 423, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: attempt to write a readonly database The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/opt/python-virtual-env/web_project/lib64/python3.8/site-packages/django/contrib/sessions/backends/db.py", line 87, in save obj.save(force_insert=must_create, … -
How to get null for rows where data doesn't exist in Postgres while performing joins
I have 2 tables. Items and Rates. All the items are stored in items table and rates are stored daily in rates table. Items and rates are linked using FK on rates table. When the rates are stored if it is not preset then row is not stored. Like for item 5 if no rate is present on 1st jan, there wont be a record for item 5. When getting the data I want item 5 rate as null (as shown in example pic). How can I proceed? I tried left joins, left Join is not working, sometimes depending on the data I get the date as null, sometimes everything except item pk is null. I dont know how to proceed furthur with this. -
Error while passing Variable from View to Form in Django
I try to send a variable form View to Form in Django. I find a solution and it's working but the problem is that I have to call the fonction form = DonneeForm(variable=variable) but it seems to just send me the entire HTML code. So I would like to find a way for the DonneeForm() to behave as DonneeForm which work but doesn't allow me to send a variable. Thanks Form.py class DonneeForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.boitier = kwargs.pop("boitier", 1) # client is the parameter passed from views.py super().__init__(*args, **kwargs) boitier = get_object_or_404(Boitier, pk=int(self.boitier)) self.fields['connexion_donnee'].queryset = boitier.donnee class Meta: model = Donnee fields = ['utilise', 'connexion_donnee', 'nom', 'type_donnee', 'valeur_min', 'valeur_max', 'tolerance', 'afficher_valeur', 'inverse'] labels = { } widgets = { 'type_donnee': forms.Select(attrs={"readonly": "True"}) } View.py type_capteur = get_object_or_404(TypeCapteur, pk=pk) capteur = get_object_or_404(Capteur, pk=article) type_capteur_donnees = type_capteur.donnee.all().count() print(DonneeForm(boitier=boitier.pk)) form = DonneeForm(boitier=boitier.pk) donnee_form_set = formset_factory(form, extra=type_capteur_donnees, max_num=type_capteur_donnees, absolute_max=type_capteur_donnees) formset_donnee = donnee_form_set if request.method == 'POST': formset = donnee_form_set(request.POST, request.FILES) if formset.is_valid(): for form in formset: if form.cleaned_data: donnee = form.save(commit=False) donnee.capteur = capteur donnee.save() capteur.save() return redirect("smart_workshop_app:configuration_capteurs") else: initial = [] for type_donnee in type_capteur.donnee.all(): initial.append({'type_donnee': type_donnee, 'nom': type_donnee.nom}) formset = formset_donnee(initial=initial) print(formset_donnee) context = {"formset": formset, "instance_id": pk, "instance_article": article} … -
Django : Fix admin link to website ressources when apps are in subfolders
Here is the architecture of my django project : project/ apps/ app1/ app2/ ... core/ management/ settings.py ... static/ templates/ utils/ It is not a conventional tree, but it works pretty well. Problem I have is with reverse admin urls. Django admin provide direct links to resources which are broken, giving me the following error : Reverse for 'pattern_name' not found. 'pattern_name' is not a valid view function or pattern name. pattern_name does exists indeed, but is behind app app1, and should be called app1:pattern_name. I don't find any documentation about this. Is there a way to fix it ? -
Django auth crash
Need help from someone experienced with Django: I'm using Django Test Client to create a request to test instance of API running in docker. Running through custom auth backend successfully, the authenticate method returns a user generated from get_user_model() and then this crash happens with following stack trace: Traceback (most recent call last): File "/my/repo/api/v1/tests/system/test_auth.py", line 29, in test_auth response = self.client.post( File "/usr/local/lib/python3.8/site-packages/django/test/client.py", line 852, in post response = super().post( File "/usr/local/lib/python3.8/site-packages/django/test/client.py", line 441, in post return self.generic( File "/usr/local/lib/python3.8/site-packages/django/test/client.py", line 541, in generic return self.request(**r) File "/usr/local/lib/python3.8/site-packages/django/test/client.py", line 810, in request self.check_exception(response) File "/usr/local/lib/python3.8/site-packages/django/test/client.py", line 663, in check_exception raise exc_value File "/usr/local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/usr/local/lib/python3.8/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/usr/local/lib/python3.8/site-packages/django/views/generic/base.py", line 103, in view return self.dispatch(request, *args, **kwargs) File "/usr/local/lib/python3.8/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/usr/local/lib/python3.8/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/usr/local/lib/python3.8/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/usr/local/lib/python3.8/site-packages/rest_framework/views.py", line 497, in dispatch self.initial(request, *args, **kwargs) File "/usr/local/lib/python3.8/site-packages/rest_framework/views.py", line 414, in initial self.perform_authentication(request) File "/usr/local/lib/python3.8/site-packages/rest_framework/views.py", line 324, in perform_authentication request.user File "/usr/local/lib/python3.8/site-packages/rest_framework/request.py", line 227, in user self._authenticate() File "/usr/local/lib/python3.8/site-packages/rest_framework/request.py", line 387, in … -
How to implement auto-refresh jwt token in server side (DRF)?
I want to refresh my jwt access token automatically when the access token expires. (only in server-side, I'm using Django) Also, I am storing tokens in HttpOnly Cookie. This is my DEFAULT_AUTHENTICATION_CLASSES in my settings.py. 'DEFAULT_AUTHENTICATION_CLASSES': ( 'account.authenticate.CustomAuthentication', 'rest_framework_simplejwt.authentication.JWTAuthentication', ), I checked that authentication works everytime I get URL. So I tried to add code about Refreshing token in my custom Authentication class which overrides JWTAuthentication. ( JWTAuthentication document ) authenticate.py class CustomAuthentication(JWTAuthentication): def authenticate(self, request): header = self.get_header(request) if header is None: raw_token = request.COOKIES.get(settings.SIMPLE_JWT['AUTH_COOKIE']) or None else: raw_token = self.get_raw_token(header) # if access_token expires if raw_token is None: refresh_token = request.COOKIES.get(settings.SIMPLE_JWT['AUTH_COOKIE_REFRESH']) or None serializer = TokenRefreshSerializer(data={'refresh': refresh_token}) # if refresh_token is valid if serializer.is_valid(): raw_token = serializer.validated_data['access'] # set cookie about access_token response = HttpResponse() response.set_cookie( key=settings.SIMPLE_JWT['AUTH_COOKIE'], value=raw_token, max_age=3600, # 1 hour secure=settings.SIMPLE_JWT['AUTH_COOKIE_SECURE'], httponly=settings.SIMPLE_JWT['AUTH_COOKIE_HTTP_ONLY'], samesite=settings.SIMPLE_JWT['AUTH_COOKIE_SAMESITE'] ) validated_token = self.get_validated_token(raw_token) enforce_csrf(request) return self.get_user(validated_token), validated_token And these are the problems. It can't return response. So, the cookie(access_token) can't be set in the request.header. Explanation about authenticate in simplejwt-document authenticate(request) Authenticate the request and return a two-tuple of (user, token). The Cookie (access_token) is not in the request.header. So it always generate new access_token. Cookie's max age doesn't work after access_token … -
django - ssl.SSLError: [SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:997)
I'm trying to send an email in django, but I can't. I keep getting an SSLError (With the code below) or I get timed out (When I use port 465) EMAIL_BACKEND = 'django_smtp_ssl.SSLEmailBackend' EMAIL_HOST = 'smtp.office365.com' EMAIL_PORT = 587 EMAIL_HOST_USER = config['EMAIL'] EMAIL_HOST_PASSWORD = config['PASSWORD'] DEFAULT_FROM_EMAIL = config['EMAIL'] EMAIL_USE_SSL = False EMAIL_USE_TLS = False EMAIL_USE_STARTTLS = True How do I fix this? Thanks :) -
JSON string passed from frontend with AJAX POST to Django view results in strange characters added
I am trying to pass a GeoJson with AJAX call to backend. I printed to console before sending the whole string and no error was there. Printing in the view the request.POST shown this error. The error occurred on the 'streetWeb' variable. This variale comes from a textfile. Its content comes from a GeoJson stringified. The call $.ajax({ type: 'POST', url: $('#confImp').data('url'), contentType: "application/x-www-form-urlencoded; charset=utf-8", data: { "csrfmiddlewaretoken": csrftoken, 'streetWeb': toExpwe, 'int_points': toExpip}, success: function(res){ ......... } }) This error occurs a couple of times always identical. The following image shows the error I got. -
Saving data has no effect but data is there and request is sent
I have this product model and I am trying to update it and I can see all the data from the form sent to the backend and in the backend I can see all the data coming from the front end. When I save nothing happens and the request is sent and the response is the object but none of the fields I updated is correct. Nothing changed and the values remain the same. Here is the Product model: class Product(models.Model): title = models.CharField(max_length=100) category = models.ForeignKey(Category, on_delete=models.CASCADE, default=None, related_name="products") body = models.TextField(max_length=5000, null=True, blank=True) image = models.FileField(upload_to=image_directory_path, default='products/default.png', null=True, blank=True) price = models.DecimalField(max_digits=20, decimal_places=2) length = models.DecimalField(max_digits=20, decimal_places=2, blank=True, null=True) width = models.DecimalField(max_digits=20, decimal_places=2, blank=True, null=True) height = models.DecimalField(max_digits=20, decimal_places=2, blank=True, null=True) weight = models.DecimalField(max_digits=20, decimal_places=2, blank=True, null=True) volume = models.DecimalField(max_digits=20, decimal_places=2, blank=True, null=True) sku = models.CharField(max_length=20, null=True, blank=True) user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="products") created_at = models.DateTimeField(auto_now_add=True, verbose_name="created at") updated_at = models.DateTimeField(auto_now=True, verbose_name="updated at") class Meta: verbose_name = "product" verbose_name_plural = "products" db_table = "products" ordering = ["title"] def __str__(self): return self.title and here is the view I use for updating: class UpdateProductView(generics.UpdateAPIView): permission_classes = [IsAuthenticated] serializer_class = UpdateProductSerializer def get_queryset(self): id = self.kwargs["pk"] return Product.objects.all().filter(id=id) and the serializer … -
How to send DELETE method without PK in tests? Django Rest Framework
My DELETE method have a format like: DELETE /albums and IDs for deletion are passed in the body of the request. ids: [1, 2, 3...] My urls: router = SimpleRouter(trailing_slash=False) router.register(r'albums', AlbumViewSet, basename='albums') I can easily send this request from the Postman and it works correctly. But I can't replicate it using tests url = reverse('albums-detail') This pattern wants pk for the request, but my request does not include it. How can i send the DELETE request from the tests without PK? -
How to check User status is available or not in django orm?
How to check user status available or not and between start date and end date if same user status canceled and another is approved create timesheet status rejected and another is canceled create timesheet status canceled and another is canceled create timesheet IF User is status is pedning Dont create Timesheet Below is my code def submit_attendance(request, approval_status=None): if request.method == "POST": month = request.POST.get("month") year = request.POST.get("year") now = datetime.date.today() first, last = calendar.monthrange(int(year), int(month)) month_first_date = datetime.date(int(year), int(month), 1) month_last_day = datetime.date(int(year), int(month), last) two_digit_month = month if len(month) > 1 else "0" + month attendance_objects = Attendance.objects.filter(employee=request.user, date__month=month, date__year=year) leave_data = EmployeeLeaves.objects.filter(~Q(approval_status='Approved'),~Q(approval_status='Cancelled'),~Q(approval_status='Rejected'), from_date__gte=month_first_date, to_date__lte=month_last_day, employee=request.user).exists() leaves_data = EmployeeLeaves.objects.filter(~Q(approval_status='Pending'), from_date__gte=month_first_date, to_date__lte=month_last_day, employee=request.user).exists() print(leaves_data) for att in attendance_objects: try: print('test1') time_sheet_obj = Timesheet.objects.get(employee=request.user, date=att.date, status=1) time_sheet_obj.employee = User.objects.get(id=att.employee_id) time_sheet_obj.date = att.date time_sheet_obj.workingday_holiday = att.workingday_holiday time_sheet_obj.in_time = att.in_time time_sheet_obj.out_time = att.out_time time_sheet_obj.shift = att.shift time_sheet_obj.working_hours = att.working_hours time_sheet_obj.remarks = att.remarks time_sheet_obj.status = 1 time_sheet_obj.save() att.status = 1 att.save() except Timesheet.DoesNotExist: time_sheet_obj = Timesheet.objects.create( employee=request.user, date=att.date, workingday_holiday=att.workingday_holiday, in_time=att.in_time, out_time=att.out_time, shift=att.shift, working_hours=att.working_hours, remarks=att.remarks, status=1 ) print(time_sheet_obj,'comming') time_sheet_obj.save() att.status = 0 att.save() -
Django template6
TemplateDoesNotExist at / todo_list_templates/list.html Request Method: GET Request URL: http://127.0.0.1:8001/ Django Version: 4.1.2 Exception Type: TemplateDoesNotExist Exception Value: todo_list_templates/list.html Exception Location: C:\Users\sachi\AppData\Local\Programs\Python\Python310\lib\site-packages\django\template\loader.py, line 19, in get_template Raised during: todo_list.views.index Python Executable: C:\Users\sachi\AppData\Local\Programs\Python\Python310\python.exe Python Version: 3.10.5 Python Path: ['C:\Users\sachi\Todo_app', 'C:\Users\sachi\AppData\Local\Programs\Python\Python310\python310.zip', 'C:\Users\sachi\AppData\Local\Programs\Python\Python310\DLLs', 'C:\Users\sachi\AppData\Local\Programs\Python\Python310\lib', 'C:\Users\sachi\AppData\Local\Programs\Python\Python310', 'C:\Users\sachi\AppData\Local\Programs\Python\Python310\lib\site-packages'] Server time: Fri, 24 Feb 2023 07:00:37 +0000 Template-loader postmortem Django tried loading these templates, in this order: Using engine django: django.template.loaders.filesystem.Loader: C:\Users\sachi\Todo_app\Templates\todo_list_templates\list.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\sachi\AppData\Local\Programs\Python\Python310\lib\site-packages\django\contrib\admin\templates\todo_list_templates\list.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\sachi\AppData\Local\Programs\Python\Python310\lib\site-packages\django\contrib\auth\templates\todo_list_templates\list.html (Source does not exist) i tried everything but couldnot work for me -
AWS s3 bucket Referer returns 403
I want to allow access to specific folder in the bucket from the admin page only. The s3 bucket is accessed by a mobile app so CORS is useless. here's my statment { "Sid": "Stmt1234567890", "Effect": "Allow", "Principal": "*", "Action": "s3:GetObject", "Resource": "arn:aws:s3:::exampleBucket/id/*", "Condition": { "StringLike": { "aws:Referer": "https://example.me/*" } } } I still get 403 on loading the image on the site using tag I made sure the referer in the request using javascript document.referrer I've no idea what I'm doing wrong -
Battling to update an object in Django
I am trying to update a product and really having a hard time understanding the process of what happens when you use the UpdateAPIView from Django Rest Framework Here is the product model: class Product(models.Model): title = models.CharField(max_length=100) category = models.ForeignKey(Category, on_delete=models.CASCADE, default=None, related_name="products") brand = models.ForeignKey(Brand, on_delete=models.CASCADE, default=None, null=True, blank=True, related_name="products") body = models.TextField(max_length=5000, null=True, blank=True) image = models.FileField(upload_to=image_directory_path, default='products/default.png', null=True, blank=True) price = models.DecimalField(max_digits=20, decimal_places=2) discount_price = models.DecimalField( max_digits=20, decimal_places=2, blank=True, null=True ) length = models.DecimalField(max_digits=20, decimal_places=2, blank=True, null=True) width = models.DecimalField(max_digits=20, decimal_places=2, blank=True, null=True) height = models.DecimalField(max_digits=20, decimal_places=2, blank=True, null=True) weight = models.DecimalField(max_digits=20, decimal_places=2, blank=True, null=True) volume = models.DecimalField(max_digits=20, decimal_places=2, blank=True, null=True) color = models.CharField(max_length=3, choices=COLORS, blank=True, null=True) sku = models.CharField(max_length=20, null=True, blank=True) stock = models.DecimalField(max_digits=30, decimal_places=0) is_published = models.BooleanField(default=True) user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="products") created_at = models.DateTimeField(auto_now_add=True, verbose_name="created at") updated_at = models.DateTimeField(auto_now=True, verbose_name="updated at") class Meta: verbose_name = "product" verbose_name_plural = "products" db_table = "products" ordering = ["title"] def __str__(self): return self.title def get_absolute_url(self): return self.slug Here is the view I use to update the object: class UpdateProductView(generics.UpdateAPIView): permission_classes = [IsAuthenticated] serializer_class = UpdateProductSerializer def get_queryset(self): id = self.kwargs["pk"] return Product.objects.all().filter(id=id) and here is the serializer: class UpdateProductSerializer(ModelSerializer): class Meta: model = Product fields = '__all__' … -
Is overriding the Django model's save function okay in this scenario?
So, I have a model, whose save function has some side effects like this: from django.db import models class Customer(models.Model): customer_name = models.CharField(max_length=255) customer_email = models.EmailField() customer_phone = models.CharField(max_length=20) customer_address = models.CharField(max_length=255) class Product(models.Model): product_name = models.CharField(max_length=255) product_description = models.TextField() product_price = models.DecimalField(max_digits=10, decimal_places=2) class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.CASCADE) order_date = models.DateField() order_total = models.DecimalField(max_digits=10, decimal_places=2) class Order_Item(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.IntegerField() item_price = models.DecimalField(max_digits=10, decimal_places=2) class User(models.Model): username = models.CharField(max_length=255) email = models.EmailField() password = models.CharField(max_length=255) class OrderFolder(models.Model): REASON_ARCHIVED = 'ARCHIVED' REASON_REVIEW = 'REVIEW' REASON_CHOICES = [ (REASON_ARCHIVED, 'Archived'), (REASON_REVIEW, 'Review'), ] order = models.ForeignKey(Order, on_delete=models.CASCADE) reason = models.CharField(max_length=10, choices=REASON_CHOICES) user = models.ForeignKey(User, on_delete=models.CASCADE) class Payment(models.Model): payment_date = models.DateField() payment_amount = models.DecimalField(max_digits=10, decimal_places=2) payment_method = models.CharField(max_length=50) order = models.ForeignKey('Order', on_delete=models.CASCADE) def save(self, *args, **kwargs): super(Payment, self).save(*args, **kwargs) # If order is paid and order is not in review, move it to the ARCHIVED folder if self.order.order_total == self.payment_amount: of = OrderFolder.objects.get(pk = self.order.id) if of.reason != 'Review': of.reason = 'ARCHIVED' of.save() In the above code, I override the Payment's save method to have a side effect in another table. Django allows overriding save method, but is this approach acceptable considering: Potentially … -
Django QuerySet incorrectly has size 0 but has an element
When I make a query on a model with a Model.objects.filter(filters) call, it returns a queryset with all the elements that satisfy the filters passed present in it. as expected. However, in this particular case, Django returned a queryset that looks like this: which should already be impossible. As you can see, the size of the queryset is 0, Model.objects.filter(filters).count() returns 0, as does len(list(Model.objects.filter())), which is supposed to force evaluate the query, and should have returned a queryset of size 1 with the element. I know that the size of the queryset should have been 1 because Model.objects.get(filters) returns the object as expected in the debugger evaluation window. One thing that might be of interest is that this behaviour is corrected when a previous filter call is removed. The Case: Initial state: There is a table that corresponds to a django.models.Model in Django, and has 0 rows and 0 constraints. Steps to replicate: Evaluate a query using Model.objects.filter(a=x,b=y) where a and b are columns in Model and x and y are valid values, and neither a nor b are primary keys. Since the table is empty, the result will be an empty queryset. Create an object with a=x and …