Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Custom Queryset constructor loses value of argument
Django. I want to prevent my future self from overwriting a certain property of the Cable class in the database. I wrote a custom Django QuerySet that accepts a field name in the constructor and which will prevent updates on that field. However, in the constructor, the argument field_name is well received (as evidenced by the correct output from print), but then the Exception is also raised, meaning that the variable was instantly changed to None. What devilry? Note I also tried putting *args in the constructor signature. class PreventChangeQuerySet(models.QuerySet): def __init__(self, field_name, **kwargs): self._field_name = field_name print(f"Field name: {self._field_name}") if self._field_name is None: print(self._field_name) raise Exception("A field name must be set") self._field_name = field_name super().__init__(**kwargs) def update(self, *args, **kwargs): if kwargs.get(self._field_name): raise Exception("This field may not be updated") super().update(*args, **kwargs) class Cable(models.Model): __original_short_name = None # For keeping track of changes objects = PreventChangeQuerySet(field_name="short_name").as_manager() output: ./manage.py shell_plus Field name: short_name Traceback ... TypeError: __init__() missing 1 required positional argument: 'field_name' -
Django stripe.error: Invalid card object: must be a dictionary or a non-empty string
I am trying to take a Stripe payment but I get an InvalidRequestError everytime I try to make a payment. The payment is for a set amount of 5 Euros. I am using the credit card number 4242 4242 4242 4242 to test the payment. My form is valid, but when it sends the payment request to Stripe I get the errors and it looks like stripe_id is blank. Any ideas? checkout.html: {% extends "base.html" %} {% load static from staticfiles %} {% load bootstrap_tags %} {% block head_js %} <script type="text/javascript" src="https://js.stripe.com/v2/"></script> <script type="text/javascript" src=""> //<![CDATA[ Stripe.publishableKey = '{{ publishable }}'; // ]]> </script> <script type="text/javascript" src="{% static 'js/stripe.js' %}"></script> {% endblock %} {% block content %} <form action="{% url 'checkout' %}" method="post" id="payment-form" class="col-md-6 col-md-offset-3"> <legend>Payment Details</legend> <div id="credit-card-errors" style="display: none;"> <div class="alert-message block-message error" id="stripe-error-message"></div> </div> <div class="form-group col-md-6"> {{ payment_form|as_bootstrap }} </div> {% csrf_token %} <div class="form-group col-md-12"> <input class=" btn btn-primary" id="submit_payment_btn" name="commit" type="submit" value="Submit Payment of 5 Euros"> </div> </form> {% endblock %} forms.py: from django import forms class MakePaymentForm(forms.Form): print("MakePaymentForm...") MONTH_CHOICES = [(i, i) for i in range(1, 12)] YEAR_CHOICES = [(i, i) for i in range(2019, 2040)] credit_card_number = forms.CharField(label='Credit Card Number', … -
Is there any option to filter data by model's filed in django python?
I am new to Django, Is there any option to display data by choice? I am able to filter by category but I have to filter by choices or model's field. Or is there any option to multiple filters in one template? Or can we filter by using two foreign keys in one model? Here is my Product model where I have used filed (member) for the filter but I could not do that then I have used another model for the filter. class Product(models.Model): MEMBER = ( ('For Kids', 'For Kids'), ('For Lover', 'For Lover',), ('For Teacher', 'For Teacher'), ('For Boss', 'For Boss'), ) category = models.ForeignKey(Category, related_name='products', on_delete=models.PROTECT) member = models.CharField(max_length=200,choices = MEMBER) title = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True) image = models.ImageField(upload_to='products/%d/%m/%Y', blank =True) description = models.TextField(blank=True) price = models.IntegerField(default=0) stock = models.PositiveIntegerField() available = models.BooleanField(True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: ordering = ('-title',) index_together = (('id','slug'),) def __str__(self): return self.title and my category model : class Category(models.Model): title = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True, unique=True) image = models.ImageField(upload_to='products/%d/%m/%Y', blank =True) parent = models.ForeignKey('self',blank=True, null=True ,related_name='children', on_delete=models.PROTECT) class Meta: unique_together = ('slug', 'parent',) ordering = ('title',) verbose_name = 'category' verbose_name_plural = 'categories' … -
ajax call returns 'undefined' during first call only
i am trying to make a desktop like text input help using datatable.in table with keyboard navigation. For that i am dynamically changing the source and also change the header column. So far i have succeeded in that except getting dynamic column header. For getting the column header based on the text input header, i am making an ajax call and getting the list of column header. the issue is during first call ajax returns 'undefined' but in the second call it shows the value. i understand this is pertaining to the asynchronous call but not sure how to handle this. Below is my code snips. AJAX call in external .js **function ajaxCall(ipUrl, callType = "POST", dataIn) { return $.ajax({ url: ipUrl, type: callType, data: dataIn, dataType: "json", success: function (response) { retData = response.data; alert('success'+ retData); return retData; }, error: function (err) { alert("fail" + JSON.stringify(err)); }, //error }); //alert('in js'+ retData); //return retData; }** HTML Script tag **$("#btn").click( function (e) { var tData = { action: 'getHeader', csrfmiddlewaretoken: 'Gys4TSx3ODJLcMDuXlSvS7DopVZr1HWEDLg9AlJsARXp7wmUGAxxKwo6uLVXIrf2', } tmp = ajaxCall('dyncolheader','GET',tData) ; if (tmp == undefined) { alert('second call'); tmp = ajaxCall('dyncolheader','GET',tData) ; alert('tmp' + tmp); } else { alert('else' + tmp); } });** Django View … -
How to ignore a postgresql generated field in Django Admin update queries
I have this model in Django: class Job(models.Model): id = models.BigAutoField(primary_key=True) start_time = models.DateTimeField(blank=True, null=True) end_time = models.DateTimeField(blank=True, null=True) run_time = models.IntegerField(editable=False, blank=True) The run_time field is a generated field in Postgresql and calculates the difference between end_time and start_time. I set it up here as editable=False. If create an Admin page for this, whenever i want to create or change a "job" i get this error ProgrammingError at /admin/model/job/1/change/ column "run_time" can only be updated to DEFAULT DETAIL: Column "run_time" is a generated column. Please note the field has editable=False I have tried many options: class JobAdmin(admin.ModelAdmin): fields = [ 'start_time','end_time'] exclude = ('run_time',) readonly_fields = ('run_time',) use_on_insert = [ 'submit_time', 'start_time'] use_on_update = [ 'submit_time', 'start_time'] I am still getting the error. How can I ignore the run_time field from the update and insert queries? -
Check if value of selected option is valid
I am very much a beginner at testing and defensive design so apologies in advance if my attempt seems naive. One of the fields in my form is a ModelChoiceField and renders a select widget with options based on the objects in the queryset. In dev tools a user could change the value of the selected option and click submit. Is there a way to protect from this and send an error in the template, the same way an emailchoicefield would flag a valid email format in an EmailInput? So far I have this in my form class (form.py ) but it doesnt work: def clean_destination(self): """ Validation to see that inputted date is from the queryset """ destination = self.cleaned_data.get('destination') if not Destination.objects.get(pk=destination) raise forms.ValidationError("This is not a valid option") return destination -
Django_Tables2 Accessor / Related Fields
I have the following constellation of Tables, which are linked via FK's: (omitted a few fields for better readability) class ProductDetail(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) product_detail = models.CharField(max_length=100, primary_key=True, verbose_name='Product Detail Name') materialcode = models.CharField(max_length=20, blank=False, null=False, verbose_name='Material-Code') billing_model = models.ForeignKey(BillingModel, on_delete=models.CASCADE) .... -------------- class MinimumRevenue(models.Model): operator = models.ForeignKey(Operator, on_delete=models.CASCADE) billing_model = models.ForeignKey(BillingModel, on_delete=models.CASCADE) minimum_revenue = models.DecimalField(decimal_places=2, max_digits=20, verbose_name='Minimum Revenue') currency = models.ForeignKey(Currency, on_delete=models.CASCADE) product_detail = models.ForeignKey(ProductDetail, on_delete=models.CASCADE, verbose_name='Product Detail') event_type_assignment = models.CharField(max_length=100, verbose_name='Event Type Assignment') start_date = models.DateField(blank=False, null=False, verbose_name='Start Date', default=get_first_of_month) end_date = models.DateField(blank=False, null=False, verbose_name='End Date') .... And a Table (Django_Tables2) which points to the MinimumRevenue Model (which works as designed), now I would like to also show some more related fields in my Table: class MinimumRevenueTable(tables.Table): edit = tables.LinkColumn('non_voice:minimum_revenue_update', orderable=False, text='Edit', args=[A('pk')]) invoice_text = tables.TemplateColumn( '<data-toggle="tooltip" title="{{record.context}}">{{record.invoice_text|truncatewords:2}}') start_date = tables.DateColumn(format='Y-m-d') end_date = tables.DateColumn(format='Y-m-d') foreigncolumn = tables.Column(accessor='productdetail.materialcode') class Meta: model = MinimumRevenue template_name = "django_tables2/bootstrap4.html" fields = ('operator', 'billing_model', 'minimum_revenue', 'product', 'product_detail', 'event_type_assignment', 'start_date', 'end_date', 'invoice_text', 'currency', 'foreigncolumn') attrs = {'class': 'table table-hover', } The foreigncolumn column is never filled, just showing '-', I also tried it with other columns of ProductDetail, but never get any result, would really appreciate any solutions! -
Printing an ERD for an specific Django app
I've had good results using the django-extensions package, more specificaly, the graphviz module. It allows to print the full cover of entities. What I couldn't do yet, is to print only some specific apps or the related entities with only one model. Already tried the documentation instruction: $ python manage.py graph_models foo bar -o specific_app_erd.png But without the expected result, only mapping the complete structure of entities, not the isolated ones. I've already tried different inputs for the app_name_arg: the name from installed_apps, the relative.path.from.base_dir, but couldn't get the selected one yet. -
Django - dynamic model for TemplateView class-based
I want to switch between two models depending on which route I am in. I am overwriting get_queryset() function to return the correct model: class DynamicModelView(TemplateView, PageDescriptionListingMixin): model = None template_name = 'dynamic_model.html' context_object_name = "accounts" def get_context_data(self, **kwargs): context = super(DynamicModelView, self).get_context_data(**kwargs) self.add_page_text_to_context(context) return context def get_queryset(self): if '/dynamic_user/' in self.request.path: model = UserAccount else: model = AdminAccount return model.objects.first() As you can see in get_context_data I am injecting an object in context for AdminAccount but inside template I can't see it! in fact if I changed model from None to AdminAccount then it appears which I want that to happen dynamically. -
Integrate Intro.js with Django
I use Intro.js in a Django website. The Intro.js is used on the navigation bar which appears and stuck on every page. <html> <script type="text/javascript"> $("#description").click(function (e) { e.preventDefault(); introJs().start(); }); </script> <style> #navigation-bar { /* position: -webkit-sticky; */ position: sticky ; width: 100%; top: 0px; background-color: #93C1DB; z-index: 9999; } </style> <div id="navigation-bar"> <a href="{% url 'AAA_page' %}" data-intro="This is AAA" data-step="1">AAA</a> <a href="{% url 'BBB_page' %}" data-intro="This is BBB" data-step="2">BBB</a> <a href="{% url 'CCC_page' %}" data-intro="This is CCC" data-step="3">CCC</a> </div> {% block content %}{% endblock %} </html> If the attribute for the position is "-webkit-sticky", then words can be displayed, but the navigation bar will not fix at the top, it will move up to exit the page while scrolling down the page: If the attribute for the position is "sticky", then the navigation will fix at the top while scrolling down the page, but the text will be covered: My objective is to make the text can be displayed and the navigation is fixed on the top when scrolling down the page. Could you give me any suggestion, thank you! -
django react authentication token
I am building a react-native app with Django backend, could someone suggest a Django authentication token tutorial for sign in and signup, since I am new to Django and I got confused among all the youtube tutorials! -
ValueError in models.py
Here is my models.py file. When I try to migrate it gives me an error. I changed Class name and it gives me an error. Now if I put even old name, it gives me the same error from django.db import models from tinymce.models import HTMLField class BlockTags(models.Model): pass class BlockTags_Text(models.Model): text = models.CharField(max_length=300, verbose_name='Заголовок 1', null=True, blank=True) block = models.ForeignKey(BlockTags, related_name="text", verbose_name='Заголовок 1', on_delete=models.CASCADE, null=True,blank=True) number = models.DecimalField(max_digits=3, decimal_places=0) ValueError: The field content.BlockTags.text was declared with a lazy reference to 'content.blocktags_text', but app 'content' doesn't provide model 'blocktags_text'. (venv) appledeMacBook-Pro:letbuycar apple$ -
How can I sort a table by click event on a select menu. JavaScript
I queried the data from the database using Django and I displayed the data into a table. I made a select menu using HTML and jQuery and now I want to create a click event on this select menu. How can I do, for example, select "Order by date" in the select menu, and start an on click event on the table? Select menu - HTML, Materialize and jQuery <div class="row"> <div class="input-field col s2 offset-s1"> <select> <option value="" disabled selected>View</option> <option value="1">Display all</option> <option value="2">Order by date</option> <option value="3">Order by price</option> </select> </div> <script> $(document).ready(function(){ $('select').formSelect(); }); </script> Table <tbody> {% block content %} {% for f in fields %} <tr> <td>{{ f.date }}</td> </tr> {% endfor %} {% endblock %} </tbody> -
Django template return all files in section
Here my problem, The user can add Sections, in the section he can add documents, what I would like to do it's to return all documents added in section I can't figure it out which way is the best to filter by section: Here my model for the Documents : class Document(models.Model): """ Staff of the hospital center services """ # ATTRIBUTES label = models.CharField( max_length=255, verbose_name='Intitulé' ) description = models.TextField( verbose_name='Description', blank=True, null=True ) document = models.FileField( verbose_name='Document' ) section = models.ForeignKey( 'espace_documentaire.EspaceDocumentaire', verbose_name="Espace Documentaire", related_name="documents", null=True, blank=True, on_delete=models.CASCADE ) dedicated_page = models.ForeignKey( "pages.Pages", verbose_name="Page", related_name="documents", null=True, blank=True, on_delete=models.CASCADE ) division = models.ForeignKey( "services.Division", verbose_name="Pôle", related_name="documents", null=True, blank=True, on_delete=models.CASCADE ) order = models.IntegerField( verbose_name="Ordre d'affichage", default=0 ) # TRACE date_created = models.DateTimeField( verbose_name="date de création", auto_now=True ) date_updated = models.DateTimeField( verbose_name="date de modification", auto_now=True ) def __str__(self): return self.section Here my Model for the Sections : class EspaceDocumentaire(models.Model): # ATTRIBUTES section = models.CharField( max_length=255, verbose_name='Nom de la section' ) colorsection = models.CharField( max_length=255, verbose_name='Couleur de la section' ) order = models.IntegerField( verbose_name="Ordre d'affichage", default=0 ) document = models.ForeignKey( 'documents.Document', verbose_name="Document", related_name="documents", null=True, blank=True, on_delete=models.CASCADE ) def __str__(self): return self.section Here my template : {% for ed in espace_documentaire %} … -
How to insert nested json data in all related table in django
I'm using Django REST framework, I'm stuck in Inserting this data into all related table. Please tell me how to insert all the data together in all related tables. I want to do that color should go to the color table, same for size in size table, same for variations in the variation table and the rest of the data should go to the product table. Json Data { "category": 15, "images": [ {"image_url": "https://images/1607679352290_0f32f124a14b3e20db88e50da69ad686.jpg", "main_image": true}, {"image_url": "https://images/1607679352290_0f32f124a14b3e20db88e50da69ad686.jpg", "main_image": false} ], "keywords": "leaxon", "long_description": "<p>l</p>", "mrp_price": "120", "selling_price": "908", "short_description": "<p>k</p>", "sku": "Sam-009", "stock": "7", "title": "Samsung", "have_variations": true, "variant": "Size-Color", "slug": "samsung-phone", "variations": [ { "image_url": "https://images/607679417554_0f32f124a14b3e20db88e50da69ad686.jpg", "mrp_price": 68, "selling_price": 86786, "sku": "iuy", "stock": 68768, "title": "hkj", "color": "red", "size": 9 }, { "image_url": "https://images/607679434082_0392bab5c6a3ec64552ea57aa69852a5.jpg", "mrp_price": 67, "selling_price": 6876, "sku": "hkjh", "stock": 868, "title": "yiui", "color": "blue", "size": 9 } ] } Models.py from django.db import models # Create your models here. from django.urls import reverse # Category table class Category(models.Model): title = models.CharField(max_length=50, default='') keywords = models.CharField(max_length=255, default='') description = models.TextField(max_length=255, default='') slug = models.SlugField(unique=False, default='') parent = models.ForeignKey('self', on_delete=models.SET_NULL, blank=True, null=True, related_name='children') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: db_table = 'product_category' ordering = ['-created_at'] … -
Creating importer service for Django
We run a medium-sized data-related website using Django. Previously, we imported new data from csv files. Now, these new data are pushed to us via an API. We need to update our software accordingly. Our importer service performs ongoing GET requests to another server to fetch new data. In total, there will be six services that keep the connection alive, and which may not interfere with our website that should keep running. We expect roughly 100 updates per second. We have thought of the following alternatives: Create software that only utilizes the ORM capability of Django and run it on a separate server/Docker virtualization. However, this raises the question how this can be done in a Pythonic manner. Any ideas or advice would be appreciated! -
How can I catch all 500 and above errors in DRF and log them?
I've looked through much of the SO responses regarding implementing this but I can't seem to find something that isn't deprecated or one that actually works for my use case. Basically, I have some API methods that return their own status codes. However, if for any reason there is a 500 Server Error or anything above 500 which indicates something strange happened (for example lets say the database connection got timeout), I want that to be logged to a file or e-mailed to an admin. I have tried using a custom exception handler but not all 500 errors are exceptions. So I resorted to writing custom middleware, which looked something like this class CustomApiLoggingMiddleware(MiddlewareMixin): def process_response(self, request, response): if response.path.startswith('/api/'): ...do stuff here The issue, however, is that there doesn't seem to be a status_code. To be frank I don't really know which response I'm actually getting. There's the 500 response returned by my API intentionally as a result of the API method, and there's the 500 response generated by Django in the backend if some kind of condition isn't met (let's say they sent a request without a proper header) I tried to generate a 500 response / error … -
my static(css , js)not loading in django sphinx project
i want to use sphinx in django .and i cant change directory (static).when i run server html is load but css & js not loading. /home/jojo/Documents/django/lolo/docs/sphinx/build/html/_static my settings BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) STATIC_ROOT = os.path.join(BASE_DIR, 'sphinx', 'build', 'html', '_static') STATIC_URL = '/_static/' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'sphinx', 'build', 'html')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] DEBUG = True ALLOWED_HOSTS = ['*'] and urls.py from django.contrib import admin from django.urls import path from auth_backends.urls import oauth2_urlpatterns from .views import DocsHandler urlpatterns = oauth2_urlpatterns + [ path('admin/', admin.site.urls), path('<doc_path>/', DocsHandler.as_view()), ] view.py is from django.http import HttpResponseNotFound from django.shortcuts import render from django.utils.translation import ugettext as _ from django.views.generic import View class DocsHandler(View): def get(self, request, doc_path): if not doc_path: doc_path = 'index.html' try: return render(request, doc_path) except: return HttpResponseNotFound(_('page not found')) and links in html file <script type="text/javascript" src="_static/js/modernizr.min.js"></script> <script type="text/javascript" id="documentation_options" data-url_root="./" src="_static/documentation_options.js"></script> <script type="text/javascript" src="_static/jquery.js"></script> <script type="text/javascript" src="_static/underscore.js"></script> <script type="text/javascript" src="_static/doctools.js"></script> <script type="text/javascript" src="_static/language_data.js"></script> <script type="text/javascript" src="_static/translations.js"></script> <script type="text/javascript" src="_static/js/theme.js"></script> <link rel="stylesheet" href="_static/css/theme.css" type="text/css" /> <link rel="stylesheet" href="_static/pygments.css" type="text/css" /> <link rel="stylesheet" href="_static/_themes/readthedocs-rtl/css/extra.css" type="text/css" /> docs main_app manage.py sphinx build html index.html ora.html _static css js _themes jquery.js … -
my testcases are failing in django for PUT and DELTE methods
i have build a basic crud api with django_rest_framework.when i write test cases for GET and POST it works fine ,But when i write test for PUT and Delete it gives me error. tests.py import json from django.urls import reverse from rest_framework.test import APITestCase from rest_framework import status from .models import Customer from .serializers import CustomerSerializer class PostCustomerTest(APITestCase): def test_post(self): data = { "name": "john", "address": "address", "phoneNumber": "2645662", "gstin": "26456", "outstandingbalance": 2356.26 } response = self.client.post("/api/",data) self.assertEqual(response.status_code,status.HTTP_201_CREATED) def test_get(self): response = self.client.get('/api',{},True) self.assertEquals(response.status_code,status.HTTP_200_OK) def test_put(self): data = { "name": "test", "address": "address", "phoneNumber": "2645662", "gstin": "26456", "outstandingbalance": .36 } response = self.client.put("/api/1/",data) serializer = CustomerSerializer(data) print(response.status_code) # self.assertEquals(response.data,serializer.data) self.assertEqual(response.status_code,status.HTTP_200_OK) def test_delete(self): response = self.client.delete("api/1/") self.assertEquals(response.status_code,status.HTTP_200_OK) views.py class CustomerView(APIView): def get_object(self, pk): try: return Customer.objects.get(pk=pk) except Customer.DoesNotExist: raise Http404 def get(self,request,format=None): cus = Customer.objects.all() serializer = CustomerSerializer(cus,many=True) return Response(serializer.data,status=status.HTTP_200_OK) def post(self,request,format=None): serializer = CustomerSerializer(data=request.data) if serializer.is_valid(): serializer.save() print("after Save") return Response({ 'Status':True, 'Message':"Customer Added Successfully", },status=status.HTTP_201_CREATED) return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST) def put(self, request, pk, format=None): customer = self.get_object(pk) serializer = CustomerSerializer(customer, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data,status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def delete(self, request, pk, format=None): customer = self.get_object(pk) customer.delete() return Response(status=status.HTTP_204_NO_CONTENT) models.py class Customer(models.Model): name = models.CharField(max_length=50) address = models.CharField(max_length=50) phoneNumber = … -
unable to insert form in template: 'WSGIRequest' object has no attribute 'get'
I try to insert form in template and get an error 'WSGIRequest' object has no attribute 'get'I don't understand my form (BillForm) is based on a model (Orders) and I just want to display one of it fields (split_bill) in my index template that is a table I have look for this error in documentation and here on stackoverflow but did not understand the issue... forms.py class BillForm(forms.ModelForm): class Meta: model = Orders fields = ['split_bill',] views.py def index(request): orders = Orders.objects.filter(paid = False) # only ongoing orders (not paid) if request.method == "POST": billform = BillForm(request, data=request.POST or None) if billform.is_valid(): billform.save() return redirect('home') else: billform = BillForm(request) return render(request, 'cafe/index.html', {'orders':orders,'billform':billform,}) index.html <div class='container'> <h1>Dashboard</h1> <table id="table_id" class="table table-stripped table-hover" style="width:100%"> <thead> <tr> <th>Order</th> <th>Table</th> <th>Date</th> <th>Served</th> <th>Bill</th> <th>Paiment</th> <th>Actions</th> </tr> </thead> <tbody> {% for order in orders %} <tr> <td data-toggle="tooltip" data-placement="top" title=""> {{ order.order_id }} </td> <td data-toggle="tooltip" data-placement="top" title=""> {{ order.table_id }} </td> <td data-toggle="tooltip" data-placement="top" title=""> {{ order.created_at|date:"D, d M, Y" }} </td> <td data-toggle="tooltip" data-placement="top" title=""> {% if order.delivered %} <a style="margin-right: 40px;color:black;" data-order="{{ order.order_id }}" class="served" href="#"><i class="fa fa-check-square" aria-hidden="true"></i></a> {% else %} <a style="margin-right: 40px;color:black;" data-order="{{ order.order_id }}" class="served" href="#"><i class="fa … -
GitHub MonoRepo Beanstalk CodePipeline Django
I'm playing around with Beanstalk to deploy a private website project. Currently, my project is organized in a Monorepo containing the frontend being vue.js and backend being Django. And looks like this: -.ebextension -django.config -.elasticbeanstalk -config.yml -frontend -... -backend -backend -settings.py -wgsgi.py -... -manage.py -... At first, I deployed the backend from inside the backend directory which worked great, but now I'm trying to change that to trigger the deployment from GitHub. The CodePipeline works in principle except for the last step, wheres about to start the application where it fails because it cannot find the application, as it is in a subdirectory. How can I reference the WSGIPath in a subdirectory? I tried now many combinations like ./backend/backend.wsgi etc. But not one is accepted. option_settings: aws:elasticbeanstalk:container:python: WSGIPath: backend/backend.wsgi:application <--Not found aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: backend.settings packages: yum: python3-devel: [] postgresql-devel: [] container_commands: 00_list: command: "ls && ls backend/" leader_only: true 01_start: command: "echo starting initialization" 02_makemigrations: command: "source /var/app/venv/staging-LQM1lest/bin/activate && cd backend/ && python manage.py makemigrations" leader_only: true 02_migrate: command: "source /var/app/venv/staging-LQM1lest/bin/activate && cd backend/ && python manage.py migrate" leader_only: true Thanks in Advance -
Inconsistent "contains" filter behaviour for jsonfield mysql/sqlite
I'm getting inconsistent results depending on the backend database when using jsonfield "contains" queries. from polymorphic.models import PolymorphicModel import jsonfield class Action(PolymorphicModel): new_object = jsonfield.JSONField(null=True) In another model I filter on this jsonfield, but I get different results. On sqlilite the following works: return Action.objects.filter( new_object__contains={"ref_id": self.id} ).order_by("-created_at")[:5] On mysql I have to do the following: return Action.objects.filter( new_object__contains=f"\"ref_id\": {self.id}" ).order_by("-created_at")[:5] So it seems to me in one environment it's deserialising the json into a dict, whereas the other keeps it as string.. Does anyone have a good way of handling this? Could there an issue with one of the configurations not lining up with the database? -
Search filter using Serializer with Django and Javascript
I want to populate my data to the table in my webpage but it gives an error as undefined in my rows And The data from my database is not being displayed in the table. How should i call the serialized data. Can anyone please help me with this. The output should look like the below: Column1 Column1 Column1 Column1 Column1 Column1 Column1 Column1 Column1 2011:abc salary 234 456 567 43 21 67 89 gia salary 56 678 654 432 345 436 789 others 123 234 456 567 765 478 987 total 56 78 98 09 76 54 56 2012:xyz salary 234 456 567 43 21 67 89 gia salary 56 678 654 432 345 436 789 others 123 234 456 567 765 478 987 total 56 78 98 09 76 54 56 2013-pqr .... . . . But my output is being displayed as below: Column1 Column1 Column1 Column1 Column1 Column1 Column1 Column1 Column1 undefined: undefined undefined undefined undefined undefined undefined undefined undefined undefined undefined undefined undefined undefined undefined undefined undefined undefined undefined undefined undefined undefined undefined undefined undefined undefined undefined undefined undefined undefined undefined undefined undefined undefined undefined: undefined undefined undefined undefined undefined undefined undefined undefined undefined undefined … -
Django: is it safe to include secret data in the context dict used to render a template in a view?
Is data that is included in the context dict passed to the render function but is not called in the template accessible to the user or their browser? Is it ok to just pass a QuerySet to the template even when some of the fields of the models must be kept secret from the user? I would appreciate a reference to the official Django documentation or any other reliable sources confirming this is safe, if anyone finds one. Code Example models.py: class Riddle(models.Model): question = models.TextField() # show to user solution = models.TextField() # very secret views.py def riddles_list(request): data = Riddle.objects.all() return render(request, 'riddles.html', {'riddles': data}) riddles.html <ul> {% for riddle in riddles %} <li>{{ riddle.question }}</li> {% endfor %} </ul> Is this safe, or does the user has a way of accessing the solution of the riddle? Is the solution now available anywhere except the Django server? A possible approach would be to change the query to: data = Riddle.objects.values('question') Is this considered better code than just fetching the whole object? (for security, efficiency, readability, maintainability etc.) In the real code there are more calls like filter and annotate in the query, and the models have more fields. -
How to implement pyodbc with Django and storing the password for databases?
I developed a Django application, where a user can change the database dynamically through the UI. I tried using Django's integrated database configurations in settings.py but I had to do some workarounds but still faced some weird errors. Therefore I decided to use pyodbc with a connection string to connect to the database in my views.py. The User inputs his database credentials (table, user, password, host, port), which then get saved on a database. Every time a user needs some data following method gets invoked: con = DatabaseConnection.objects.all().first() conn_str = '{}/{}@{}:{}/{}'.format(con.user, con.password, con.host, con.port, con.name) Everything works fine, but how exactly do I store the password(or the rest of the data) correctly? I thought about encrypting and decrypting the password in my views.py but that wouldn't make sense, would it?