Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to Display Total Object Count in Wagtail Snippet ViewSet?
I am currently developing a Wagtail project where I use the ModelAdmin to create custom admin interfaces for my models. When using ModelAdmin, the total object count of a model is displayed below the model name in the list view. However, when I switched to using SnippetViewSet, I lost this functionality.I would like to display the total object count in the list view based on the custom get_queryset method defined in my SnippetViewSet class. ModelAdmin: SnippetViewSet: class PidProviderViewSet(SnippetViewSet): model = PidProvider icon = 'folder' list_display = ["v3", "created"] menu_name = "Unloaded Objects PidProvider" def get_queryset(self, request): qs = PidProvider.objects.filter(foo='foo') return qs register_snippet(PidProviderViewSet) -
Django where to store model-level variables
So I have my model: from django.db import models x_default_coordinate = 0 y_default_coordinate = 0 class Model(models.Model): location1 = gis_models.PointField( srid=4326, default=Point(x_default_coordinate, y_default_coordinate) ) location2 = gis_models.PointField( srid=4326, default=Point(x_default_coordinate, y_default_coordinate) ) Where would be an appropriate place to store the default coordinates? Currently I have them as shown, but that doesn't seem right. -
Sum an aggerated value in Django
I'm trying to achieve the following SQL query in Django: (The table contains the purchases per each day per each location. I want to get the biggest amount of each location, then group them by state to see how much is the max that can be sold in each state) select state, type, sum(amount) from ( select l.state, dd.type, max(amount) as amount from daily_data dd join locations l on l.id = dd.location_id where dd.type in ('purchases', 'returns') group by dd.location_id, dd.type ) group by state, type Where I get this: NY,purchases,80 NY, returns,6 Maine,purchases,125 Maine, returns,12 But I'm geting stuck on how to achieve that in django. I tried this: daily_data.objects.filter(type__in=['purchases', 'returns'] ).values('location', 'type' ).annotate(total=Max('amount') ).values('location__state','type' ).annotate(sum=Sum('total')) But I get an error django.core.exceptions.FieldError: Cannot compute Sum('total'): 'total' is an aggregate I even tried a subquery, but this is generating a bad sql query which yields the query taking forever. subquery = daily_data.objects.filter( location=OuterRef('location'), type=OuterRef('type') ).values('location', 'type').annotate( max_amount=Max('amount') ).values('max_amount') annotated_data = daily_data.objects.filter( type__in=['purchases', 'returns'] ).annotate( max_amount=Subquery(subquery) ).values( 'location__state', 'type' ).annotate( total_max_amount=Sum('max_amount') ).order_by('location__state', 'type') This generates: SELECT "state", "type", SUM(( SELECT MAX(U0."amount") AS "total" FROM "daily_data" U0 INNER JOIN "locations" U1 ON (U0."location_id" = U1."id") WHERE (U1."state" = ("state") AND U2."type" = … -
My partner and I are running the same code, but mine is the only one not working on my local server
We are working with Django to perform an asynchronous export task that will populate a CSV with information and then download the CSV automatically to the user's Downloads once a user hits the button 'Start Export.' When it comes time to run the server and test the download, their CSV downloads immediately upon hitting the export button and mine stays stuck, resulting in infinite XMLHttpRequest's (I eventually have to stop running server), as pictured below. Naturally, their Safari network shows only one XHR before it downloads. Infinite XHR's We have pulled the same code and I have matched up my Python version and package downloads to theirs. I have also made sure I cleared cache, tried different browsers, and allowed all popups on my browser. I have also confirmed that the async task successfully results in a CSV when I test on the shell. I have also recreated the virtual environment multiple times. I've been tearing my hair out about this for 8 hours a day for the past week. Any pointers would be appreciated! Thank you. -
How to implement Django WebSockets?
I'm trying to create a simple Django app, using websockets for sending data. According to the documentation: I've added 'channels' in settings.py's INSTALLED APPS: INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "channels", "serial_mouse", ] ASGI_APPLICATION = 'mouse_serial.asgi.application' Created asgi.py file, to configure ASGI: import os from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter, URLRouter from channels.auth import AuthMiddlewareStack from serial_mouse import routing os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mouse_serial.settings') application = ProtocolTypeRouter({ 'http': get_asgi_application(), 'websocket': AuthMiddlewareStack( URLRouter( routing.websocket_urlpatterns ) ), }) Set up routing.py for websockets: from django.urls import path from . import consumers websocket_urlpatterns = [ path('ws/serial/', consumers.SerialConsumer.as_asgi()), ] Implemented the WebSocket consumer in the newly created consumers.py: import json import asyncio import os import serial import cv2 import time from django.conf import settings from channels.generic.websocket import AsyncWebsocketConsumer from .models import Capture, MouseData class SerialConsumer(AsyncWebsocketConsumer): def __init__(self, *args, **kwargs): super().__init__(args, kwargs) self.serial_task = None async def connect(self): await self.accept() self.serial_task = asyncio.create_task(self.read_serial()) async def disconnect(self, close_code): self.serial_task.cancel() async def receive(self, text_data): data = json.loads(text_data) if data['action'] == 'capture': self.capture_image() elif data['action'] == 'mouse_move': self.save_mouse_data(data['x'], data['y']) async def read_serial(self): ser = serial.Serial('/dev/ttyUSB0', 9600) while True: line = ser.readline().decode('utf-8').strip() await self.send(text_data=json.dumps({ 'message': line, })) @staticmethod def capture_image(): cam = cv2.VideoCapture(0) ret, frame = cam.read() … -
The debug toolbar is not displayed - docker - django
) I hope you be well... well! I just installed debug toolbar for my django project like allways. but I don't know why doesn't the debug toolbar display?! and I have to add that I'm using docker and it's my first time that use docker. I think I should do something with docker... I have no ideas:) I also run "docker-compose up --build" but nothing and nothing -
Field is filled but still get ValidationError this field is required in
I want to create User using User.objects.create_user and I am using some fields of a form Utilisateurs to do that. The image field and username field from this form are also used to populate a model UserProfile. In views py def sign_in(request): form=Utilisateur(request.GET) if request.method=="POST": form=Utilisateur(request.POST) if form.is_valid(): User.objects.create_user(username=form.cleaned_data["username"], password=form.cleaned_data["password"], first_name=form.cleaned_data["first_name"], last_name=form.cleaned_data["last_name"], email=form.cleaned_data["email"] ) UserProfile.objects.create(username=form.cleaned_data["username"],profile_img=form.cleaned_data["profile_img"]) return redirect("home") else: print(form.errors.as_data()) context={"form":form} return render(request,'signin.html',context) In models.py class UserProfile(models.Model): username=models.CharField(max_length=50) profile_img=models.ImageField(default="images/logo.png", upload_to="images/",blank=True, null=True) date = models.DateField(default=django.utils.timezone.now()) In forms.py class Utilisateur(forms.Form): first_name=forms.CharField(min_length=4,max_length=15,label="Nom",widget=(forms.TextInput(attrs={"class":"userclass"}))) last_name = forms.CharField(min_length=4, max_length=15,label="Prenom",widget=(forms.TextInput(attrs={"class":"userclass"}))) username=forms.CharField(min_length=4, max_length=15,label="Nom d'uttilisateur",widget=(forms.TextInput(attrs={"class":"userclass"}))) email=forms.EmailField(label="Email",widget=(forms.EmailInput(attrs={"class":"userclass"}))) password=forms.CharField(label="Mot de passe",widget=(forms.PasswordInput(attrs={"class":"userclass"}))) profile_img = forms.ImageField(label="Image de Profile") class ProfileForm(forms.Form): profile_img = forms.ImageField(label="Image de Profile", required=False) Error printed out: {'profile_img': [ValidationError(['This field is required.'])]} -
"No errors found by the IDE" in problems tab
My PyCharm always shows: "No errors found by the IDE" I don't open power save mode. I don't know why. I even reinstalled PyCharm and shut down all plugins, however, my idea doesn't work well. I have search this problem on the internet but without finding any solution. -
I'm unable to run my django application, but nothing happens
I have a django project and I'm trying to run it with '''python manage.py runserver ''' but nothing really happens. I was working on it just 5 mins before this happens. Now, I'm unable to run anything, my project doesn't even show on the github desktop version... anyone has any ideas ? I've tried to check django, python, Running Processes, everything is okey. I'm not able to Run Django Shell neither.enter image description here -
how to show user in TokenSerializer dj-rest-auth
I'm trying to return UserSerializer after successful login through dj-rest-auth. I followed the steps that were told in After login the `rest-auth`, how to return more information? which has a similar issue, but it still doesn't show information about User after logging in. what i'm getting after successful login REST_AUTH_SERIALIZERS = { 'TOKEN_SERIALIZER': 'blink.user.serializers.TokenSerializer', 'USER_DETAILS_SERIALIZER': 'blink.user.serializers.UserSerializer' } #settings.py class UserSerializer(serializers.ModelSerializer): def __init__(self, *args, **kwargs): exclude_fields = kwargs.pop('exclude_fields', None) super(UserSerializer, self).__init__(*args, **kwargs) if self.context and 'view' in self.context and self.context['view'].__class__.__name__ == 'UsersView': exclude_fields = ['subscription', 'avatar', 'file'] if exclude_fields: for field_name in exclude_fields: self.fields.pop(field_name) class Meta: fields = ('id', 'username', 'email', 'last_login', 'first_name', 'last_name') model = User class TokenSerializer(serializers.ModelSerializer): user = UserSerializer() class Meta: model = TokenModel fields = '__all__' #User.serializers.py -
Post.objects.all() not working as i wished
Hey I am currently going through the Django tutorials and I am trying to display all of my Post objects in the python shell using from blog.models import Post Post.objects.all() my model is from django.db import models from django.utils import timezone from django.contrib.auth.models import User # Create your models here. class Post(models.Model): title = models.CharField(max_length=200) contents = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User,on_delete=models.CASCADE) def __str__(self): return self.title It should display ` [<Post: Blog 1>, <Post: Blog 2>] instead of [<Post: Post object (1)>, <Post: Post object (2)>] It just says "Post object" instead of the title. What is the reason why? I have been following the tutorial exactly and can't understand why it displays it like that. It's hard to organize all of the posts when it says "Post object" for all of them. I am using the latest version of python and django. -
ReactJS useParams for Django equivalent?
Django Example # urls.py url = [ path('password_reset/<uidb64>/<token>/', views.password_reset_confirm, name='password_reset_confirm'), ] # views.py def password_reset_confirm(request, id, token): print(id) print(token) pass How would I create an equivalent for ReactJS?? // App.js <Route path='password_reset/:uid/:token' element={<PasswordResetPage/>} /> // PasswordResetPage.js ???? -
Custom Django Transform with case statement for casting a string to either int or null
I'm trying to create a custom django lookup as_int so that you can easily compare and order the contents of text fields when they contain only a number, and treat them as NULL when they have the wrong format. For example: Comment.objects.filter(body__as_int__gt=5) # Should treat a comment with body="37" as 37 # Should treat a comment with body="abc" as NULL This is what I have so far: class AsIntTransform(Transform): lookup_name = "as_int" output_field = models.IntegerField() def as_sql(self, compiler, connection): case_expr = Case( When( Regex(self.lhs, r"^\d+$"), then=Cast(self.lhs, models.IntegerField()), ), default=Value(None), ) return case_expr.as_sql(compiler, connection) models.CharField.register_lookup(AsIntTransform) models.TextField.register_lookup(AsIntTransform) Trying to filter with the above code is throwing: field_list = name.split(LOOKUP_SEP) ^^^^^^^^^^ AttributeError: 'Col' object has no attribute 'split' It looks like the 'Col' its referring to here is self.lhs in the transform, but I'm not sure what I'm supposed to change to make this work? -
Django errorlist in form Select Valid Choice
The situation is as follows: I am building a form where I fetch data for some fields from an API. I have tried debugging in every possible way, but I cannot understand why the data is not being persisted in the database. Whenever I click submit, I get the following error: <ul class="errorlist"><li>municipio<ul class="errorlist"><li>Select a valid choice. Afuá is not one of the available choices.</li></ul></li></ul> If anyone can help me understand why this error is occurring, I would appreciate it. To provide context, I am sharing the three main files. My models.py: # apps/parametrizacao/models.py from django.db import models class RegraFiscal(models.Model): REGIME_TRIBUTARIO_CHOICES = [ ('Simples Nacional', 'Simples Nacional'), ('Lucro Presumido', 'Lucro Presumido'), ('Lucro Real', 'Lucro Real'), ('Misto', 'Misto') ] PORTE_CHOICES = [ ('ME', 'Microempresa (ME)'), ('EPP', 'Empresa de Pequeno Porte (EPP)'), ('Demais', 'Demais') ] nome = models.CharField(max_length=255, default='Padrão') regime_tributario = models.CharField(max_length=20, choices=REGIME_TRIBUTARIO_CHOICES) porte = models.CharField(max_length=10, choices=PORTE_CHOICES, default='ME') aliquota_csll = models.DecimalField(max_digits=5, decimal_places=2, default=0) aliquota_irpj = models.DecimalField(max_digits=5, decimal_places=2, default=0) aliquota_pis = models.DecimalField(max_digits=5, decimal_places=2, default=0) aliquota_cofins = models.DecimalField(max_digits=5, decimal_places=2, default=0) aliquota_icms = models.DecimalField(max_digits=5, decimal_places=2, default=0) aliquota_ipi = models.DecimalField(max_digits=5, decimal_places=2, default=0) aliquota_iss = models.DecimalField(max_digits=5, decimal_places=2, default=0) aliquota_inss = models.DecimalField(max_digits=5, decimal_places=2, default=0) def __str__(self): return f"{self.nome} - {self.porte}" class Empresa(models.Model): nome = models.CharField(max_length=255) cnpj = models.CharField(max_length=18) … -
How to debug HTTP 400 Bad Request errors in django?
I have an app with React frontend and Django backend. I'm trying to make a POST request from my react client but I get "Bad Request" error. I checked my request url and it matches with my api url. Therefore I believe the error has to do with the data I pass. How can I debug this error to learn more about it? Here are the necessary code parts: models.py class Product(models.Model): name = models.CharField(max_length=100) description = models.TextField() created_at = models.DateTimeField(auto_now_add=True) owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name="products") def __str__(self): return self.name class BatchChain(models.Model): created_at = models.DateTimeField(auto_now_add=True) created_by = models.ForeignKey(User, on_delete=models.CASCADE) is_active = models.BooleanField() class Batch(models.Model): # This is the model I'm trying to POST product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name="batches_from_products") chain = models.ForeignKey(BatchChain, on_delete=models.CASCADE) serializers.py class BatchPostSerializer(serializers.ModelSerializer): class Meta: model = Batch fields = ["id", "product", "chain"] views.py class BatchListCreate(generics.ListCreateAPIView): serializer_class = BatchPostSerializer permission_classes = [IsAuthenticated] def get_queryset(self): user = self.request.user batches = Batch.objects.filter(product__owner=user) return Batch.objects.filter(chain__in=batches.values_list("chain")) def perform_create(self, serializer): if serializer.is_valid() is False: return Response({'Message': 'Serializer is not valid'}, status=status.HTTP_400_BAD_REQUEST) if Batch.objects.filter(chain=self.request.data["chain"]).exists(): return Response({'Message': 'You can not create a second batch with same chain'}, status=status.HTTP_405_METHOD_NOT_ALLOWED) serializer.save() api/urls.py ... path("batches/", views.BatchListCreate.as_view(), name="batch-list-create"), # all calls to /api/ are directed to this folder ... … -
Validation in DR(Django)
I'm trying create customs validations to my serialiazer but Django just ignore them and return me DRF default errors. {'message': 'Erro ao criar camião', 'data': {'plate': [ErrorDetail(string='This field may not be null.', code='null')]}} That's the answer i get view.py View that allow companies to add their trucks class TruckView(generics.GenericAPIView): permission_classes = [IsAuthenticated, IsCompanyAuthenticated] queryset = Trucks.objects.all() serializer_class = TruckSerializer def post(self, request): company = get_object_or_404(Company, user=request.user) request.data['company'] = company.id request.data['on_service'] = False serializer = TruckSerializer(data=request.data) if serializer.is_valid(raise_exception=False): serializer.save() return Response( { 'message': "Camião criado com sucesso", 'data': serializer.data }, status=status.HTTP_201_CREATED ) else: print(serializer.data) return Response( { 'message': "Erro ao criar camião", 'data': serializer.errors }, status=status.HTTP_400_BAD_REQUEST ) Serializer.py class TruckSerializer(serializers.ModelSerializer): company = serializers.PrimaryKeyRelatedField(queryset=Company.objects.all()) types = TypesSerializer(many=True, read_only=True) class Meta: model = Trucks fields = '__all__' def validate(self, attrs): return super().validate(attrs) def validate_required_field(self, value, error_message): if not value or value in [None, "", " ", []]: raise ValidationError(error_message) return value def validate_plate(self, value): return self.validate_required_field(value, "Matricula inválida") def validate_types(self, value): for type_id in value: try: # Get the Types instance by ID Types.objects.get(id=type_id['id']) except Types.DoesNotExist: # Handle the case where the type ID is not valid raise serializers.ValidationError("Tipo de veículo inválido") return self.validate_required_field(value, "Introduza tipo válidos para este camião") def validate_policy_nr(self, value): … -
Django app deployed to under the url subdirectoly
In my server,django and nginx is deployed on ECS fargate and connected to loadbalancer, but URL is transferd by Akamai https://www.example.com/company/playground/* -> https://amazonloadbalancer/* However, there comes a few problem,such as Problem 1 static Access https://www.exmplae.com/company/playground/top will be jumped to https://amazonloadbalancer/top correctly, but static file url will be https://www.exmplae.com/static/main.js while the real file is located https://www.example.com/company/playground/static/main.js /company/playground is omitted so, can not be reached. Problem 2 admin transfered accesing https://www.example.com/company/playground/admin the url is transferred by django to https://www.example.com/admin/login/?next=/admin/ /company/playground is omitted again, so can not be reached. Is there any good setting for this purpose?? -
Django Inline Formset data not saving
I have created an inline formset which works exactly as I planned on the frontend side- However I can't seem to access any of the data- it seems like the form isn't saving the data? Here in the views.py you can see where it should be saving: def formset_variantingredients_valid(self, formset): variantingredients = formset.save(commit=False) for variantingredient in variantingredients: variantingredient.recipe = self.object variantingredient.save() def formset_images_valid(self, formset): images = formset.save(commit=False) for image in images: image.recipe = self.object image.save() In the admin, in my saved form I can only see the standard fields that have saved and not either of these two inline formsets- Is my issue in the saving of the form itself or am I just not accessing the data correctly? Many Thanks for the help! -
Is the batch processing speed of Python slower than that of Java?
I am working on migrating a function implemented in Java Spring Boot to Python Django. I encountered an issue while migrating a function that retrieves a list of keywords through a select query and updates these keywords using an update query. Specifically, updating 450 rows takes around 0.1 seconds in Java, but it takes 2 seconds in Python. Below are the methods I used to measure the time and the Java and Python code. Measurement method // java long startTime = System.nanoTime(); // Execute the update long endTime = System.nanoTime(); double duration = (endTime - startTime) / 1_000_000_000.0;; String formattedDuration = String.format("%.2f seconds", duration); log.info("processing_time: {}", formattedDuration); // python start_time = time.perf_counter() // Execute the update end_time = time.perf_counter() processing_time = end_time - start_time processing_time_formatted = f"{processing_time:.2f}" logger.info(f"processing_time: {processing_time_formatted} seconds") Logic Java // application.yml spring: datasource: driver-class-name: org.mariadb.jdbc.Driver url: jdbc:mariadb:... username: ... password: ... jpa: hibernate: ddl-auto: none properties: hibernate: show_sql: true use_sql_comments: true format_sql: true dialect : org.hibernate.dialect.MariaDBDialect open-in-view: false sql: init: mode: never // service public void updateUserIntrKwd(String indvNum) { // 2s List<IntrKwdDto> kwdList = intrKwdMapper.selectIntrKwdList(indvNum); // 0.001s DatesAndMaxFrequency datesAndMaxFrequency = getDatesAndMaxFrequency(kwdList); // 0.1s intrKwdMapper.updateUserIntrKwd(kwdList, datesAndMaxFrequency); } // Mapper <update id="updateUserIntrKwd" parameterType="map"> <foreach collection="kwdList" item="item" separator=";"> ... Python … -
AJAX Filtering with jQuery and Django Not Updating Product List
I am working on a project where I need to filter products based on selected categories and vendors using AJAX with jQuery and Django. However, despite no errors in the console, the product list is not updating as expected. Here are the relevant parts of my code: JavaScript: $(document).ready(function(){ $(".filter-checkbox").on("click",function(){ console.log("A checkbox have benn clicked"); let filter_object = {} $(".filter-checkbox").each(function(){ let filter_value = $(this).val() let filter_key = $(this).data("filter") // console.log("Filter value is:", filter_value); // console.log("Filter key is:", filter_key); filter_object[filter_key] = Array.from(document.querySelectorAll('input[data-filter = '+ filter_key +']:checked')).map(function(element){ return element.value }) }) console.log("Filter object is:", filter_object) $.ajax({ url: '/filter-product', data: filter_object, dataType: 'json', beforeSend: function(){ console.log("Trying to filter Product...") }, success: function(response){ console.log(response); console.log("Data filtered successfully..."); $("#filtered-product").html(response.data) } }) }) }) Django Views: def filter_product(request): categories = request.GET.getlist("category[]") vendors = request.GET.getlist("vendor[]") products = Product.objects.filter(product_status="published").order_by("-id").distinct() if len(categories) > 0: products = products.filter(cagtegory__id__in = categories).distinct() if len(vendors) > 0: products = products.filter(vendor__id__in = vendors).distinct() context = { "products":products } data = render_to_string("core/async/product-list.html",context) return JsonResponse({"data":data}) Template: <div class="showcase" id="filtered-product"> {% for p in products %} <div class="showcase-banner"> <img src="{{p.image.url}}" width="300" class="product-img default"> <img src="{{p.image.url}}" width="300" class="product-img hover"> <p class="showcase-badge">15%</p> <div class="showcase-actions"> <button class="btn-action"> <ion-icon name="heart-outline"></ion-icon> </button> <button class="btn-action"> <ion-icon name="eye-outline"></ion-icon> </button> <button class="btn-action"> <ion-icon name="repeat-outline"></ion-icon> </button> … -
Payment Gateway Integration with Django
I'm integrating payment gateway APIs in my application (Django). I have written a class PaymentGateway that provides all the methods for all payment related utility. The __init__ initialises the payment gateway client as self.client so that it's available across all methods. But, I need help in making a decision on how to use it. Is it OK if I instantiate and use the payment gateway object across the program, whenever I need it? OR Should I maintain a single instance of it across the whole application? Need help in understanding what could be pros and cons or any other suggestion so that I can make this decision. My current code looks something like below right now: class PaymentGateway: def __init__(self): self.client = PG(api_key="api_key") def create_intent(self, user): return self.client.intents.create(customer_id=user.email) def get_user_id(email): return self.client.users.retrieve(customer_id=email) class MyView(GenericAPIView): def get(self, request): pg_instance = PaymentGateway() intent = pg_instance.create(request.user) return Response({"user_id": get_user_id(request.user), "intent": intent}) # Somewhere in utils.py def get_user_id(user): pg = PaymentGateway() return pg.get_user_id(user.email) -
runser can't serve media if MEDIA_URL is within STATIC_URL, even different settting
In my server,django and nginx is deployed on ECS fargate and connected to loadbalancer, but URL is transferd by Akamai https://www.exmplae.com/company/playground/* -> https://amazonloadbalancer/* So,https://www.exmplae.com/company/playground/ is the url in browser. I have this error django on server (DEBUG=TRUE) runser can't serve media if MEDIA_URL is within STATIC_URL However in this case I have only static setting, no media settings. STATIC_URL = "static/" STATIC_ROOT = "static/" So I just added the media setting in settings.py = STATIC_URL = "static/" STATIC_ROOT = "static/" MEDIA_URL = 'media/' MEDIA_ROOT = 'media/' However , strangely the same error runser can't serve media if MEDIA_URL is within STATIC_URL occurs. How can I fix this? -
Handle Http 302 response on Django view and Javascript async function
For strict security, how can I implement redirect on Django view in response to a JS async call that only updates a div InnerHTML? That is the first preference. I tried JS client-side redirect in multiple ways. It didn't work either. JS keeps rendering home page as InnerHTML in the div. When user's session is ended, server returns 302 Location: /. To take the user to the home page. View @csrf_protect def edit_form(request): if not request.user.is_authenticated: return redirect('/') form = userForm() return render(request, 'edit_form.html', {'form': form}) JS async function fetch_form() { try { const response = await fetch('http://192.168.1.10:8000/edit_form',{ method: 'GET', }); if (!response.ok) { //redirect didn't work const redirectUrl = response.headers.get('Location'); console.log(redirectUrl); window.location.href = redirectUrl; //throw new Error('Network response was not ok ' + response.statusText); } else if (response.status === 302) { //redirect didn't work const redirectUrl = response.headers.get('Location'); console.log(redirectUrl); window.location.href = redirectUrl; } document.getElementById('firstModal').innerHTML = data; } catch (error) { console. Error('There has been a problem with your fetch operation:', error); } }; async function fetch_form() { try { const response = await fetch('http://192.168.1.10:8000/edit_form',{ method: 'GET', }); if (!response.ok){ throw new Error('Network response was not ok ' + response.statusText); } document.getElementById('firstModal').innerHTML = data; } catch (error) { if (error.response.status … -
Django Auto Assigning Author to the user creating the post
I am having an issue with my Author being auto-assigned, it was previously working but has stopped working since I added some inline formsets- Here is my model: class Recipe(models.Model): title = models.CharField(max_length=100) description = models.TextField() author = models.ForeignKey(User, on_delete=models.CASCADE) serving = models.PositiveIntegerField(default=1) temperature = models.PositiveIntegerField(default=1) prep_time = models.PositiveIntegerField(default=1) cook_time = models.PositiveIntegerField(default=1) ##tags = models.ManyToManyField('Tag') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def get_absolute_url(self): return reverse('recipes-detail', kwargs={"pk": self.pk}) def __str__(self): return self.title Unsure if maybe some of my other code could be overriding this? This is my form: class RecipeForm(forms.ModelForm): class Meta: model = Recipe exclude = ['author', 'created_at', 'updated_at'] def __init__(self, *args, **kwargs): super(RecipeForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_tag = True self.helper.form_class = 'form-horizontal' self.helper.label_class = 'col-md-3 create-label' self.helper.field_class = 'col-md-9' self.helper.layout = Layout( Div( Field('title'), Field('description'), Field('temperature'), Field('serving'), Field('prep_time'), Field('cook_time'), ) ) If I set blank=True, null=True in the model, it allows the form to go through but with no author associated- Even any indication to what could be causing my issue would be hugely helpful! Many Thanks -
binascii.Error: Invalid base64-encoded string: number of data characters (41) cannot be 1 more than a multiple of 4
I'm trying to use py-vapid, pywebpush, and django-push-notifications to send notifications via Webpush. When I try to send a test notification from the django admin website, I get this traceback log in the console: | Internal Server Error: /djangoadmin/push_notifications/webpushdevice/ | Traceback (most recent call last): | File "/usr/local/lib/python3.8/site-packages/asgiref/sync.py", line 518, in thread_handler | raise exc_info[1] | File "/usr/local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 38, in inner | response = await get_response(request) | File "/usr/local/lib/python3.8/site-packages/django/core/handlers/base.py", line 233, in _get_response_async | response = await wrapped_callback(request, *callback_args, **callback_kwargs) | File "/usr/local/lib/python3.8/site-packages/asgiref/sync.py", line 468, in __call__ | ret = await asyncio.shield(exec_coro) | File "/usr/local/lib/python3.8/site-packages/asgiref/current_thread_executor.py", line 40, in run | result = self.fn(*self.args, **self.kwargs) | File "/usr/local/lib/python3.8/site-packages/asgiref/sync.py", line 522, in thread_handler | return func(*args, **kwargs) | File "/usr/local/lib/python3.8/site-packages/django/contrib/admin/options.py", line 616, in wrapper | return self.admin_site.admin_view(view)(*args, **kwargs) | File "/usr/local/lib/python3.8/site-packages/django/utils/decorators.py", line 130, in _wrapped_view | response = view_func(request, *args, **kwargs) | File "/usr/local/lib/python3.8/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func | response = view_func(request, *args, **kwargs) | File "/usr/local/lib/python3.8/site-packages/django/contrib/admin/sites.py", line 232, in inner | return view(request, *args, **kwargs) | File "/usr/local/lib/python3.8/site-packages/django/utils/decorators.py", line 43, in _wrapper | return bound_method(*args, **kwargs) | File "/usr/local/lib/python3.8/site-packages/django/utils/decorators.py", line 130, in _wrapped_view | response = view_func(request, *args, **kwargs) | File "/usr/local/lib/python3.8/site-packages/django/contrib/admin/options.py", line 1723, in changelist_view | response = self.response_action(request, …