Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Best way to secure an API key in Vanilla JS and Django
I am building a simple webapp in Django which makes use of Google Places API. The API is called from main.js file, and the data is displayed on the page. Right now, the main.js file looks like this: ... const apikey_gmaps = "AIzaSyDMjUwEt0bumPTVt1GpfQHrxyz"; var lat = position.coords.latitude; var long = position.coords.longitude; fetch("https://maps.googleapis.com/maps/api/geocode/json?latlng="+lat+","+long+"&key="+**apikey_gmaps**) .then(... ... I want to secure the API key, since I don't want everyone to be use and share my credentials, and break my bank. I have been reading about it lately, and I am able to use .env file in Django(Python) using the Decouple library. I want to use the .env variables in the main.js file. The only solution that I could find was to use dotenv, but that requires NodeJS. Is there any way to pass the API key from .env to Django and then from Django to main.js? Is there a better way of achieving this? -
how to calculate two aggregate fields in different queries : 'dict' object has no attribute 'variable-name' django
i need to subtraction between two aggregate fields in two different queries : class ModelA(models.Model): price = models.IntegerField() #others class ModelB(models.Model): cost = models.IntegerField() #others paid_price = ModelA.objects.filter(status=True).annotate( total_paid = Sum(F('price')), #some more fields ).aggregate( paid = Sum(F('total_paid')) #some more fields ) paid_costs = ModelB.objects.filter(status=True).annotate( total_cost = Sum(F('cost')), #some more fields ).aggregate( t_cost= Sum(F('total_paid')), #some more fields ) i need to calculate t_cost with paid i tried this final_result = paid_price.paid - paid_costs.t_cost but raised this errror: 'dict' object has no attribute 'paid ' is there a way to achieve it ? note : the models dont have connection between each other -
Google Cloud unable to serve static files using Django
I have code deployed in Google Cloud but when I try to access the admin website , style sheets are not found static/admin/css/dashboard.css net::ERR_ABORTED 404 (Not Found) My Static paths STATIC_URL = '/static/' Tries everything , please help -
Dependent dropdown, ['Select a valid choice. That choice is not one of the available choices.'] Error
So I needed a dependent dropdown in my app and I followed this tutorial https://simpleisbetterthancomplex.com/tutorial/2018/01/29/how-to-implement-dependent-or-chained-dropdown-list-with-django.html Here is my forms.py class InvoiceItemForm(forms.ModelForm): class Meta: model = InvoiceItem fields = '__all__' widgets = { 'i_item':forms.Select(attrs={ 'class' : "pro form-control", 'onchange' : "load_batch(this);",}), 'batch':forms.Select(attrs={'class':"batch form-control bg-light"}), } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['i_item'].queryset = Product.objects.order_by('P_Name') #Product is a model, FK self.fields['batch'].queryset = PurchaseItem.objects.none() #PurchaseItem is a model, FK item_id = self.prefix + "-i_item" # I use a formset, so i had to go with this if item_id in self.data: try: print("Entered try in init") itemid= int(self.data.get(item_id)) print("\nITEMID: ",itemid) self.fields['batch'].queryset = PurchaseItem.objects.filter(product_id=itemid,inventory__status__exact="Active").order_by('expiry') #print("\n Init set: ",PurchaseItem.objects.filter(product_id=itemid,inventory__status__exact="Active").order_by('expiry')) print("\n\n init self.fields: ",self.fields['batch'].queryset) except (ValueError, TypeError): print("Entered exception in init") pass # invalid input from the client; ignore and fallback to empty City queryset elif self.instance.pk: print("Entered exception in elif") self.fields['batch'].queryset = self.instance.product.purchaseitem_set.order_by('expiry') print("init: ",self.instance.product.purchaseitem_set.order_by('expiry')) else: print("ELSE in Init") InvoiceItemFormSet = inlineformset_factory( Invoice, InvoiceItem, fk_name='invoice_bill', form=InvoiceItemForm, extra=1, can_delete=False, ) This is my views.py def load_batches(request): item = request.GET.get('item') batchset = PurchaseItem.objects.filter(product_id=item,inventory__status__exact="Active").order_by("expiry") #inventory is a model, i am checking for a condition print("\n\nITEM ID: ",item,"\n\nbatchset: ", batchset) #just an effort to find out the reason return render(request, 'tracks/batchset_dropdown.html', {'batchset': batchset}) my js function load_batch(getid) { console.log(getid) //getid … -
Vue3 cdn not working as Vue2 cdn on Django project
Recently I added Vue2 in my django project using the cdn. I saw Vue3 beta is already available and I want to test it, but the Vue3 cdn is not working as Vue2. The error in the console is saying "Vue is not a constructor". The Vue3 file structure seems totally different from Vue2, a lot of exports/imports (I know it is common in Node.js) I search a bit on the internet and saw something about AMD/CommomJS/UMD javascript cdn structures but I am not sure this is the case... Does anybody knows what can I do to have the Vue3 cdn working as Vue2 cdn on a django project? -
Django Allauth: How to customize confirmation email subject?
I was able to customize the confirmation email HTML template by adding this file into the templates folder: templates/account/email/email_confirmation_signup_message.html Now I'm trying to customize the subject of the email by adding the text I want inside this file: templates/account/email/email_confirmation_signup_subject.txt But it doesn't seem to do anything, I still get the default subject all the time. Does anyone know what I'm doing wrong? Many thanks! -
Sending http request inside django's asynchttpconsumer?
I have an asynchttpconsumer class in my django project that receives webhooks from an external server. during the webhook request, I would like the to send a http request to an authorization server, get the response back, and use that to finish processing the webhook request. I followed this tutorial but extended the code that I have. https://channels.readthedocs.io/en/latest/topics/consumers.html#asynchttpconsumer class frontEndConsumer(AsyncHttpConsumer): async def http_request(self, request): header = self.scope print(header) # connect to auth server conn = http.client.HTTPConnection("https://******.auth0.com", 80) headers = { 'authorization': "Bearer *******************" } print("request get connection") conn.request("GET", "/userinfo", headers=headers) res = conn.getresponse() data = res.read() # do some processing print(data.decode("utf-8")) # do other stuff await self.http_reply(data) return Since I am using an authentication service (auth0), I used their example for getting information back from here: https://auth0.com/docs/quickstart/backend/python/02-using but I keep getting errno -2 on the "conn.request" line: Exception inside application: [Errno -2] Name or service not known File "/home/jeremy/.local/lib/python3.6/site-packages/channels/consumer.py", line 59, in __call__ [receive, self.channel_receive], self.dispatch File "/home/jeremy/.local/lib/python3.6/site-packages/channels/utils.py", line 51, in await_many_dispatch await dispatch(result) File "/home/jeremy/.local/lib/python3.6/site-packages/channels/consumer.py", line 73, in dispatch await handler(message) File "/home/jeremy/Documents/APbackend/myapp/webhook.py", line 59, in http_request conn.request("GET", "/userinfo", headers=headers) File "/usr/lib/python3.6/http/client.py", line 1264, in request self._send_request(method, url, body, headers, encode_chunked) File "/usr/lib/python3.6/http/client.py", line 1310, in _send_request self.endheaders(body, encode_chunked=encode_chunked) … -
Integration of razorpay payment gatway with django application
I am a beginner in django and i want to integrate razorpay with django application but not getting any proper documentation can anyone help me to provide step by step documentation or any github link. Thank you. -
django with apache authorization header doesnot work
I have a django project hosted on Apache2 which has several get, post, put, delete apis that works perfectl fine when I use postman but when I try to hit from the browser the same api only those api works that are not authenticated, When I hit post api with authtoken Authorization: Token abcd1234 I get the following error Access to XMLHttpRequest at 'http://12.232.50.225/api/citymgmt/banner?cityadmin_id=6' from origin 'http://127.0.0.1:4200' has been blocked by CORS policy: Request header field authorization is not allowed by Access-Control-Allow-Headers in preflight response. The auth token works perfectly when I use postman, python requests, google collab, but it doen't work from the browser. my django setting contains INSTALLED_APPS = [ ... 'rest_framework', 'rest_framework.authtoken', 'corsheaders', ] CORS_ORIGIN_ALLOW_ALL = True CORS_ORIGIN_WHITELIST = ( 'http://localhost:8081', 'http://localhost:4200', ) from corsheaders.defaults import default_headers CORS_ALLOW_HEADERS = default_headers + ( 'Authorization', ) MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', ... ] -
No changes detected for makemigrations
I am new to Django. I want to create tables by using models. I have tried to follow this link: https://docs.djangoproject.com/en/3.0/topics/db/models/. I have registered the app and provided connection details of the DB. But when I tried to run makemigrations and migrate, it's not identifying the changes. python manage.py makemigrations No changes detected python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions Running migrations: No migrations to apply. any help would be appriciated. -
Django Form is not displaying inside template file and not getting any error
I am new in Django and creating one blog application and below to my detail post page and trying to display comment form but i am not getting form even i have used csrf also and not getting any error while running server. However other things like buttons and comment is showing in web browser. 1.models.py ######Model related to comment # We required to create a Model to save comments # We required to create a model based form to submit comments # We required to create a view function to process comments and save to the database # We have to edit post_detail.html to display list of comments and add a form to submit # comments class Comment(models.Model): post=models.ForeignKey(Post,related_name='comments',on_delete=models.DO_NOTHING) name=models.CharField(max_length=32) email=models.EmailField() body=models.TextField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) active = models.BooleanField(default=True) #now order we can define. class Meta: ordering=('-created',) #now let me take str if any person want to display comment object. def __str__(self): return 'Commented by {} on {}'.format(self.name,self.post) #Means if any person want to display my comment object sir simply return o/p in above form :) #Now after creating comment model we need to run migration and migrate and need to register inside admin.py from blog.forms import … -
What is the correct way to test django with APIReqFactory or mock?
I want to test with django, but they do not run and I do not understand, that I am wrong, the following error returns: Expected view ActorViewSet to be called with a URL keyword argument named "pk". Fix your URL conf, or set the .lookup_field attribute on the view correctly. My testCase: from rest_framework.test import APITestCase, APIRequestFactory from .views import ActorViewSet class TestActor(APITestCase): def setUp(self): self.factory = APIRequestFactory() self.view = ActorViewSet.as_view({'get': 'list', 'get': 'retrieve', 'post': 'create', 'put': 'update', 'delete': 'destroy'}) self.url = '/actor/' def test_list(self): req = self.factory.get(self.url) res = self.view(req) self.assertEqual(res.status_code, 200, 'expected http code 200' .format(res.status_code) ) def test_get_one(self): self.get_one_url = '/actor/1' req = self.factory.get(self.get_one_url, format='json') res = self.view(req) self.assertEqual(res.status_code, 200, 'expected http code 200' .format(res.status_code) ) def test_create(self): data = {'movie_title': 'type', 'name': 'TCY', 'awards': 5} req = self.factory.post(self.url, data, format='json') res = self.view(req) self.assertEqual(res.status_code, 201, 'exepted created 201' .format(res.status_code) ) def test_put(self): self.get_one_url = '/actor/1' data = {'movie_title': 'type', 'name': 'TCY', 'awards': 3} req = self.factory.put(self.get_one_url, data, format='json') res = self.view(req) self.assertEqual(res.status_code, 204, 'expected http code 204' .format(res.status_code) ) def test_destroy(self): self.get_one_url = '/actor/1' data = {'movie_title': 'type', 'name': 'TCY', 'awards': 3} req = self.factory.delete(self.get_one_url, data, format='json') res = self.view(req) self.assertEqual(res.status_code, 204, 'expected http code 204' … -
Need help in Django Orm query
I have 3 models and they are as follow class Table(models.Model): waiter = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, related_name='restaurant_table') table_no = models.IntegerField() objects = TableManager() class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.CASCADE) food = models.ManyToManyField(OrderFood, related_name='ordered_food') order_status = models.ForeignKey(OrderStatus, on_delete=models.CASCADE) table = models.ForeignKey(Table, on_delete=models.CASCADE) datetime = models.DateTimeField(default=now) class OrderStatus(models.Model): CHOOSE = ( ('Received', 'Received'), ('Cooking', 'Cooking'), ('WaiterHand', 'In Waiter Hand'), ('Delivered', 'Delivered'), ('Paid', 'Payment Completed'), ('Rejected', 'Rejected') ) status = models.CharField(max_length=30, null=False, blank=False, choices=CHOOSE) created_at = models.DateTimeField(auto_now=True) updated_at = models.DateTimeField() Actually I am creating a restaurant management system. So here a restaurant has tables associated with a or more waiter. But I need a new feature that is table status. I mean when an order is actively associated with the table that means that table is booked. Actually that is not a problem as I can do that in many ways. One way is I will count the active order associated with this table and if I found any active order I will return the table is booked. Another way is I will add an extra field with the table that is a flag. This flag store status of tables is booked or not I mean the boolean field. But my question is not … -
Django + Celery "cannot serialize '_io.BufferedReader' object"
While trying to pass a file off to a Celery task, I am sometimes getting the exception "cannot serialize '_io.BufferedReader' object". This seems to be happening with some files and not others. The endpoint is an APIView with the following to launch the task: from celery import signature task = signature( data.get('action'), kwargs={'data': data, 'authorization': authorization, "files": files} ).apply_async() It does work fine when some files are included in the request, but throws the exception for other files. -
Using django with telebot (telegram api)
everyone, I want to use django as framework and telebot as telegram bot api, but have no idea how to make them work together, because I should have two processes -- django server and telegram bot messages handler, that uses same database and other resourses. Where and how should I run these two processes or it'll be easer to choose anoter framework/package? -
Can we use static files without defining STATICFILES_DIRS in django
It's not nice to memorize a variable name to use a framework, is there another way that needs less of our memories? -
SSLError installing Django 2.2 using Pipenv
I am trying to install django to my python 3.6 virtual enviroment using pip env sudo pipenv install --python 3.6 django==2.2 and I get an this error ⠧ Installing django...Error: An error occurred while installing django==2.2! Error text: Could not fetch URL https://pypi.org/simple/django/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max retries exceeded with url: /simple/django/ (Caused by SSLError("Can't connect to HTTPS URL because the SSL module is not available.",)) - skipping WARNING: The directory '/Users/jayshah/Library/Caches/pipenv' or its parent directory is not owned or is not writable by the current user. The cache has been disabled. Check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag. WARNING: pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available. WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.",)': /simple/django/ WARNING: Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.",)': /simple/django/ WARNING: Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL … -
Django dictionary shopping cart
I am trying to delete my dictionary cart in django but it' not work def deleteCart(request, id): myCart = request.session.get('shopcart') if id in myCart.keys(): myCart.pop(id) request.session['shopcart'] = myCart return render(request, 'home/check.html', {'myCart': myCart}) -
how to get the instance created in the viewset, then return it in the response?
como obtener la instancia creada en el viewset, para luego retornarla en la respuesta class SolicitudCrear(generics.CreateAPIView): queryset = Grado.objects.all() serializer_class = GradoSerializer def create(self, request, *args, **kwargs): super(SolicitudCrear, self).create(request, args, kwargs) data = ? return Response( {"data": data}) -
Django model form with additional parameters will not validate
I have looked at the over-dozen SO threads on django validation forms but have not been able to figure out why my form will neither validate nor output any errors. The form is generated off a model and is loaded with two custom parameters item and size_choices. I presume that somehow my form initiation is faulty? I also thought that maybe it's because I make a form on only a subset of the model fields but don't fill all of the model fields out yet, according to django documentation, that shouldn't be an issue since only included fields get validated. Here are the simplified model, form, view, and template codes: the model: class Order(models.Model): # item description item = models.ForeignKey(Item, on_delete=models.CASCADE) itemSizes = [(s,s.upper()) for s in ['xxs','xs','s','m','l','xl','xxl','xxxl','count']] size = models.CharField("Item size", max_length = 5, choices = itemSizes) quantity = models.IntegerField(default=1) class Recipient(models.TextChoices): TEAM = 'TEAM MEMBER' RETAIL = 'RETAIL' recipient = models.CharField(max_length=11, choices = Recipient.choices, default=Recipient.RETAIL) date = models.DateField('date of order',auto_now_add=True) the form: class itemOrderForm(forms.ModelForm): def __init__(self,size_choices = None,item=None ,*args,**kwargs): super().__init__(*args,**kwargs) #itemOrderForm,self if size_choices: self.fields['size'].choices = size_choices self.fields['item'].initial = item self.fields['item'].disabled=True #print("GOT HERE") class Meta: model = Order fields = ('item','size', 'quantity') the view: def orderCart(request): context = {} … -
Django: get rid of the label in model fields
So I have this models: class ProfileImage(models.Model): user = models.OneToOneField( verbose_name=_('User'), to=settings.AUTH_USER_MODEL, related_name='profile', on_delete=models.CASCADE ) avatar = models.ImageField(upload_to='profile_image') How can I get rid of the label "avatar:" -
How to implement chart.js in Django?
I'm trying to visualize my data to a graph using chart.js! However, I have no idea how that's done... Could you program experts help me with this, please? Here's the code I had so far model.py class MarksInputOne(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True) date = models.DateTimeField(auto_now_add=True) mark = models.CharField(max_length=200) def __str__(self): return self.mark views.py def courseOne(request): marks = MarksInputOne.objects.filter(user=request.user) total_assign = TodoList.objects.filter(user=request.user) total = total_assign.count() this = total_assign.filter(category__name="MAT292H1").count() return render(request, 'courses/firstcourse.html', {'marks': marks, 'total_assign': total_assign, 'total': total, 'this': this}) def lineChart(request): labels =[] data = [] queryset = MarksInputOne.objects.values('mark').filter(category__name='MAT292H1').order_by('date') for entry in queryset: labels.append(entry['date']) data.append(entry['mark']) return JsonResponse(data={ 'labels': labels, 'data': data, }) and finally, chart.html, this is actually an example code from chart.js <div class="col"> <div class="col-md"> <h5>Graph</h5> <hr> <div class="card card-body"> <canvas id="chart" width="800" height="400"></canvas> <script> var ctx = document.getElementById('chart').getContext('2d'); var myChart = new Chart(ctx, { type: 'line', data: { labels: [{{data}}], datasets: [{ label: 'Academic Performance', data: [{{ labels }}], fill: false, backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', 'rgba(255, 159, 64, 0.2)' ], borderColor: [ 'rgb(255,99,132)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)', … -
Query parameters in request on Django 3.0.3
I'm putting together an API and need to add query parameters to the URI like https://www.example.com/api/endpoint?search=term&limit=10. My first question is, in Django 3.0, I'd need to use re-path to accomplish parsing out the various parameters, correct? Secondly, the question is about convention. It seems like two of the three APIs I've been working with a lot lately us a convention like: /api/endpoint?paramater1=abc&parameter2=xyz Another uses something like: /api/endpoint?$parameter1=abc&parameter2=abc Looking at some past Django question related to this topic, I see stuff like: /api/endpoint/?parameter1=abc&parameter2=xyz Another post I read was suggesting that parameters should be separated with ;. I guess I'm just curious what the "correct" convention should be either in terms of Django or general concensus. Lastly, it seems to me what I'm trying to accomplish should be a GET request. The front-end sends the user defined parameters (section and startingPage) to the back-end where a PDF is generated matching those parameters. When it is generated, it sends it back to the FE. The PDFs are much too large to generate client-side. GET would be the correct method in the case, correct? -
django-cron: Why is one of my crons not running while my other ones are?
I'm using this Django package django-cron and today one of my crons stopped running. My code runs locally and on staging but not prod and I can't figure out why. My project is running on Docker with Django and MySQL This is what my /etc/crontab looks like #run every 10 minutes */10 * * * * root sudo docker exec backend_1 python manage.py runcrons my_project.cron.Submit #run every 5 minutes */5 * * * * root sudo docker exec backend_1 python manage.py runcrons my_project.cron.Check In the table django_cron_cronjoblog I see my_project.cron.Check running every 5 minutes. This cron works fine. But my my_project.cron.Submit doesnt appear in the table. When I run it manually the first thing I do is a print statement to test but that's not executing. It's been working for the last couple of days and it stopped working today. I can't figure out how to debug and/or test. Cron my_project.cron.Submit does do a lot of calculations that might take longer than 10 minutes. I was thinking maybe a second instance of the cron started and maybe that caused an issue? But i'm not sure and don't know how to check. Can anyone help me out? -
List View Method Flowchart
With my products I wanted to have a buy it now or remove from cart button depending on if the item was already in the cart. Im my trace back I had this issue queryset = kwargs.pop('object_list', self.object_list) AttributeError: 'ProductListView' object has no attribute 'object_list' This is my original code class ProductListView(ListView): model = Product template_name = "products/list.html" # added for pagination context_object_name='object_list' #Default: object_list # print(context_object_name) # paginate_by = 3 def get_context_data(self, *args, **kwargs): context = super(ProductListView, self).get_context_data(*args, **kwargs) cart_obj, new_obj = Cart.objects.new_or_get(self.request) print("get context data") # context = {} context['cart'] = cart_obj return context def get_queryset(self, *args, **kwargs): request = self.request return Product.objects.all() def get(self, request): paginate_by = request.GET.get('paginate_by',6) or 4 data = self.model.objects.all() paginator = Paginator(data, paginate_by) page = request.GET.get('page') try: paginated = paginator.page(page) except PageNotAnInteger: paginated = paginator.page(1) except EmptyPage: paginated = paginator.page(paginator.num_pages) context = self.get_context_data() context['DataPaginated'] = paginated context['paginate_by'] = paginate_by return render(request, self.template_name, context) I fixed the issue by modifying the get_context_data function in the class ProductListView(ListView): def get_context_data(self, *args, **kwargs): self.object_list = super().get_queryset() context = super(ProductListView, self).get_context_data(*args, **kwargs) I examined the code for ListView here https://www.kite.com/python/docs/django.views.generic.ListView. Method Flowchart dispatch() http_method_not_allowed() get_template_names() get_queryset() get_context_object_name() get_context_data() get() render_to_response() I am baffled why adding in super().get_queryset() …