Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
List of string with Django and Django restAPI
I have setup my Django and Django restAPI and I'm trying to setup my model to have a list of strings. Here's my code model.py import uuid from django.db import models class TagModel(models.Model): name = models.CharField(max_length=100) class EventModel(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title = models.CharField(max_length=255) tags = models.ManyToManyField(TagModel) class Meta: db_table = "events" ordering = ['-createdAt'] def __str__(self) -> str: return self.title serializers.py from rest_framework import serializers from .models import EventModel, TagModel class TagSerializer(serializers.ModelSerializer): class Meta: model = TagModel fields = '__all__' class EventSerializer(serializers.ModelSerializer): tags = TagSerializer(many=True) class Meta: model = EventModel fields = '__all__' My code works but not what I expected. I tried on postman to do a GET and POST request. The GET response seems to work well, but the POST request works but only with a dictionnary like the following { "title": "My example title", "tags": [{"name":"string"}, {"name":"pokemon"}] } but I wanna send something simpler like this { "title": "My example title", "tags": ["string", "pokemon"] } how to make this happen? Note: I don't use POSTGRESQL -
How do I unit test writing to a CSV file?
I am currently writing a test for a django script that writes some audit log entries to a CSV file. The system takes one CSV file, parses its contents, then adds entries based on the selections within, and saves it again once its all done. The outline of the test is as follows: class ProjectAuditReportExporterTestCase(TransactionTestCase): (...) def test_csv_generation(self): (...) mock_csv_writer = MagicMock() mock_csv_writer.writerow = MagicMock() with patch("external.exporters.csv_overwrite", return_value=mock_csv_writer) as mock_csv_overwrite: it = ImportTask.objects.create( organization=self.organization, user=self.user, data="force_delete", file=ContentFile(csv_buffer.getvalue(), "test_audit_report_exporter.csv"), importer="TasksAuditReportExporter", ) mock_csv_overwrite.assert_called_once_with(it.file, "Task Audit Report") mock_csv_writer.writerow.assert_called() The applicable bits of code for the export process are as follows: @contextmanager def csv_overwrite(file, filename_prefix) -> csv.writer: with tempfile.NamedTemporaryFile() as temp_file, io.TextIOWrapper( temp_file, encoding="utf-8-sig", write_through=True ) as text_file: yield csv.writer(text_file) temp_file.flush() temp_file.seek(0) file.save(f"{filename_prefix}_{now().strftime('%Y-%m-%d')}.csv", temp_file) (...) class EventsAuditReportExporter(BaseCSVImporter): def _handle_row(self, row): log_entries = self._logs_filter(LogEntry.objects.get_for_model(Event), start_date, end_date) with csv_overwrite(self.task.file, "Event Audit Report") as csv_writer: csv_writer.writerow( ( "Event ID", "Action date", "Action actor", "Action", "Event name", "Event date", ) ) for log_entry in log_entries.prefetch_related("actor", "version"): field_dict = log_entry.version.field_dict if field_dict: csv_writer.writerow( ( log_entry.object_id, log_entry.created.isoformat(), log_entry.actor, log_entry.action, field_dict.get("title"), field_dict.get("date"), ) ) I know there are appropriate log entries available, my debugger will always get into the csv_writer.writerow line with out issue. The issue that I have is that … -
Django: Extended User Model not saving changes to database
I have the following extended user class in models.py: Pro_User(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) access = models.BooleanField def access_update(self, Activated:bool): self.access = Activated self.save() However when I call access_update(True) in the shell it does not store the changes permanently, in the next shell session it is just BooleanField again. Any tips are appreciated :) I tried a lot of different things I found on StackOverflow already -
Elasticsearch, Searching by extra field in logging
I'm using Elasticsearch with elastic-apm==6.19.0 configured for Django. After logging an error message like logger.exception( custom_logging_message, exc_info=True, extra={ 'status_code': status_code }, ) I can indeed observe the error containing custom_logging_message in Kibana. In Elasticsearch, I can even use Query DSL to view the document which was created by the above logging event. It also holds the data which was passed to the logger using the extra keyword, as follows: "error": { ..., "custom": { ..., "status_code": 500, } } So far so great, but I want to write a query which is based on one of the extra fields. Like: GET _search { "query": { "range": { "error.custom.status_code": { "gte": 500 } } } } But the result is empty. I tried to figure out whether the respective field is indexed, using the following query: GET _my_error_index/_mapping?pretty. The result did indeed not hold the respective field under "mappings". Is this the reason why I could not use it in the search query? And if so, how to I get it indexed? Is it a setting in the elastic-apm package? I am very new to this topic and appreciate any help. Thank you. -
received channel layer as None in django
I am using channels into python and django project. the project is in docker image and the containers are redis, celery, postgres etc. and the work is to connect to the server and receive messages from the server using the redis for that. But the problem i am facing is i can't connect to the server and receiving the value of channel_layer as none let me provide you the code so that finding issue will be clean and clear so the code i updated in my settings.py file is settings.py `ASGI_APPLICATION = "ucm.asgi.application" CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [("redis", 6379)], }, }, }` asgi.py ` import os from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from channels.security.websocket import AllowedHostsOriginValidator from django.core.asgi import get_asgi_application from hook.routing import websocket_urlpatterns import hook.routing django_asgi_app = get_asgi_application() application = ProtocolTypeRouter( { "http": django_asgi_app, "websocket": AllowedHostsOriginValidator( AuthMiddlewareStack(URLRouter(websocket_urlpatterns)) ), } ) **hook\\routing.py**`from channels.routing import ProtocolTypeRouter, URLRouter from django.urls import re_path from .ChatConsumer import ChatConsumer websocket_urlpatterns = [ re_path(r'ws/chat/(?P<name>[^/]+)--(?P<wa_number>\d+)++(?P<mobile>\d+)/$', ChatConsumer.as_asgi()), ] application = ProtocolTypeRouter({ 'websocket': URLRouter(websocket_urlpatterns), })`` chatconsumers.py ` import json from channels.generic.websocket import AsyncWebsocketConsumer class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): #Extract data from payload _payload = await self.receive_json() room_data = f"{_payload['name']}--{_payload['wa_number']}--{_payload['mobile']}" # … -
How to get hierarchal results from models
I have hierarchal django model and it looks like this class Organizator(Model): is_active = models.BooleanField() user = models.IntegerField() clas Task(Model): content = models.CharField() task_id = models.IntegerField() parent = models.ForeignKey('self') organizator = models.ForeignKey(Organizator, related_name='control_taks') class Performer(Model): user = models.IntegerField() task = models.ForeignKey(Task, related_name='tasks') from this given model I am going to get following result like this { "user": 1, "is_active": true, "control_taks": [ { "task_id": 2, "content": "test", "performers": [ { "user": 1, "tasks": [ { "task_id": 3, "performers": [ { "user": 3, "tasks": [] } ] } ] } ] } ] } how can I do this? My code does not return expected result so I did not show here. Any help would be appreciated! -
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.