Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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" . -
Django Internal Server Error, when DEBUG = False
I have this relatively famous problem but I just can´t found the solution, when my DEBUG = True everything works fine and then I set it to False and it just doesn't work... And I set also the 'ADMINS = [('my_app', 'my_app@gmail.com')]' and I don't receive any email whit the error instructions. I hope someone can show the light, thanks! """ Django settings for my_app_web project. Generated by 'django-admin startproject' using Django 2.2.7. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os import django_heroku # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ.get('my_app_web_django_secret_key') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False DEBUG_PROPAGATE_EXCEPTIONS = True ALLOWED_HOSTS = ["my_app.herokuapp.com"] SERVER_EMAIL = 'my_app@gmail.com' ADMINS = [('my_app', 'my_app@gmail.com')] CSRF_COOKIE_SECURE = True SESSION_COOKIE_SECURE = True # Application definition INSTALLED_APPS = [ 'clients.apps.ClientsConfig', 'home.apps.HomeConfig', 'crispy_forms', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'storages', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'my_app_web.urls' TEMPLATES … -
Django: Problem with Adding Editing and Deleting Functionality in Django Form
I am learning Django by building an application, called TravelBuddies. It will allow travelers to plan their trip and keep associated travel items (such as bookings, tickets, copy of passport, insurance information, etc), as well as create alerts for daily activities. The application will also able to update local information such as weather or daily news to the traveler. Travelers can also share the travel information with someone or have someone to collaborate with them to plan for the trip. I have created a form that enables the users to add their trip information, like trip name, planner name, co-planner, date etc. However, I can't find a proper way of allowing them to edit and delete the forms. I have seen some videos. But they are not using TemplateView like me. So, I am a bit confused. Here are my codes in forms.py file under addtrip folder: from django import forms from django.contrib.auth.models import User from django.forms import ModelForm from trips.models import Trip class TripForm(ModelForm): class Meta: model = Trip fields = ['trip_name', 'date', 'planner_name', 'add_coplanner', 'trip_description'] class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) class Meta: model = User fields = ['username', 'email', 'password'] Here are my codes in views.py file under … -
Python 3 Django 3.0 Running but not listening or opening port
I am using PyCharm and an instance running in AWS for remote debugging. When I start debugging the server starts and continues to run. However, it is inaccessable and doesn't appear to be grabbing the port. Running with sudo doesn't change anything. When running the app using gunicorn it works perfectly. Pycharm Console ssh://ubuntu@34.204.XXX.X:22/usr/bin/python3 -u /home/ubuntu/.pycharm_helpers/pydev/pydevd.py --multiproc --qt-support=auto --client 0.0.0.0 --port 46691 --file /opt/ctp/cloudportal/manage.py runserver 0.0.0.0:8000 pydev debugger: process 3021 is connecting Connected to pydev debugger (build 193.5233.109) [2019-12-14 03:51:18] 3028 INFO django.utils.autoreload:run_with_reloader:598 - Watching for file changes with StatReloader Performing system checks... /usr/lib/python3/dist-packages/Crypto/Random/Fortuna/FortunaGenerator.py:28: SyntaxWarning: "is" with a literal. Did you mean "=="? if sys.version_info[0] is 2 and sys.version_info[1] is 1: /usr/lib/python3/dist-packages/Crypto/Random/Fortuna/FortunaGenerator.py:28: SyntaxWarning: "is" with a literal. Did you mean "=="? if sys.version_info[0] is 2 and sys.version_info[1] is 1: System check identified no issues (0 silenced). December 14, 2019 - 03:51:19 Django version 3.0, using settings 'CloudPortal.settings_dev' Starting development server at http://0.0.0.0:8000/ Quit the server with CONTROL-C. Linux Server ubuntu@ip-192-168-128-120:~$ sudo ps -alf F S UID PID PPID C PRI NI ADDR SZ WCHAN STIME TTY TIME CMD 0 S ubuntu 3028 3021 3 80 0 - 72808 poll_s 03:51 pts/0 00:00:09 /usr/bin/python3 /opt/ctp/cloudportal/manage.py runserver 0.0.0.0:8000 4 S root 3139 … -
Hitting 500 error on django with debug=False even with ALLOWED_HOSTS=["*"]
I am getting 500 errors on every page I try to go with. The only thing that i'm changing is DEBUG to False. Here is my config: SECRET_KEY = os.environ.get("SECRET_KEY", "0$ke!x1bz5cj0mpzo1zfx4omw-c9iqw%m95zb)(2@ddg5s+3!f") ALLOWED_HOSTS = ['*'] # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False # Application definition INSTALLED_APPS = [ 'posts', # Contains all dynamic and static pages related to posts 'courses', # Contains all dynamic and static pages related to courses and modules 'pages', # Contains all static pages that are not post related 'markdownx', # Allows for editing and creating markdown content 'jet.dashboard', 'jet', # Django admin theme override 'pwa', # Sets app to be PWA compliant 'whitenoise.runserver_nostatic', # Serving static files 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] Literally every answer i've seen says just set your ALLOWED_HOSTS to ['*'], as you can see i've done that and still no dice. I checked the Docs and they are pretty sparse on what else DEBUG mode effects there is a section of the docs that says: As a security measure, Django will not include settings that might be sensitive, such as SECRET_KEY. Specifically, it will exclude any setting whose name includes any of the … -
django, update modified_at when doing update()
Following field gets updated whenever model_obj.save() happens. modified_at = models.DateTimeField(auto_now=True, db_index=True) However, it is not updated when doing MyModel.objects.filter(id=model_obj.id).update(**kwargs) Is there a way to somehow enforce updating modified_at? -
Is Django REST framework suppose to be public?
I recently found some security holes in my university website. Among other issues was that, a page for viewing and managing api requests, using Django REST framework was found to be public. There were option to generate manage oauth tokens, and different things like that. I am planning to report the issues together soon. Is this actually a bug or is it suppose to be public? If it is a bug, what are the possible consequences? Is it to be taken seriously? -
django post api through postman
**Hi when I try to hit the post api from postman I am receiving the response from API but the request is not received from postman when I print the request it showing but not the data and i attached the screenshot of postman ** from django.shortcuts import render from django.http import HttpResponse from django.core.mail import send_mail from django.views.decorators.csrf import csrf_exempt # Create your views here. @csrf_exempt def email(request): print(request) subject = request.POST.get('subject', 'hello') body = request.POST.get('body', 'very bad') senderEmail = request.POST.get('senderEmail', 'my_email@gmail.com') send_mail(subject, body, 'sender@gmail.com', [senderEmail], fail_silently=False) return HttpResponse("Email Send.") -
CSRF verification failed only in production, Django
{% csrf_token %} is set. Tried @ensure_csrf_cookie as well. code: views.py: https://bpaste.net/show/UANTI template (landing.html): https://bpaste.net/show/P5YJA form_fields.html: https://bpaste.net/show/UQZKQ Can anyone help? Thanks in advance. -
django-cacheops... what is the "ops"?
I've searched, but I can't find anything that explains this. I know I'm risking a downvote here, but what is meant by "ops" with django-cacheops? https://github.com/Suor/django-cacheops I would think it's just a name, but sentences such as ...Here you can specify which ops should be cached... and ...You can pass any subset of this ops to... and ...with non-empty ops is... make me think I should know what 'ops' is... But the context clues aren't helping, and after reading the documentation and searching the internets, I feel like I'm missing something very obvious, and that I'm not going to get the full benefit of this tool... -
Structure in Django tutorial does not match match my strucuture
Starting a new project and realized that the structure for tutorial and my structure do not match. It looks like a directory was created for the myproject and a directory AND a file were created for myapp...I don't understand. Is this correct? Tutorial structure shows: mysite/ manage.py mysite/ init.py settings.py urls.py asgi.py wsgi.py My structure shows: myapp myappp __init__.py settings.py urls.py wsgi.py manage.py```