Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django filtering with select_related using Custom QuerySet, works in shell, fails in views
I am using Django 3.2 Below is a reduced portion of my code models.py class ItemQuerySet(models.QuerySet): def qualified(self): return self.filter(status=1) def training(self): return self.filter(status=2) def failed(self): return self.filter(status=3) def showable(self): Q1 = Q(status=1) Q2 = (Q(last_fields__isnull=False) & ~Q(last_fields__exact='')) return self.filter(Q1 | Q2) class Foobar(models.Model): # some fields objects_qualifiers = ItemQuerySet().as_manager() class Category(models.Model): pass class Foo(Foobar): title = models.CharField(max_length=16) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT) category = models.ForeignKey(Category, on_delete=models.CASCADE) content = models.TextField() is_done = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now=True) def __str__(self): return self.title views.py class FooListView(ListView): model = Foo template_name = 'foobar/index.html' context_object_name = 'foos' paginate_by = 5 ordering=['-created_at'] def get_queryset(self): return self.model.objects_qualifiers.showable().filter(is_done=True).all().select_related('author','category') When the view is accessed, it raises the following error: self.RelatedObjectDoesNotExist( foo.models.Foo.author.RelatedObjectDoesNotExist: Foo has no author. This (seems to) makes sense, because I am calling select_related on a QuerySet object - however, the error is a bit misleading, because it does identify and report the correct class (Foo) but then says that it has no author field. It would make sense if the error message said something like ItemQuerySet has no 'author' field. In order to test that my reasoning was correct, I decided to test my hypothesis in the shell: console output from foo.models import Foo foo = Foo.objects.get(id=1) foo.author … -
how to view models with foreign keys with serializers
Hi I am making a crud with serializers and I am having trouble viewing them.An error which I am unable to solve "ErrorDetail(string='Incorrect type. Expected pk value, received str.', code='incorrect_type')" models class Products(models.Model): categories = models.ForeignKey(Categories,on_delete=models.CASCADE) sub_categories = models.ForeignKey(SUBCategories,on_delete=models.CASCADE) color = models.ForeignKey(Colors,on_delete=models.CASCADE) size = models.ForeignKey(Size,on_delete=models.CASCADE) # image = models.ImageField(upload_to = 'media/',width_field=None,height_field=None,null=True) title = models.CharField(max_length=50) price = models.CharField(max_length=10) sku_number = models.CharField(max_length=10) product_details = models.CharField(max_length=300) quantity = models.IntegerField(default=0) isactive = models.BooleanField(default=True) functions def insert(request): if request.method == "POST": print('POST',id) insert_clothes = {} insert_clothes['categories']=request.POST.get('categories') insert_clothes['sub_categories']=request.POST.get('sub_categories') insert_clothes['color']=request.POST.get('color') insert_clothes['size']=request.POST.get('size ') # insert_clothes['image']=request.POST.get('image') insert_clothes['title']=request.POST.get('title') insert_clothes['price']=request.POST.get('price') insert_clothes['sku_number']=request.POST.get('sku_number') insert_clothes['product_details']=request.POST.get('product_details') insert_clothes['quantity']=request.POST.get('quantity') print("insert clothes:",insert_clothes) serializer = POLLSerializer(data = insert_clothes) print('form:',serializer.initial_data) if serializer.is_valid(): serializer.save() messages.success(request,'Record Updated successfully :)!!!!') return redirect('polls:show') else: print("invalid") print("error of serializer:",serializer.errors) return redirect('polls:insert') else: print('GET',id) return render(request,'polls/product_insert.html') def show(request): showall = Products.objects.filter(isactive=True) print("show all data:",showall) serializer = POLLSerializer(showall,many=True) return render(request,'polls/product_list.html',{"data":serializer.data}) can someone please point out to where I am going wrong?Thanks -
Prevent all data from being displayed with Django-filter
I am currently developing a search system using Django-filter. For example, if you search under the following conditions, all the displays will be returned. Data [ { "id": 1, "city": "aaa", }, { "id": 2, "city": "bbb", }, { "id": 3, "city": "ccc", } ] views.py class CitySearchView(APIView): def get(self, request): if not request.GET: raise Http404() queryset = City.objects.all() filterset = FilterCity(request.query_params, queryset=queryset) serializer = CitySerializer(instance=filterset.qs, many=True) return Response(serializer.data) filter.py class FilterCity(filters.FilterSet): city = filters.CharFilter(lookup_expr='icontains') class Meta: model = City fields = [] Request URL there is no value. http://127.0.0.1:8000/api/search/?city= Response [ { "id": 1, "city": "aaa", }, { "id": 2, "city": "bbb", }, { "id": 3, "city": "ccc", } ] My hope is to return the string "Not Found" or empty array[]. In that case, how should I implement it? Thank you. -
Why pagination provided by django rest framework is not consistent?
I am currently using Django-Rest framework to implement the API endpoints. I am following the documentation to implement the pagination, my pagination class is, class Pagination(PageNumberPagination): page_size = 10 page_size_query_param = 'page' I am using this class as follows:- class QuestionList(generics.ListAPIView): queryset = Question.objects.all().prefetch_related('tags').order_by('id') serializer_class = QuestionSerializer pagination_class = Pagination For the first page, i am getting objects from id 1 to 10 which is expected. But from second page onwards, i am only getting 2 objects per page(id 3 and 4 for second page) and i cannot find any reason behind this strange behaviour. What should i do to make the pagination consistent. -
Flutter and Python Full Stack Solution with Cloud
I am interesting in building a solution for a Platform, knowing only Flutter and Python + Some SQL. Currently my thinking is towards having SQL/NoSQL DB (or via Cloud Provider's DB service), driven with Django RestAPI, and Frontend driven by Flutter. I am now sure how it would come together, hence asking advices on how the Stack Solution should be setup and whether there will be other languages I should learn? -
Accessing values in a JSON array and then assigning it to a textfield
My question is very simple. By using the DjangoJSONEncoder, I am able to send a JSON array of Model instances with the fields, product_number(pk) and amount as context to the HTML file. I then access the JSON array obj using some javascript code. The JS code: {{ data|json_script:"hello-data" }} <script type="text/javascript"> const data = JSON.parse(document.getElementById('hello-data').textContent); document.getElementById('id_line_one').onchange = function(event){ alert(data); document.getElementById('id_line_one_unit_price').value = data[event.target.value].fields.amount }; </script> The array is: [[1, 56000], [2, 55000]] I think it's a string and not an array? I have a dropdown box and when the user selects a title from the dropdown menu, It returns the primary key of that title, and then using that, I want to retrieve the amount of that product from the JSON array and then set the value of a text field with that amount. views.py: def add_invoice(request): form = InvoiceForm(request.POST or None) total_invoices = Invoice.objects.count() queryset = Invoice.objects.order_by('-invoice_date')[:6] dataa = Inventory.objects.values_list('product_number','amount') data = json.dumps(list(dataa), cls=DjangoJSONEncoder) if form.is_valid(): form.save() messages.success(request, 'Successfully Saved') return redirect('/invoice/list_invoice') context = { "form": form, "title": "New Invoice", "total_invoices": total_invoices, "queryset": queryset, "data": data, } return render(request, "entry.html", context) models.py: from django.db import models class Inventory(models.Model): product_number = models.IntegerField(primary_key=True) product = models.TextField(max_length=3000, default='', blank=True, null=True) title = models.CharField('Title', … -
Django Project in Visual Studio Community 2022 Edition
How to fix the python interpreter within Vs Community 2022 edition for Django project? After creating a project, created an environment. Within the environment, I've updated the Django version to 4.0.6 some days back. But today noticed that runserver shows Django version as 4.0.5 Need to know if the Visual Studio Community 2022 edition picks any other interpreter than the one created. Unable to figure it as google shows details for changing interpreter only with VS Code. Attaching the images for ref, Created Environment Default interpreters DjangoVersion in runserver -
Pass custom request header from views.py to models.py
I am receiving a customer header with the post request on views which I am able to access using request.META. I want to now pass this header to my data model as I need to check if this header is a particular string, then a particular action must not be performed i.e. the post save signal on the data model should be muted. -
How do object-relational databases store their data?
I use Django ORM, which according to objects creates tables in a database. I would like to more accurately understand the transformation process in order to create more effective data storage facilities. Unfortunately, I havn't found such information anywhere. -
Uncaught TypeError: data.find is not a function
I am trying to convert the model instances into a JSON object and then according to the value selected in the dropdown menu, I want to assign its amount to the line_one_unit_price text field in the form. Javascript code: {{ data|json_script:"hello-data" }} <script type="text/javascript"> const data = JSON.parse(document.getElementById('hello-data').textContent); document.getElementById('id_line_one').onchange = function(event){ let elementInData = data.find(() => item.pk == event.target.value); document.getElementById('id_line_one_unit_price').value = elementInData && elementInData.amount ? elementInData.amount : 0; }; </script> I guess, I am getting the error at data.find because .find is used on an array whereas the constant data is not an array? How do I convert that JSON object into an array? how do I assign the amount of the title selected in the forms to the line_one_unit_price? When I click some title from the dropdown, I want the amount to be displayed in the Unit Price. views.py: def add_invoice(request): form = InvoiceForm(request.POST or None) data = serializers.serialize("json", Inventory.objects.all()) total_invoices = Invoice.objects.count() queryset = Invoice.objects.order_by('-invoice_date')[:6] if form.is_valid(): form.save() messages.success(request, 'Successfully Saved') return redirect('/invoice/list_invoice') context = { "form": form, "title": "New Invoice", "total_invoices": total_invoices, "queryset": queryset, "data": data, } return render(request, "entry.html", context) models.py: class Inventory(models.Model): product_number = models.IntegerField(primary_key=True) product = models.TextField(max_length=3000, default='', blank=True, null=True) title = models.CharField('Title', max_length=120, … -
Having trouble with this error ErrorDetail(string='Incorrect type. Expected pk value, received str.', code='incorrect_type')
I am tasked to do this with serializers and foreign keys and I am new to this concept and doing a CRUD where I am struggling with this error: "ErrorDetail(string='Incorrect type. Expected pk value, received str.', code='incorrect_type')" model class Products(models.Model): categories = models.ForeignKey(Categories,on_delete=models.CASCADE) sub_categories = models.ForeignKey(SUBCategories,on_delete=models.CASCADE) color = models.ForeignKey(Colors,on_delete=models.CASCADE) size = models.ForeignKey(Size,on_delete=models.CASCADE) # image = models.ImageField(upload_to = 'media/',width_field=None,height_field=None,null=True) title = models.CharField(max_length=50) price = models.CharField(max_length=10) sku_number = models.CharField(max_length=10) product_details = models.CharField(max_length=300) quantity = models.IntegerField(default=0) isactive = models.BooleanField(default=True) insert function def insert(request): if request.method == "POST": print('POST',id) insert_clothes = {} insert_clothes['categories']=request.POST.get('categories') insert_clothes['sub_categories']=request.POST.get('sub_categories') insert_clothes['color']=request.POST.get('color') insert_clothes['size']=request.POST.get('size ') # insert_clothes['image']=request.POST.get('image') insert_clothes['title']=request.POST.get('title') insert_clothes['price']=request.POST.get('price') insert_clothes['sku_number']=request.POST.get('sku_number') insert_clothes['product_details']=request.POST.get('product_details') insert_clothes['quantity']=request.POST.get('quantity') print("insert clothes:",insert_clothes) serializer = POLLSerializer(data = insert_clothes) print('form:',serializer.initial_data) if serializer.is_valid(): serializer.save() messages.success(request,'Record Updated successfully :)!!!!') return redirect('polls:show') else: print("invalid") print("error of serializer:",serializer.errors) return redirect('polls:insert') else: print('GET',id) return render(request,'polls/product_insert.html') Can someone tell me how I am supposed to call thier IDs?thanks -
Running Test Cases in Django, just like testcases in leetcode, codesignal and codewar
Does anybody knows, how we can run test cases on a data(function) sent by the user in Django, (as implemented by leetcode, codesignals and codewar) -
AttributeError at /invoice/add_invoice/ 'int' object has no attribute '_meta' while using in_bulk
I want to convert the model instances into a JSON object and then pass it to the HTML file. However, I get an AttributeError at this line: data = serializers.serialize("json", Inventory.objects.in_bulk()) The full views.py: def add_invoice(request): form = InvoiceForm(request.POST or None) data = serializers.serialize("json", Inventory.objects.in_bulk()) total_invoices = Invoice.objects.count() queryset = Invoice.objects.order_by('-invoice_date')[:6] if form.is_valid(): form.save() messages.success(request, 'Successfully Saved') return redirect('/invoice/list_invoice') context = { "form": form, "title": "New Invoice", "total_invoices": total_invoices, "queryset": queryset, "data": data, } return render(request, "entry.html", context) The Javascript code: {{ data|json_script:"hello-data" }} <script type="text/javascript"> const data = JSON.parse(document.getElementById('hello-data').textContent); document.getElementById('id_line_one').onchange = function(event){ document.getElementById('id_line_one_unit_price').value = data[event.target.value].fields.amount; }; </script> models.py: class Inventory(models.Model): product_number = models.IntegerField(primary_key=True) product = models.TextField(max_length=3000, default='', blank=True, null=True) title = models.CharField('Title', max_length=120, default='', blank=True, unique=True) amount = models.IntegerField('Unit Price', default=0, blank=True, null=True) def __str__(self): return self.title How can I pass that JSON object and assign the amount value to the text field according to the object selected in the dropdown? Thanks -
Django nginx staticfiles 404
I am trying to get my head around nginx serving Dockerized Django static files behind a https proxy. I was trying to mostly follow this tutorial: https://testdriven.io/blog/django-lets-encrypt/ This was all working on my local machine so I moved to a remote server running at a real domain behind an https reverse-proxy. I have a docker-compose.yml like this: backend: ... volumes: - ./backend/:/code/ - static_volume:/code/staticfiles - media_volume:/code/mediafiles ... nginx-proxy: ... volumes: - static_volume:/code/staticfiles - media_volume:/code/mediafiles ... depends_on: - backend I have a default file in vhost.d directory with the following directives: location /static/ { alias /code/staticfiles/; add_header Access-Control-Allow-Origin *; } location /media/ { alias /code/mediafiles/; add_header Access-Control-Allow-Origin *; } my nginx docker files is the following: FROM jwilder/nginx-proxy:0.9 COPY vhost.d/default /etc/nginx/vhost.d/default COPY custom.conf /etc/nginx/conf.d/custom.conf my Django settings.py: STATIC_URL = '/static/' STATIC_ROOT = BASE_DIR / 'staticfiles' I am collecting the files at backend boot and if I exec to either the backend or nginx-proxy services I can find my files at the correct location: /code/staticfiles/... # all the files are here in the right place... So I "assume" the volumes are correct. /vhosts.d/default is also present and at the correct location when i log into the nginx service. The HTTPS reverse-proxy works … -
Using django and react together
I'm making an SSR website using Django, Gunicorn, and Nginx. As I'm familiar with react and I'd like to use some of its libraries like redux, tailwind with daisyui, etc... it would be great if I could use React for the frontend and Django for the backend. I am aware I can use Django just as a rest framework and then run react separately as a CSR, SSG app, or even ssr using something like nextjs but my goal is to keep most of the react functionality, share the codebase, use Django to render the react pages essentially as a replacement for react-router, and optimize SEO. I was wondering what the best way to integrate them is? I know generally, it's common to separate react and Django but I'd like to use Django as the router/renderer for the react app as I believe it would be more performant to use one server for both the API and the website. I also plan on using django-hosts to render the react templates in two Django apps with different hostnames. Note: I don't need to be able to use the normal django templating -
Best django fieldtype(postgres datatype) to save python hashlib hexdigest (40 characters)
What is the best field type in django to save a fixed length (40 characters) hexdigest? This field is indexed and needs to be optimized for storage and querying. Currently we use CharField but doesn't seem to be optimal as this is varchar class MyModel(models.Model): ... my_field = models.CharField(max_length=40, null=True) class Meta: indexes = [models.Index(fields=["my_field"])] -
Any reason that .distinct() is outputting multiple rows? - Django/PostgreSQL
Is there any reason that this query Finances.objects.order_by('payout').distinct('payout') is still returning multiple rows? It returns 3 rows. I have an aggregate function getting the sum of the rows in the database. That looks like this: @property def Calculate_bank(self): totalpayout = Finances.objects.all().aggregate(Sum('payout'))['payout__sum'] or 0.00 totalwithdraw = Finances.objects.all().aggregate(Sum('withdraw'))['withdraw__sum'] or 0.00 totalbank = totalpayout - totalwithdraw return totalbank @property def Calculate_cash(self): totalwithdraw = Finances.objects.all().aggregate(Sum('withdraw'))['withdraw__sum'] or 0.00 totalcash = Finances.objects.all().aggregate(Sum('cash'))['cash__sum'] or 0.00 totalbank = totalwithdraw - totalcash return totalbank I then use the Finances.objects.order_by('payout').distinct('payout') query in view.py and it displays three rows of the same output? If I add more order_by or distinct filters, it duplicated the three rows already showing. I have tried filtering by id as well. If I do not use the distinct, it shows a new row for everytime there is an entry in the database. -
Django Add Custom Attributes to Model Fields
I have a model with a large number of fields that store float values: class Report(models.Model): field1 = models.Floatfield(...) field2 = models.Floatfield(...) ... The fields need to be able to have public-facing names that differ based on who is using it. For example, field1 might be named "Apples" for one user, but should display "Bananas" for another. I know that FloatField has a verbose_name option, but it seems like it has to be hardcoded and is not able to be dynamic. It is ideal for our setup that this is stored as data is written to the database. What is the best practice for setting something like this up? Is it best to use a custom field and add attributes? Do these attributes save when the model object is created? -
Not being redirected to the redirect_uri in live server | Spotipy
I am using Django and when I run a local server at localhost:8000, this piece of code works as intended: spotipy.Spotify( auth_manager=SpotifyOAuth( redirect_uri=config["REDIRECT_URI"], client_id=config["SPOTIPY_CLIENT_ID"], client_secret=config["SPOTIPY_CLIENT_SECRET"], scope="user-library-read user-library-modify playlist-modify-private playlist-modify-public", cache_handler=spotipy.DjangoSessionCacheHandler(request), ) ).current_user() It redirects me to http://localhost:8080/callback and fetches all the data by itself and caches the received token. But when I do the same on a live server, it doesn't redirect me and the bash asks me to input the URL I have been redirected to. I even tried including a false redirect_uri but it still asks me for the URL I have been redirected to. I have no idea what I am doing wrong, any help is appreciated. -
Making Javascript files private in Django Project
I am following a tutorial to integrate Apple Pay payments (w/ Stripe) into my website using Javascript to process the payments. The Javascript file renders the Apple Pay Button as well as actually processing the payment. I need to pass a secret key into one of the functions, but the file is public b/c its in my static folder. What can I do to either make the Javascript file private or at least make some of the functions private so I don't need to worry about hackers stealing my key from the static files? -
Django and Javascript. Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
Tengo un formulario el cual al momento de enviarlo, recibo la información por javascript para realizar una serie de validaciones y enseguida por fetch envió la información al servidor (una api sencilla creada con django). El código cuando lo trabajaba en un etorno de desarrollo funcionaba correctamente pero ahora que lo trabajo en un entorno de producción y lo desplegué en heroku me da el error. El código es el siguiente: formulario.addEventListener('submit', (e) => { e.preventDefault(); fetch('https://portafolioadrian.herokuapp.com/contacto', { method: 'POST', body: JSON.stringify({ nombre: document.querySelector('#nombre').value, correo: document.querySelector('#correo').value, telefono: document.querySelector('#telefono').value, mensaje: document.querySelector('#form__message').value, terminos : document.getElementById('terminos').checked, }), headers: { 'X-CSRFToken': getCookie('csrftoken'), "Accept": "application/json", 'Content-Type': 'application/json'} }) .then(res => res.json()) .then(res => { if (res.success) { formulario.reset(); document.getElementById('form__message-success').classList.add('form__message-success-active'); setTimeout(() => { document.getElementById('form__message-success').classList.remove('form__message-success-active'); }, 5000); document.querySelectorAll('.form__group-correct').forEach((icono) => { icono.classList.remove('form__group-correct'); }); }else{ document.getElementById('form__message').classList.add('form__message-active'); } }) }); Al momento de enviarlo, por consola me da el siguiente error Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 El urls.py de la app es esta: urlpatterns = [ path('', views.contacto, name='contacto'), path('mensajes/', views.mensajes, name='mensajes'), ] Y la view es la siguiente: def contacto(request): if request.method == "POST": data = json.loads(request.body) nombre = data['nombre'] correo = data['correo'] telefono = data['telefono'] mensaje = data['mensaje'] terminos = data['terminos'] … -
Searching by multiple categories in Django
Hi everyone! I want search by multiple categories, but my code is not working. When I type categories name, I got nothing. Can anyone help me? '''views.py''' class ExpenseListView(ListView): model = Expense paginate_by = 5 def get_context_data(self, *, object_list=None, **kwargs): queryset = object_list if object_list is not None else self.object_list form = ExpenseSearchForm(self.request.GET) if form.is_valid(): name = form.cleaned_data.get('name', '').strip() if name: queryset = queryset.filter(name__icontains=name) return super().get_context_data( form=form, object_list=queryset, summary_per_category=summary_per_category(queryset), get_per_year_month_summary=get_per_year_month_summary(queryset), **kwargs) def get_queryset(self): queryset = super(ExpenseListView, self).get_queryset() q = self.request.GET.get("q") if q: return queryset.filter(date__icontains=q) return queryset def get_gategory(request, pk_test): category = Category.objects.get(id=pk_test) orders = category.order_set.all() order_count = orders.count() myFilter = OrderFilter(request.GET, queryset=orders) orders = myFilter.qs context = {'category': category, 'orders': orders, 'order_count': order_count, 'myFilter': myFilter } return render(request, 'expense_list.html',context) '''May be my problem is in my vieews or in models. I m new in Django and dont nkow many things..''' ''' Here my models.py''' class Category(models.Model): class Meta: ordering = ('name',) name = models.CharField(max_length=50, unique=True) def __str__(self): return f'{self.name}' class Expense(models.Model): class Meta: ordering = ('-date', '-pk') category = models.ForeignKey(Category, models.PROTECT, null=True, blank=True) name = models.CharField(max_length=50) amount = models.DecimalField(max_digits=8, decimal_places=2) date = models.DateField(default=datetime.date.today, db_index=True) def __str__(self): return f'{self.date} {self.name} {self.amount}' '''html'' {% extends "base.html" %} {% block content %} <a … -
How do I configure my Django server to avoid Firefox "Response body is not available to scripts (Reason: CORS Missing Allow Header)" errors?
I'm running Django 3.2, Python 3.9 and trying to execute a fetch request in Firefox. Specifically, this OPTIONS request curl 'http://localhost:8000/login' -v -X OPTIONS -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:102.0) Gecko/20100101 Firefox/102.0' -H 'Accept: */*' -H 'Accept-Language: en-US,en;q=0.5' -H 'Accept-Encoding: gzip, deflate, br' -H 'Access-Control-Request-Method: POST' -H 'Access-Control-Request-Headers: content-type' -H 'Referer: http://localhost:3000/' -H 'Origin: http://localhost:3000' -H 'Connection: keep-alive' -H 'Sec-Fetch-Dest: empty' -H 'Sec-Fetch-Mode: cors' -H 'Sec-Fetch-Site: same-site' -H 'Pragma: no-cache' -H 'Cache-Control: no-cache' returns this error in Firefox Response body is not available to scripts (Reason: CORS Missing Allow Header) I'm not sure what Firefox is complaining about. When I run the above request in curl, I get these headers * Trying ::1... * TCP_NODELAY set * Connection failed * connect to ::1 port 8000 failed: Connection refused * Trying 127.0.0.1... * TCP_NODELAY set * Connected to localhost (127.0.0.1) port 8000 (#0) > OPTIONS /login HTTP/1.1 > Host: localhost:8000 > User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:102.0) Gecko/20100101 Firefox/102.0 > Accept: */* > Accept-Language: en-US,en;q=0.5 > Accept-Encoding: gzip, deflate, br > Access-Control-Request-Method: POST > Access-Control-Request-Headers: content-type > Referer: http://localhost:3000/ > Origin: http://localhost:3000 > Connection: keep-alive > Sec-Fetch-Dest: empty > Sec-Fetch-Mode: cors > Sec-Fetch-Site: same-site … -
Is there a way to keep Javascript files private in a Django project?
I have a Django project where I would like to accept Apple Pay payments. I followed a tutorial that uses Stripe with Javascript to process the payments. The Javascript is responsible for rendering the Apple Pay button, as well as using several functions to actually process the payment. Naturally, my javascript file ended up being public because it was in my static folder. However, I need to pass a secret key into one of these functions. Is there a way I can rearrange my project so that the Javascript file is private? Alternatively, is there a way to make some of my functions private so that I don't have to worry about hackers stealing my key from my static files? -
Django query returns multiple rows of Sum, I only want to display one row
currently the way I have the code written is that I have a model named Finances. I have an aggregate set up so it sums up all of the rows. I am trying to display the outcome of the rows, but when I do it displays a row for every database entry. I understand that I am grabbing all with .all() in the viewpayout = Finances.objects.all() in views.py, but I am unsure of how this should be written to only display one row. How would I display only one row that sums up all of the rows for a column? Any help is greatly appreciated! Below is my code: views.py def finances(request): viewpayout = Finances.objects.all() updatepayout = UpdatePayout() updatewithdraw = UpdateWithdraw() updatecash = UpdateCash() if request.method == "POST": if 'add_payout' in request.POST: updatepayout = UpdatePayout(request.POST) if updatepayout.is_valid(): post = updatepayout.save(commit=False) post.save() return redirect("/finances") else: updatepayout = None if 'bank_withdraw' in request.POST: updatewithdraw = UpdateWithdraw(request.POST) if updatewithdraw.is_valid(): post = updatewithdraw.save(commit=False) post.save() return redirect("/finances") else: updatewithdraw = None if 'add_cash' in request.POST: updatecash = UpdateCash(request.POST) if updatecash.is_valid(): post = updatecash.save(commit=False) post.save() return redirect("/finances") else: updatecash = None return render(request, 'portal/finances.html', {"updatepayout": updatepayout, "updatewithdraw": updatewithdraw, "updatecash": updatecash, "viewpayout": viewpayout}) model.py class Finances(models.Model): payout …