Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django inspectdb non public schema
We only have 1 database with atleast 10 different schemas how can I generate an inspectdb. Let's say python manage.py inspectdb "schema9.table1" > models.py to generate models I found couple of answers saying that django dont support this kind of feature specifically postgresql but maybe since it's 2022 maybe there's a simple and short way to do this -
Writeable Serializer
I have the following viewsets and serializers setup to create a single action to post a schedule with it's steps but I receive the following error. class StepCreateSerializer(serializers.Serializer): start_time = serializers.TimeField() time = serializers.IntegerField() def update(self, instance, validated_data): pass def create(self, validated_data): print(validated_data) return validated_data class ScheduleCreateSerializer(serializers.Serializer): name = serializers.CharField(max_length=100) identifier = serializers.CharField(max_length=10) steps = StepCreateSerializer(many=True) def update(self, instance, validated_data): pass def create(self, validated_data): steps_data = validated_data.get('steps', []) schedule = Schedule.objects.create(**validated_data) for step_data in steps_data: Step.objects.create(schedule=schedule, **steps_data) return schedule class ScheduleViewSet(BaseViewSet): queryset = Schedule.objects.all() serializer_class = ScheduleSerializer def create(self, request, *args, **kwargs): ser = ScheduleCreateSerializer(data=request.data) ser.is_valid(raise_exception=True) ser.save() return Response() I call it with the following json payload with POST method: { "name": "Schedule123", "identifier": "S123", "steps": [ { "start_time": "07:21:00", "time": 5, "valve_actions": [ { "start_state": true, "end_state": false, "valve": 2 }, { "start_state": true, "end_state": false, "valve": 1 } ] } ] } It results in the following error when called with the payload TypeError: Direct assignment to the reverse side of a related set is prohibited. Use steps.set() instead. The models are as follows class Schedule(models.Model): identifier = models.CharField(max_length=10) name = models.CharField(max_length=100) class Step(models.Model): start_time = models.TimeField() time = models.IntegerField() schedule = models.ForeignKey("manager.Schedule", on_delete=models.CASCADE, related_name="steps", null=True) How do … -
Route53 DNS issue with Django Elastic Beanstalk app
Not sure what I am doing wrong here. My zone is public and I have simple routing for the A records pointing to the EB alias. I even tried a CNAME to no avail. I even did a test response within the console. Everything checks out but there is something funny happening between the Route53 -> EB handshake. The EB alias works just fine by itself. I would love some pointers. Perhaps I need to configure something within Django settings? -
Getting "_pickle.PicklingError: Can't pickle <function>: it's not the same object" for django-q async_task decorator
I'm trying to create a decorator that I can apply to any function, so I can make it a django-q async task. The decorator is written as bellow def django_async_task(func): """Django Q async task decorator.""" def wrapper(*args, task_name): return django_q.tasks.async_task(func, *args, task_name=task_name) return wrapper Then I can use the above decorator in any task as below @django_async_task def my_task(a): print(f'Hello {a}') task_id = my_task('Vidu', task_name='task1') However, I cannot get the above to work as I'm getting _pickle.PicklingError: Can't pickle <function my_task at 0x7f3dc084be50>: it's not the same object as tests.my_task I tried functools wraps as below but it didn't have any effect. def django_async_task(func): """Django Q async task decorator.""" @functools.wraps(func) def wrapper(*args, task_name): return django_q.tasks.async_task(func, *args, task_name=task_name) return wrapper I also tried a decorator class but it didn't solve the issue either. -
Password reset function in django admin is not working
urls.py from django.contrib import admin from django.urls import path,include from django.urls import re_path from App.views import * from.router import router from django.views.generic import TemplateView from rest_framework_simplejwt.views import ( TokenObtainPairView,TokenRefreshView) from django.conf.urls.static import static from django.conf import settings from django.contrib.auth import views as auth_views urlpatterns = [ path('', TemplateView.as_view(template_name="social_app/index.html")), #social_app/index.html path('admin/', admin.site.urls), #admin api path('api/',include(router.urls)), #api path('accounts/', include('allauth.urls')), #allauth re_path('rest-auth/', include('rest_auth.urls')), #rest_auth path('api-auth/', include('rest_framework.urls')), re_path('/registration/', include('rest_auth.registration.urls')), path('api/token/', MyObtainTokenPairView.as_view(), name='token_obtain_pair'), path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), path('jobview/',job), path('timelog/',timelogview), path('chaining/', include('smart_selects.urls')), path('admin/password_reset/',auth_views.PasswordResetView.as_view(),name='admin_password_reset',), path('admin/password_reset/done/',auth_views.PasswordResetDoneView.as_view(),name='password_reset_done',), path('reset/<uidb64>/<token>/',auth_views.PasswordResetConfirmView.as_view(),name='password_reset_confirm',), path('reset/done/',auth_views.PasswordResetCompleteView.as_view(),name='password_reset_complete',), ] + static(settings.STATIC_URL, document_root = settings.STATIC_ROOT) I have given the password reset function in the admin page login, it is showing as "Forgotten your password or username?" in the page but when I click it the url changes http://127.0.0.1:8000/admin/login/?next=/admin/password_reset/ to this but the same login page is loading i didnt redirected to any other reset page. I have tried but couldn't able to fix it, kindly help me to fix this issue. -
Django+Docker - print() works in settings.py but not in other files
I'm using Django with Docker on my local system. print("Hello World") works in settings.py, but doesn't work in any other file!? Guess the Logger is taking away the control, but I just can't figure out how. At my wits end with this issue. Even print("Hello World", flush=1) doesn't work. (Here's the bigger issue) -
Multiple orders are being saved in one time django ecommerce?
In my django ecommerce website. I am trying to impplement order. It's working, but in one click being saved two orders. orderItem def updateItem(request): data = json.loads(request.body) productId = data['productId'] action = data['action'] quantity = data['quantity'] print('Action:', action) print('Product:', productId) print('Quantity:',quantity) customer = request.user.customer product = Product.objects.get(id=productId) order, created = Order.objects.get_or_create(customer=customer, complete=False) orderItem, created = OrderItem.objects.get_or_create(order=order, product=product) if action == 'add': orderItem.quantity = (orderItem.quantity + quantity) if action == 'remove': orderItem.quantity = (orderItem.quantity - quantity) orderItem.save() if action=='delete': orderItem.quantity=0 if orderItem.quantity <= 0: orderItem.delete() return JsonResponse('Item was added', safe=False) order def processOrder(request): transaction_id = datetime.datetime.now().timestamp() data = json.loads(request.body) name = data['form']['name'] email = data['form']['email'] phone = data['form']['number'] phoneAdd = data['form']['numberAdd'] address = data['form']['address'] time = data['form']['time'] date = data['form']['date'] payment = data['form']['payment'] comment = data['form']['comment'] id_order = int(data['form']['id']) if request.user.is_authenticated: customer = request.user.customer order = Order.objects.get(id=id_order) order.transaction_id = transaction_id order.complete=True order.save() OrderInfo.objects.create(customer=customer,order=order,name=name,email=email,phone=phone,phoneAdd=phoneAdd,address=address,time=time,date=date,payment=payment,comment=comment) else: print("Not logged in ") return JsonResponse('Payment submitted..', safe=False) It's working and complete is being changed to TRUE. However, another empty order being created. So, what's the problem? Can you please help to solve this problem? -
Scanning External files inside python backend
I have some files that I need to download and then upload to a specific location during execution of code. These files are other than source code files but required by the source code(.yaml, .xml, some .zip folders etc.) I need to scan these files for any security vulnerabilities - on the backend. Most available approaches look at source code and not at external files. Any advice to this end would be useful.(No recommendations) Note:- I am not asking for any Software recommendations. Please feel free to ask for clarifications if you find the question misleading. -
Django Admin S3 Private Media Files
When using the private media django-storages class below. When I view the uploaded file in the admin it does not generate the URL Query String Authorization parameters. from django.conf import settings from storages.backends.s3boto3 import S3Boto3Storage class PrivateMediaRootTenantedS3Boto3Storage(S3Boto3Storage): auto_create_bucket = True default_acl = "private" file_overwrite = False custom_domain = False -
datatable column filtering with serverside(ajax) doesn't work
I'm developing with django and javascript with datatable. I want to apply column filtering in my datatable (https://datatables.net/extensions/fixedheader/examples/options/columnFiltering.html) but it works fine without serverside option & ajax (in client side), but it doesn't work with serverside option & ajax. How can i FIX IT? Please help me..T_T this is my code. <table id="sample_table" class="table table-bordered table-hover"> <thead> <tr> <th class="sample_id">ID</th> <th>date</th> <th>serial</th> <th>name</th> <th>birth</th> </tr> </thead> <tbody id="sample_table_body"> </tbody> <tfoot> <tr> <th>ID</th> <th>date</th> <th>serial</th> <th>name</th> <th>birth</th> </tr> </tfoot> </table> </div> <!-- /.card-body --> </div> var column_list = [ { "data" : "id" , "className": "sample_id"}, { "data" : "receiving_at" }, { "data" : "serialnumber" }, { "data" : "name" }, { "data" : "birthday" }, ]; $('#sample_table tfoot th').each(function(){ var title = $("#sample_table thead th").eq( $(this).index() ).text(); $(this).html('<input type="text" placeholder="Search '+title+'" />' ); }); var sample_table = $('#sample_table').DataTable({ "paging": true, "autoWidth": false, "lengthChange": false, "ordering": true, "processing" : true, "columns": column_list, "order": [ [0, 'desc'] ], "fixedHeader": true, "orderCellsTop": true, "ajax": { url: '/view_datatable/', type: 'POST' }, "serverSide" : true, //get data from server "initComplete": function() { // column filtering RUN after table loaded . $( '#sample_table tfoot input' ).on( 'keyup change clear', function () { if ( sample_table.search() !== … -
API request failing if pagination is required in Django due to OrderBy' object has no attribute 'lstrip'?
I have a view that inherits from the ListModelMixin from Django REST Framework and have overridden the list(...) function so I can add query parameter validation to the list method: <!-- language: python--> class UserViewSet(ListModelMixin): def get_queryset(self): return User.objects.all() def list(self, request): queryset = self.get_queryset() # Get the query parameters from the request sort_by = request.query_params.get('sort_by') sort_order = request.query_params.get('sort_order') sorting_query: OrderBy = F(sort_by).asc(nulls_last=True) if sort_order == "desc": sorting_query = F(sort_by).desc(nulls_last=True) querySet = querySet.order_by(sorting_query, "id") # Code fails here on the pagination method page = self.paginate_queryset(queryset) if page is not None: serializer = self.get_serializer(page, many=True) return self.get_paginated_response(serializer.data) serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) The error I see when running the API is: AttributeError(\"'OrderBy' object has no attribute 'lstrip'\")", which I suspect has something to do with the sorting_query variable, but I have no idea WHY. The thing is, I only see this error when the total number of results exceed the MAX page size and pagination is needed. Otherwise, the API works fine. Any help would be appreciated! Note: I'm using cursor pagination from the Django REST Framework. -
Creating a Django post feed that gradually renders posts in batches as you scroll down
I am trying to make a Django post feed without pagination, but hypothetically, once there are more than a thousand posts, it would be too heavy to always render all of the posts available. So I am trying to find a way to mimic what many other websites with infinite feeds (like Twitter for example) do so that it renders only a batch of posts, and then renders additional ones once you scroll down to the end of the already rendered ones. I am using a function view instead of the class view. Thank you in advance for any help. -
Ignore HTML line in Django Template
I am new to Django. That's why I am a bit confused. and I am not sure is it possible or not? {% for appoint in appoints %} {% if appoint.a_status == 'Pending' %} <h4>Pending</h4> <p>{{appoint}}###<a href="#">Accept</a>###<a href="#">Reject</a></p?> {% elif appoint.a_status == 'Accept' %} <h4>Accepted</h4> <p>{{appoint}}###<a href="#">Done</a>###<a href="#">Reject</a></p?> {% elif appoint.a_status == 'Done' %} <h4>Done</h4> <p>{{appoint}}</p?> {% else %} <h4>Reject</h4> <p>{{appoint}}</p?> {% endif %} {% endfor %} This is part of a template. I want to ignore Django attribute/code to ignore the h4 tag. I know I can do this something by running loop for every h4 tag. but that will less efficient. -
Please, help to solve an exercise 19.1 from the book Python-Crash-Course.-Eric-Mattes
When I try to edit a post I see this error: TypeError at /edit_post/ edit_post() missing 1 required positional argument: 'post_id' blogs/models.py from django.db import models # Create your models here. class BlogPost(models.Model): """Creating blog topics and text""" title = models.CharField(max_length=200) text = models.TextField() date_added = models.DateTimeField(auto_now_add=True) def __str__(self): """Retunrning title""" return self.title def __str__(self): """retunrning text""" return self.text blogs/views.py from django.shortcuts import render, redirect from .models import BlogPost from .forms import PostForm # Create your views here. def index(request): """Homepage for blogs""" return render(request, 'blogs/index.html') def posts(request): """Shows the blogposts list""" posts = BlogPost.objects.order_by('-date_added') context = {'posts': posts} return render(request, 'blogs/posts.html', context) def new_post(request): """Creating new topic""" if request.method != 'POST': #Data didn't sent; create empty form form = PostForm() else: # Data sent POST; process data form = PostForm(data=request.POST) if form.is_valid(): form.save() return redirect('blogs:posts') # Show empty or invalid form context = {'form': form} return render(request, 'blogs/new_post.html', context) def edit_post(request, post_id): """Edit post""" post = BlogPost.objects.get(id=post_id) if request.method != 'POST': # Request; form is filled with the data from current post form = PostForm(instance=post) else: # Sending POST data; process data form = EntryForm(instance=post, data=request.POST) if form.is_valid(): form.save() return redirect(request, 'blogs:posts') context = {'post': post, 'form': form} return … -
How to use if control statement in jinju2 embedded html file
I'm using parsehub to scrape a bunch of movie names and have a python script export it to an html file and that is working fine. However I want to use an if statement to only print titles that have "The" in them. The structure is fine and it is evaluating the if clause, but it always evaluates to false and I am not sure why. This is my first time using Jinju2 or even hearing about the language. {% for movie in movies %} {% if 'The' in movie %} <div name="title">{{movie["title"]}}</div> {% endif %} {% endfor %} Alternatively, the parsehub tutorial I was following https://help.parsehub.com/hc/en-us/articles/217751808-API-Tutorial-How-to-get-run-data-using-Python-Flask said that there is a way to optionally filter the scraped data but I have looked into it and am not sure how to do so. # movies.py from flask import Flask, render_template import requests import json API_KEY = '' PROJECT_KEY = '' PROJECT_DATA = f"https://www.parsehub.com/api/v2/projects/{PROJECT_KEY}/last_ready_run/data" app = Flask(__name__, template_folder='.') @app.route('/') def homepage(): params = { 'api_key': API_KEY, } r = requests.get( PROJECT_DATA, params=params) #print("The r var is: \n") #print(r) return render_template('movies.html', movies=json.loads(r.text)['movies']) if __name__ == '__main__': app.run(host='0.0.0.0', debug=True) How do I get the jinju2 if statement to evaluate to true, or how … -
Django running sum with a lag
I am trying to create a table with running sum with a lag using Django window functions -------------------------------------------------- id price size cumm_sum lagged_cumsum --------------------------------------------------- 1 5 6 6 0 2 5 9 15 6 3 15 10 25 15 Following the excellent answer here: Django cumulative sum or running sum I tried to do the following query.annotate(cumsum=Window(Sum("size"), order_by=F("price").asc()), lagged_cumsum=Window(Lag("cumsum", offset=1, default=0), order_by=F("price").asc())) However I keep getting the following error code: OperationalError: misuse of window function SUM() any ideas what i may be missing? -
How to delete all schemas in postgres
I'm using django-tenants, and for some tests I need to delete all schemas at once, so I was wondering how could I delete all schemas with a single sentence/script from postgresql shell, because deleting one by one is not scalable. Thx so much. -
ValidationError at /opd/ ['“OPDCashSheet object (2)” value must be a decimal number.'] How can a model-object be a decimal number?
models.py: class Opd(models.Model): patient=models.ForeignKey(Patient, on_delete=CASCADE) bill_number=models.IntegerField(default=None) date=models.DateField(default=datetime.date.today) service_name=models.ForeignKey(ServiceName, on_delete=SET_NULL, null=True) mode=models.CharField(max_length=5, default=None) amount=models.DecimalField(max_digits=7, decimal_places=2) remarks=models.TextField(max_length=500, blank=True, default=None) opd_date=models.DateTimeField(auto_now_add=True) modified_on=models.DateTimeField(auto_now=True) def __str__(self): return self.patient.name class OPDParticulars(models.Model): opd_particulars=models.CharField(max_length=150) def __str__(self): return self.opd_particulars class OPDCashSheet(models.Model): date=models.DateField(default=datetime.date.today) patient=models.ForeignKey(Patient, on_delete=SET_NULL, blank=True, null=True) opd=models.ForeignKey(Opd, on_delete=SET_NULL, null=True, blank=True) opd_particulars=models.ForeignKey(OPDParticulars, on_delete=SET_NULL, null=True, blank=True) source=models.CharField(max_length=10, default='OPD', null=True, blank=True) case_number=models.IntegerField(null=True, blank=True) mode=models.CharField(max_length=5) cash_in=models.DecimalField(max_digits=7, decimal_places=2, null=True, blank=True) cash_out=models.DecimalField(max_digits=7, decimal_places=2, null=True, blank=True) balance=models.DecimalField(max_digits=7, decimal_places=2, default=0) bank_oopl=models.DecimalField(max_digits=7, decimal_places=2, null=True, blank=True) remarks=models.TextField(max_length=500, blank=True, null=True, default=None) created_on=models.DateTimeField(auto_now_add=True) modified_on=models.DateTimeField(auto_now=True) class BankDeposits(models.Model): opdcashsheet=models.ForeignKey(OPDCashSheet, on_delete=SET_NULL, null=True, blank=True) date=models.DateField(default=None) amount=models.DecimalField(max_digits=7, decimal_places=2, default=None) bank=models.CharField(max_length=70, default=None, null=True, blank=True) mode=models.CharField(max_length=5, default=None) bank_ac=models.CharField(max_length=25, default='ABC Pvt. 123456789') branch=models.CharField(max_length=20, default='XYZ') remarks=models.TextField(max_length=500, blank=True, null=True, default=None) created_on=models.DateTimeField(auto_now_add=True) modified_on=models.DateTimeField(auto_now=True) forms.py: class UpdateOPDCashSheetForm(ModelForm): MODE_SELECT = ( ('cash', 'Cash'), ('bank', 'Bank'), ) mode=forms.CharField(widget=forms.RadioSelect(choices=MODE_SELECT, attrs={'class': 'form-check-inline'})) class Meta: model=OPDCashSheet labels={ 'cash_in':'Cash-in', 'cash_out':'Cash-Out', 'balance':'Cash Balance', 'bank_oopl':'To Bank', 'opd_particulars':'Description', } fields='__all__' widgets={ 'date': DateInput(attrs={'type': 'date'}), } class BankDepositsForm(ModelForm): MODE_SELECT = ( ('cash', 'Cash'), ('bank', 'Bank'), ) mode=forms.CharField(widget=forms.RadioSelect(choices=MODE_SELECT, attrs={'class': 'form-check-inline'})) class Meta: model=BankDeposits labels={ 'bank_ac':'Bank A/c', } fields='__all__' widgets={ 'date': DateInput(attrs={'type': 'date'}), } class OpdForm(ModelForm): MODE_SELECT = ( ('cash', 'Cash'), ('bank', 'Bank'), ) mode=forms.CharField(widget=forms.RadioSelect(choices=MODE_SELECT, attrs={'class': 'form-check-inline'})) class Meta: model=Opd fields='__all__' widgets={ 'date': DateInput(attrs={'type': 'date'}), } views.py: def opd_view(request): if request.method=='POST': fm_opd=OpdForm(request.POST) if fm_opd.is_valid(): opd=fm_opd.save() OpdReport.objects.create(patient=opd.patient, opd=opd) if opd.mode=='cash': OPDCashSheet.objects.create(date=opd.date, patient=opd.patient, opd=opd, case_number=opd.bill_number, mode=opd.mode, cash_in=opd.amount) … -
search files on a specific folder in Django
how to search files on a specific folder in Django 2.1.15w i'm making a n an web app, and i want user to select a variable file only from on specific folder, how i should fix the header in Django to show on directory path, happy to here any ideas -
Django rest framework Field name `ia_superuser` is not valid for model `CustomUser`
I got stock with writing custom user in Django an rest framework.I've written custom user and custom serializer, I've added every necessaries in settings.py. When I try to go to user app I get this error: ImproperlyConfigured at /api/user/ Field name ia_superuser is not valid for model CustomUser. Request Method: GET Request URL: http://127.0.0.1:8000/api/user/ Django Version: 3.0.8 Exception Type: ImproperlyConfigured Exception Value: Field name ia_superuser is not valid for model CustomUser. Exception Location: C:\Users\Aireza.virtualenvs\lcodev-lF6rFvWb\lib\site-packages\rest_framework\serializers.py in build_unknown_field, line 1340 Python Executable: C:\Users\Aireza.virtualenvs\lcodev-lF6rFvWb\Scripts\python.exe Python Version: 3.10.2 Python Path: ['F:\Python\lcodev\ecom', 'C:\Users\Aireza\AppData\Local\Programs\Python\Python310\python310.zip', 'C:\Users\Aireza\AppData\Local\Programs\Python\Python310\DLLs', 'C:\Users\Aireza\AppData\Local\Programs\Python\Python310\lib', 'C:\Users\Aireza\AppData\Local\Programs\Python\Python310', 'C:\Users\Aireza\.virtualenvs\lcodev-lF6rFvWb', 'C:\Users\Aireza\.virtualenvs\lcodev-lF6rFvWb\lib\site-packages'] Server time: Tue, 22 Mar 2022 11:34:45 +0000 I have an api app in the project and the user app is in the api app. anyone can help? thanks here's everything: user serializer.py: from rest_framework import serializers from .models import CustomUser from django.contrib.auth.hashers import make_password from rest_framework.decorators import authentication_classes,permission_classes class UserSerializer(serializers.HyperlinkedModelSerializer): def create(self,validated_data): password = validated_data.pop('password',None) # pop method removes the given index from the list and returns it instance = self.Meta.model(**validated_data) if password is not None: instance.set_password(password) instance.save() return instance def update(self,instance , validated_data): for attr,value in validated_data.item(): if attr == 'password': instance.set_password(value) else: setattr(instance,attr,value) instance.save() return instance class Meta: model = CustomUser extra_kwargs = {'password':{'write_only':True}} … -
How to fix this django+bootstrap carousel bug
After first scroll carousel stops working and return error, but i don't understand it my html: <div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel"> <div class="carousel-indicators"> {% for photo in product.photo_set.all %} {% with forloop.counter0 as i %} <button type="button" data-target="#carouselExampleIndicators" data-slide-to="{{i}}"{% if i is 0 %}class="active" aria-current="true"{% endif %}></button> {% endwith %} {% endfor %} </div> <div class="carousel-inner"> {% for photo in product.photo_set.all %} {% with forloop.counter0 as i %} <div class="carousel-item {% if i is 0 %}active{% endif %}"> <img class="d-block w-100 image-source rounded" src={{photo.image.url}} style='height: 30rem;'> </div> {% endwith %} {% endfor %} </div> <button class="carousel-control-prev" type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="visually-hidden">Previous</span> </button> <button class="carousel-control-next" type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="visually-hidden">Next</span> </button> </div> and error in chrome: Uncaught TypeError: Cannot read properties of null (reading 'classList') at at._setActiveIndicatorElement (carousel.js:364:23) at at._slide (carousel.js:435:10) at at.prev (carousel.js:154:10) at Function.carouselInterface (carousel.js:526:12) at HTMLButtonElement.dataApiClickHandler (carousel.js:556:14) at HTMLDocument.s (event-handler.js:119:21) yeah (sorry), at the computer I'm a monkey with a grenade -
Django Kubernetes yaml error mapping values are not allowed in this context
Im currently trying to run helm upgrade --install --dry-run --debug django-test ./helm/django-website but when i do im met with this error line and i cant seem to fix the issue with anything i try Error: UPGRADE FAILED: YAML parse error on django-website/templates/deployment.yaml: error converting YAML to JSON: yaml: line 38: mapping values are not allowed in this context helm.go:84: [debug] error converting YAML to JSON: yaml: line 38: mapping values are not allowed in this context YAML parse error on django-website/templates/deployment.yaml helm.sh/helm/v3/pkg/releaseutil.(*manifestFile).sort helm.sh/helm/v3/pkg/releaseutil/manifest_sorter.go:146 helm.sh/helm/v3/pkg/releaseutil.SortManifests helm.sh/helm/v3/pkg/releaseutil/manifest_sorter.go:106 helm.sh/helm/v3/pkg/action.(*Configuration).renderResources helm.sh/helm/v3/pkg/action/action.go:165 helm.sh/helm/v3/pkg/action.(*Upgrade).prepareUpgrade helm.sh/helm/v3/pkg/action/upgrade.go:234 helm.sh/helm/v3/pkg/action.(*Upgrade).RunWithContext helm.sh/helm/v3/pkg/action/upgrade.go:143 main.newUpgradeCmd.func2 helm.sh/helm/v3/cmd/helm/upgrade.go:197 github.com/spf13/cobra.(*Command).execute github.com/spf13/cobra@v1.3.0/command.go:856 github.com/spf13/cobra.(*Command).ExecuteC github.com/spf13/cobra@v1.3.0/command.go:974 github.com/spf13/cobra.(*Command).Execute github.com/spf13/cobra@v1.3.0/command.go:902 main.main helm.sh/helm/v3/cmd/helm/helm.go:83 runtime.main runtime/proc.go:255 runtime.goexit runtime/asm_arm64.s:1133 UPGRADE FAILED main.newUpgradeCmd.func2 helm.sh/helm/v3/cmd/helm/upgrade.go:199 github.com/spf13/cobra.(*Command).execute github.com/spf13/cobra@v1.3.0/command.go:856 github.com/spf13/cobra.(*Command).ExecuteC github.com/spf13/cobra@v1.3.0/command.go:974 github.com/spf13/cobra.(*Command).Execute github.com/spf13/cobra@v1.3.0/command.go:902 main.main helm.sh/helm/v3/cmd/helm/helm.go:83 runtime.main runtime/proc.go:255 runtime.goexit runtime/asm_arm64.s:1133 line 38 is the include line under env:, ive read up on yaml indentations, tried yaml scanners, i cant seem to fix it and when i do it causes something else to break but the code im using is generated from kubernetes so i dont understand why it wont work does anyone know how to fix it -
Python equivalent of `binding.pry`
What is the Python and Django equivalent of the Pry Gem, binding.pry. What library can I use to easily debug? In ROR I can put binding.pry in any code and it will stop the execution on that line and give me a chance to debug. -
Include Django variable into a JQuery Code
I have a JQuery code using a pagination plugin, Here is the code : $('#demo').pagination({ dataSource: [1, 2, 3, 4, 5, 6, 7, ... , 195], callback: function(data, pagination) { // template method of yourself var html = template(data); dataContainer.html(html); } }) But here I want to make the dataSource of a list of customers that is stocked in my database -
Django : Structure of the API withe redirect functions or decorators
I am a Newbee on Django and I am not sure of the structure of my API. There is a sidebar with a list of apps. I have one that is to upload files. I want that when the user click on the upload files app it appears a page with a dropdown list to choose a client. Then when it selects a client, it redirects to the upload page with the value of the client selected because this value has to be stored in the database when a file is upload and show in the templates too. When the user wants to change of client, he has to return to the previous page and change the selected client How should I do that ? What is the most efficient and logic in terms of views and decorators ? Here is what I did. I think that it is not efficient.The user clicks on the upload url, it brings to the upload view where the id_client selected is initialize to None. So it redirects to the selectclient view where the user selects the client and brings back to the upload view def upload(request, idclient = None): if idclient == None …