Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Listing items by the category they belong to
I'm a complete Newb so please bear with me. I've never used OOP or a framework before. I'm creating a book keeping system where I want the ledgers to be displayed by the category they belong to. Here's my model and it seems to work: class COAGroup(models.Model): Name = models.CharField(max_length=200) def __str__(self): return self.Name class Ledger(models.Model): Name = models.CharField(max_length=200) COAGroup = models.ForeignKey(COAGroup, on_delete=models.CASCADE) def __str__(self): return self.Name I'm working on my first view which should list all the ledgers by the category they belong to. Eg <h2>Some COAGroup Name</h2> <ul> <li>A ledger that belongs to this group</li> <li>Another ledger that belonds to the group</li> <li>And another</li> </ul> <h2>Another COAGroup</h2> <ul> <li>A ledger that belongs to this second group</li> <li>Another ledger</li> </ul> I've written the following view in views.py: def showledgers(request): COAGroups = COAGroup.objects.all() Ledgers = Ledger.objects.all() context = { "COAGroups":COAGroups, "Ledgers":Ledgers, } return render(request,"ListLedgers.html",context) I've managed to get the ledgers to show in ListLedgers.html but I can't figure out how to get them to list by COA Group as per my example. Thank you! -
VS Code: ModuleNotFoundError when using debug
I develop a Django project I ma newbie in Django and VS Code so I "debug" using print() and console.log() which is not efficient... so I really need to be able to debug my code and follow variable value during execution but when I try to run debug I read the VS Code doc about django so I have set the launch.json like that: { // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "name": "Python : Fichier actuel", "type": "python", "request": "launch", "program": "${file}", "console": "integratedTerminal" } { "name": "Python: Django", "type": "python", "request": "launch", "program": "${workspaceFolder}/manage.py", "console": "integratedTerminal", "args": [ "runserver", "--noreload" ], "django": true }, ] } I select Python: Django in the debug configuration list and run my project and have ModuleNotFoundError: No module named 'simple_history' and other... I don't understand because my project works so tierce app are correctly installed in my env It wonder if it could be link to another problem I have since I start using python/VS Code and was not able to fix (I already post on this problem: python can't load on … -
Wagtail: How to Use Directly Video Section and Add Custom fields
{% video self.header_video autoplay controls width=256 %} Through This We Get the Video in Our Page. if we have header_video field in Our Model. But What I want According To the Requirement of Project. I Don't Want To make the VideoChooserPanel Field in My Home Model and use that to upload videos from the Home Fields and Showed into the Page. Because this is not my project requirement. What I Want the Videos section which is available in the Wagtail SidePanel that Uploaded Videos Directly I Want To Access through the Page . I want to use that Directly in my Home Page and In Other Pages Also and a One or More Custom fields I want to add also on that . How Can I Do That . Any Help Will Be Appreciated -
Best practice to share data continuously for specific time period using websockets?
I'm using Django-channels, to send data to the frontend using a while-loop. Code: # This code only executes, after running the newly create command "python manage.py auto_update" While True: if <condition>: break async_to_sync(channel_layer.group_send)( group_name, { 'type': 'auto_update', # this is the name of my consumer method } This is working fine. I want to know, using a while loop to send data is a best practice or not? If not, please suggest the best practice for this scenario to deploy on production. Fetching data from pickle files(size: in KB's). -
.htaccess configuration for Django and Apache on a shared hosting server
I find quite difficult to set up Django on a shared LAMP hosting server. I've been trying to find .htaccess configuration but everything I've found is not clear and didn't work for me. I have manage.py in the root of the domain and then the main project folder with some .py files. I have no access to shell, no access to apache configuration. I have only .htaccess and ftp on my disposal. I know from the hosting provider that Python is available but they don't provide any information about specific configuration for Django. I would have thought that a few lines of code in .htaccess would make it possible. Or is it more complicated than this? Can somebody more experienced help? Thanks. -
How to edit migration file to be fake and not from command line in django
Now at my live DB, there's a table created by another service and will be updated from service_1 while service_2 is retrieving data from it only, I want on service_2 to implement the model representing this db_table but when not responsible for creating it on migration file I know there is /path/to/python manage.py migrate --fake and /path/to/python manage.py migrate --initial-fake but I want the fake migration occurs on the file itself, as per the documentation there's no option to make this at migrations.Migration My first solution was using raw sql which is not bad to me but I found it not readable for other developers, so I was thinking about this solution, Any ideas? -
How to connect Heroku app to my client network?
I have a Heroku app using Django (my first project). There is a button in the website which when clicked will try to send a GET request to a URL which exists within my Client network. I can't access that Client URL outside their Network, like I cannot access from my home Wifi (hope this is because of Firewall). So how do I establish this connection from outside my Client network? I would really appreciate a detailed answer! -
Can't send post request from JavaScript when CSRF_COOKIE_SECURE is enabled
API Endpoint: /api/items/ has authentication_classes = (SessionAuthentication, ) In my Vue.js code I have: getCookie: function (name) { match = document.cookie.match(new RegExp(name + '=([^;]+)')); if (match) return match[1]; return }, ... saveApiCall: function (data) { this.$http.post("/api/items/", data, { headers: { 'X-CSRFToken': this.getCookie('csrftoken') } }).then(function (response) { this.close(); }).catch(function (response) { this.form_errors = response.body; }); }, but it doesn't work when I set these settings: CSRF_COOKIE_SECURE = True SESSION_COOKIE_SECURE = True CSRF_COOKIE_HTTPONLY = True How to send this $http.post request when csrftoken is secure? -
django to serve same static file from different urls
I have a situation where a minified js script tries to include another js file with a hard coded relative path. More precisely : I'm rendering an html page with url pattern path('room/<int:room_id>/', room, name='room'), This page includes the first js lib with <script src="{% static 'js/firstlib.min.js' %}"></script> I have js/firstlib.min.js in my static files dir, thus Django serve http://localhost:8000/static/js/firstlib.min.js correctly. The problem is that firstlib.min.js tries to include tanks/lib/otherlib.js using hardcoded relative path, using http://localhost:8000/room/139/tanks/lib/otherlib.js A dirty hack would be to replace tank/* with /static/tank/* everywhere in firstlib.min.js. But I'wondering if there is a better way to solve this issue, for example by dynamically rewriting url : /room/<int:room_id>/<path>/somescript.js becoming /static/<path>/somescript.js (actually, the first script tries to include several other scripts the same way :-s) -
About converting custom functions in models into annotations in custom managers/querysets
Being new to Django, I'm starting to care a bit about performance of my web application. I'm trying to transform many of my custom functions / properties which were originally in my models to querysets within custom managers. in my model I have: class Shape(models.Model): @property def nb_color(self): return 1 if self.colors=='' else int(1+sum(self.colors.upper().count(x) for x in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ')) def __str__(self): return self.name + "-" + self.constraints @property def image_url(self): return format_html(f'{settings.SVG_DIR}/{self}.svg') @property def image_src(self): return format_html('<img src="{url}"|urlencode />'.format(url = self.image_url)) def image_display(self): return format_html(f'<a href="/static/SVG_shapes/{self}">{self.image_src}"</a>') But I'm not clear on a few points: 1/ is there any pros or cons declaring with the propriety decorator in a django model? 2/ what is the cost of calling a function/property in term of database calls and therefore, is there an added value to use custom managers / querysets and define annotations to simulate my functions at that level? 3/ how would you suggest me to transform my image & nb_color functions into annotations Thanks in advance -
systemd service for django orm standalone python script?
I have a python script that uses django orm: import os from os import sys, path import json import pika parrot_path = "/home/alireza/Workspace/Python/Django/Motosel/parrot/" os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings.base") sys.path.append(parrot_path) os.chdir(parrot_path) # This is so models get loaded. from django.core.wsgi import get_wsgi_application application = get_wsgi_application() def callback(ch, method, properties, body): from sms_service.utils.sms_types import send_submit_service_sms data = json.loads(body) if send_submit_service_sms(data): return True else: return False if __name__ == '__main__': os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings.base") import django django.setup() credentials = pika.PlainCredentials('pika', 'xxx') connection = pika.BlockingConnection(pika.ConnectionParameters('localhost')) channel = connection.channel() result = channel.queue_declare(queue='parrot_queue', durable=True) channel.basic_consume(queue='parrot_queue', auto_ack=True, on_message_callback=callback) print("Listening ...") channel.start_consuming() and this is the systemd service file: [Unit] Description=Parrot RabbitMQ Service After=multi-user.target [Service] Type=simple WorkingDirectory=/home/alireza/Workspace/Python/Django/Motosel/parrot/ ExecStart=/home/alireza/VirtualENVS/parrot/bin/python sms_ervice/scripts/read_queue.py Environment=PYTHONUNBUFFERED=1 Restart=on-failure [Install] WantedBy=multi-user.targets the problem is that i should place all of my django project to the systemd folder, that's not an option. I need a help on running this service file Thank you -
How do I use Jinja2 template in my Sendgrid Transactional Template
Is there a way to include jinja2 templating in Sendgrid template? Am trying to use {% for %} and {% endfor %} in Sendgrid template but it doesn't seem to work. Though email sends successfully but its empty when you open it. HTML Code(placeorder.html): <h3>From: {{name}}</h3> <h3>Email: {{emailFrom}}</h3> <body> <table id="customers"> <tr> <th>Product</th> <th>Quantity</th> <th>Sub Total</th> </tr> {% for order_item in order.items.all %} <tr> <td>{{ order_item.item.title}}</td> <td>{{ order_item.quantity }}</td> <td>&#8358;{{ order_item.get_final_price }}</td> </tr> {% endfor %} <p> <span>Total &#8358;</span> <strong>{{ order.get_total }}</strong> </p> </table> </body> Views.py(Django) name = form.cleaned_data['name'] emailFrom = form.cleaned_data['email'] emailTo = settings.DEFAULT_FROM_EMAIL message = Mail( from_email=emailFrom, to_emails= emailTo , subject='subject', html_content= settings.BASE_DIR + "/templates/placeorder.html") message.dynamic_template_data = { 'name': name, 'email': emailFrom , } message.template_id = '********************************' try: sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY')) response = sg.send(message) messages.success(request, "Thanks, We received your Order message. We will get back to you!.") OrderItem.delete(order) except Exception as e: messages.warning(request, "Sorry, Order message not sent.Please Try Again!.") -
is there a way to execute my python program inside html using django?
enter image description hereSo this is my python code how do i get a value from the html input and store it in "entry_word" ,then run the function rg and return its value in my webpage ... def rg(entry_word): import pronouncing for i in entry_word: from nltk.corpus import words words_list = words.words() if i in words_list: return HttpResponse(i) ... -
How can I store and retrieve Django session variable to/from database?
I have my Django website which is currently being served from two machines, using a load balancer. I want to maintain session correponding to a user from one single machine. I know that I can configure my load balancer to use sticky sessions so that all the requests from a user will be served by the same server. But I want to use session variable to achieve the same. That is how can I store that session variable in a centralised database from which any server can access the session of that user and therefore any server can serve it by using that session variable storage. But I am unable to understand the flow and how will I achieve the same in Django. So my question is how can the session be saved in database for a user, for any server to be able to access it and serve the request accordingly. How will those login() and logout work in this case? -
Load static files for all templates and django (needs update for Django 3.0)
As of django 3.0, they took away the feature that allowed you to not have to put {% load static %} at the beginning of every template. Here's a question & answer that was asked and worked on previous versions: Load static files for all templates in django You could previously just add 'builtins': ['django.contrib.staticfiles.templatetags.staticfiles'] into your template options, and so long as you had {% load static %} in your base.html file, you wouldn't have to add it to any others. Is there another way to not have to add {% load static %} above every template using Django 3.0? -
How to fix "Truncated or oversized response headers received from daemon process" when running a Django application?
I have a Django application that is running on an Apache web server. However, the application throws of the error (found in the error log): Timeout when reading response headers from daemon process 'djangoproject': [Sat Dec 14 06:53:16.317958 2019] [wsgi:error] ... Truncated or oversized response headers received from daemon process My application works but it's turning out to be really slow. This happens very often - especially when I keep refreshing my template. I tried looking into the error and expanding the header limit size in the Apache config file but it didn't resolve my issue. This is my Apache config file: Alias /static /var/myproject/myapp/static <Directory /var/myproject/myapp/static> Require all granted </Directory> Alias /media /var/myproject/myapp/media <Directory /var/myproject/myapp/media> Require all granted </Directory> <Directory /var/myproject/myapp/myapp> #wsgi file lives inside here <Files wsgi.py> Require all granted <Files> </Directory> WSGIScriptAlias / /var/myproject/myapp/myapp/wsgi.py WSGIDaemonProcess djangoproject python-path=/var/myproject/myapp python-home=/var/myproject/myapp/venv WSGIProcessGroup djangoproject Does anyone know how to solve this problem? -
Dealing with additional kwargs in Django models
I want to pass some parameters with kwargs to get_or_create() function in Django models but if there are some additional key-values in kwargs that do not exist in models, an error will apear. Is there any way to pass the dictionary and the function itself handles the additional keys? -
A couple of questions about Django
I just got started with Django and I would like to ask the more experienced devs some questions about. One of the main reasons why I chose to swap to Django is the rest-framework API. Would you say that is good practice to use djoser to take care of auth/register/forgotten passwords and all other features that the library provide or should I code everything by myself? If I want to some columns to the user model such as country, location, phone or others would you recommend me to override the default model or create a new model with a one to one relationship linked to the user? Considering both cases from the question above, will I have to override the registration/update methods or is it gonna sort it out by itself? -
Please provide the api_key in the google-services.json file, Web Browser
I'm trying to send a notification push after saving a product but after pressing Save,this error appears: AuthenticationError at /register/ Please provide the api_key in the google-services.json file Request Method: POST Request URL: http://127.0.0.1:8000/register/ Django Version: 2.2.5 Exception Type: AuthenticationError Exception Value: Please provide the api_key in the google-services.json file Exception Location: C:\Users\chida\AppData\Local\Programs\Python\Python37\lib\site-packages\pyfcm\baseapi.py in init, line 49 Python Executable: C:\Users\chida\AppData\Local\Programs\Python\Python37\python.exe Python Version: 3.7.0 this is the head of my base: <!-- The core Firebase JS SDK is always required and must be listed first --> <script src="https://www.gstatic.com/firebasejs/3.9.0/firebase-app.js"></script> <script src="https://www.gstatic.com/firebasejs/3.9.0/firebase-messaging.js"></script> <script> // Your web app's Firebase configuration var firebaseConfig = { apiKey: "AIzaSyAaMtLcRqXU80pWdGLvh_1l43HIJ2Bn7ls", authDomain: "frikiwaii-9a224.firebaseapp.com", databaseURL: "https://frikiwaii-9a224.firebaseio.com", projectId: "frikiwaii-9a224", storageBucket: "frikiwaii-9a224.appspot.com", messagingSenderId: "801502260469", appId: "1:801502260469:web:634927965960d2963729bc" }; // Initialize Firebase firebase.initializeApp(firebaseConfig); let messaging = firebase.messaging(); navigator.serviceWorker .register('./serviceworker.js') .then(function(register) { messaging.useServiceWorker(register); messaging.requestPermission() .then(function(){ console.log("The user has accepted the Notifications") return messaging.getToken(); }) .then(function(token){ console.log(token); fetch('save-token/',{ method:'post', headers:{ 'Content-Type':'application/json', 'Accept':'application/json' }, body:JSON.stringify({ 'token':token }) }) .then(function(resultado){ console.log("Token saved") }) .catch(function(e){ console.log("Error at trying to save Token") }) }) .catch(function(e){ console.log("The user has not accepted the notifications") }) }) messaging.onMessage(function(payload){ console.log("You have received a Notification") let data = payload; console.log(data); let title = payload.notification.title; let options = { body: payload.notification.body, icon: payload.notification.icon } let mensaje … -
Entry point error when using PostGIS in GeoDjango
I am trying to use GeoDjango in my application. I have followed GeoDjango tutorial and tried to install GeoDjango on windows and install spatial database on postgres with PostGIS. But when I try to run my application following error show up: It is good point to mention that before this error I was trying to solve another error and solved it with this answer. Currently I am using Django 3.0 and GDAL 3.0.0. This is part of my setting file: .... DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'postgis_30_sample', 'USER': 'postgres', 'PASSWORD': 'coa@sg.net', 'HOST': 'localhost', 'PORT': '5432', } } INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.gis', 'first.apps.FirstConfig' ] .... -
TemplateDoesNotExist, urls can't find it
I am newbie in Django using, and I got some problems when I try to entering by URL, problem causes in TemplateDoesNotExist at /ads/products/ ads/product/index.html I checked the directory, and index.html file - is existed there, I can't figure out what I've done not correct. For all answers I will be appreciate. Thanks in advance! app_name = 'ads' urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^ads/$', views.index, name='index'), url(r'^products/$', views.products, name='products'), url(r'^product/(?P<product_id>[0-9]+)/$', views.single_product, name='single_product'), -
Python - Add custom user models in Django admin
I'm working on a project using Python(3.7) and Django(2.2) in which I have implemented my models for multiple user types with custom user model as the base model. Everything working fine except the admin side, I have register these modles to admin but when I try to add an object from admin interface it's giving an error. Here's what I have tried so far: From models.py: class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=254, unique=True) title = models.CharField(max_length=255, blank=False) user_type = models.CharField(max_length=255, choices=USER_TYPE, blank=False) gender = models.CharField(max_length=255, choices=CHOICES, blank=False) contenst = models.CharField(max_length=255, blank=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) last_login = models.DateTimeField(null=True, blank=True) date_joined = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'email' EMAIL_FIELD = 'email' REQUIRED_FIELDS = ['password'] objects = UserManager() def get_absolute_url(self): return "/users/%i/" % (self.pk) class PersonalBelow18(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile') dob = models.DateField(blank=False) customer_id = models.BigIntegerField(blank=False) collection_use_personal_data = models.BooleanField(blank=False) reference_identities = models.ForeignKey(Identities, blank=False, on_delete=models.CASCADE, related_name='refs') class PersonalAbove18(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) dob = models.DateField(blank=False) customer_id = models.BigIntegerField(blank=False) contact_email = models.EmailField(blank=False) reference_identities = models.ForeignKey(Identities, blank=False, on_delete=models.CASCADE) contact_no = PhoneNumberField(blank=True, help_text='Phone number must be entered in the' 'format: \'+999999999\'. Up to 15 digits allowed.') collection_use_personal_data = models.BooleanField(blank=False) class Parent(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) contact_email = models.EmailField(blank=False) customer_id = models.BigIntegerField(blank=True) contact_no … -
django middleware modify response message
I need to write a custom django middleware where i need to modify the response message from the view.Is it possible with process_response method of the middleware something like this class Mymiddlewareclass: def process_response(self, request, response): json.loads(response.content.decode('utf-8'))['data']['message'] = "Modified Message" return response -
Django session deletion effects another django application
I have two applications running on the same server with different ports and with their SQLite DB's are also different which is used to store user sessions data. if request.session.exists(stored_session_key) and stored_session_key != request.session.session_key: Session.objects.get(session_key=stored_session_key).delete() request.user.logged_in_user.session_key = request.session.session_key request.user.logged_in_user.save() I'm using this condition, to delete the previous session of the same user to logout from previous device and keep login in the current device. This was working as expected. But I have two projects with the same logic. Problem: When I open two applications on the same browser(eg: In chrome, tab-1:https://ip_address:8000, tab-2:https://ip_adress:8001), I can able to login into one application at once. When I tried to login application two, the application one is getting logged out. Why this behavior and how to solve it? My assumption: Browser is sending different session_key, to the same running application when I log-in to a new application? -
Remotely manage the number of objects in a model
Let's say I have a model called Players. I want to limit the amount of players to 20 in one of my Django servers. I also have another, main control panel Django server that would manage all my other Django servers. Before I begin with my problem, here's the Django app I'll be using (Thinking of using, let me know if there's a better option out there) [Django Limits][1] . I want to make it so that my Django Projects would ask my main Control Panel for how many Players to allow for this app. I've set up the rest API and everything on the control panel and it has all the models and stuff, but how would I go on about with the Players Django Project itself to make it ask for how many Players to allow? I can't wrap my head around that. Any help would be appreciated. Thank you for taking your time reading, [1]: https://pypi.org/project/django-limits/ "Django Limits" .